天天看點

【譯】用Java建立你的第一個區塊鍊-part1

轉自 https://longfeizheng.github.io/2018/03/10/%E7%94%A8Java%E5%88%9B%E5%BB%BA%E4%BD%A0%E7%9A%84%E7%AC%AC%E4%B8%80%E4%B8%AA%E5%8C%BA%E5%9D%97%E9%93%BE-part1/#

前言

區塊鍊是分布式資料存儲、點對點傳輸、共識機制、加密算法等計算機技術的新型應用模式。所謂共識機制是區塊鍊系統中實作不同節點之間建立信任、擷取權益的數學算法 。 

本系列教程旨在幫助你了解如何開發區塊鍊技術。

本章目标

建立你第一個非常基本的區塊鍊 

實作一個簡單的工作量證明系統即挖礦 

在此基礎上進行擴充 

(我會假設你對面向對象程式設計有基本的了解)

值得注意的是,這裡建立的區塊鍊并不是功能完全的完全适合應用與生産的區塊鍊,相反隻是為了幫助你更好的了解區塊鍊的概念。

https://raw.githubusercontent.com/longfeizheng/longfeizheng.github.io/master/images/qukuai/qukuai01.gif

建立區塊鍊

區塊鍊就是一串或者是一系列區塊的集合,類似于連結清單的概念,每個區塊都指向于後面一個區塊,然後順序的連接配接在一起。那麼每個區塊中的内容是什麼呢?在區塊鍊中的每一個區塊都存放了很多很有價值的資訊,主要包括三個部分:自己的數字簽名,上一個區塊的數字簽名,還有一切需要加密的資料(這些資料在比特币中就相當于是交易的資訊,它是加密貨币的本質)。每個數字簽名不但證明了自己是特有的一個區塊,而且指向了前一個區塊的來源,讓所有的區塊在鍊條中可以串起來,而資料就是一些特定的資訊,你可以按照業務邏輯來儲存業務資料。

https://raw.githubusercontent.com/longfeizheng/longfeizheng.github.io/master/images/qukuai/qukuai01.png

這裡的hash指的就是數字簽名

是以每一個區塊不僅包含前一個區塊的hash值,同時包含自身的一個hash值,自身的hash值是通過之前的hash值和資料data通過hash計算出來的。如果前一個區塊的資料一旦被篡改了,那麼前一個區塊的hash值也會同樣發生變化(因為資料也被計算在内),這樣也就導緻了所有後續的區塊中的hash值。是以計算和比對hash值會讓我們檢查到目前的區塊鍊是否是有效的,也就避免了資料被惡意篡改的可能性,因為篡改資料就會改變hash值并破壞整個區塊鍊。 

定義區塊鍊的類快

import java.util.Date;

public class Block {

public String hash;     public String previousHash;     private String data; //our data will be a simple message.     private long timeStamp; //as number of milliseconds since 1/1/1970.     //Block Constructor.     public Block(String data,String previousHash ) {         this.data = data;         this.previousHash = previousHash;         this.timeStamp = new Date().getTime();     }           
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

正如你可以看到我們的基本塊包含String hash,它将儲存我們的數字簽名。變量previoushash儲存前一個塊的hash和String data來儲存我們的塊資料

建立數字簽名

熟悉加密算法的朋友們,Java方式可以實作的加密方式有很多,例如BASE、MD、RSA、SHA等等,我在這裡選用了SHA256這種加密方式,SHA(Secure Hash Algorithm)安全雜湊演算法,這種算法的特點是資料的少量更改會在Hash值中産生不可預知的大量更改,hash值用作表示大量資料的固定大小的唯一值,而SHA256算法的hash值大小為256位。之是以選用SHA256是因為它的大小正合适,一方面産生重複hash值的可能性很小,另一方面在區塊鍊實際應用過程中,有可能會産生大量的區塊,而使得資訊量很大,那麼256位的大小就比較恰當了。

下面我建立了一個StringUtil方法來友善調用SHA256算法

import java.security.MessageDigest;

public class StringUtil { 

//Applies Sha256 to a string and returns the result. 

public static String applySha256(String input){ 

try { 

MessageDigest digest = MessageDigest.getInstance(“SHA-256”); 

//Applies sha256 to our input, 

byte[] hash = digest.digest(input.getBytes(“UTF-8”)); 

StringBuffer hexString = new StringBuffer(); // This will contain hash as hexidecimal 

for (int i = 0; i < hash.length; i++) { 

String hex = Integer.toHexString(0xff & hash[i]); 

if(hex.length() == 1) hexString.append(‘0’); 

hexString.append(hex); 

return hexString.toString(); 

catch(Exception e) { 

throw new RuntimeException(e); 

或許你完全不了解上述代碼的含義,但是你隻要了解所有的輸入調用此方法後均會生成一個獨一無二的hash值(數字簽名),而這個hash值在區塊鍊中是非常重要的。

接下來讓我們在Block類中應用 方法 applySha256 方法,其主要的目的就是計算hash值,我們計算的hash值應該包括區塊中所有我們不希望被惡意篡改的資料,在我們上面所列的Block類中就一定包括previousHash,data和timeStamp,

public String calculateHash() { 

String calculatedhash = StringUtil.applySha256( 

previousHash + 

Long.toString(timeStamp) + 

data 

); 

return calculatedhash; 

然後把這個方法加入到Block的構造函數中去

public Block(String data,String previousHash ) { 

this.data = data; 

this.previousHash = previousHash; 

this.timeStamp = new Date().getTime(); 

this.hash = calculateHash(); //Making sure we do this after we set the other values. 

測試

在主方法中讓我們建立一些區塊,并把其hash值列印出來,來看看是否一切都在我們的掌控中。

https://raw.githubusercontent.com/longfeizheng/longfeizheng.github.io/master/images/qukuai/qukuai.gif

第一個塊稱為創世紀區塊,因為它是頭區塊,是以我們隻需輸入“0”作為前一個塊的previous hash。

public class NoobChain {

public static void main(String[] args) {         Block genesisBlock = new Block("Hi im the first block", "0");         System.out.println("Hash for block 1 : " + genesisBlock.hash);         Block secondBlock = new Block("Yo im the second block",genesisBlock.hash);         System.out.println("Hash for block 2 : " + secondBlock.hash);         Block thirdBlock = new Block("Hey im the third block",secondBlock.hash);         System.out.println("Hash for block 3 : " + thirdBlock.hash);     }           
  • 13

列印:

Hash for block 1: f6d1bc5f7b0016eab53ec022db9a5d9e1873ee78513b1c666696e66777fe55fb 

Hash for block 2: 6936612b3380660840f22ee6cb8b72ffc01dbca5369f305b92018321d883f4a3 

Hash for block 3: f3e58f74b5adbd59a7a1fc68c97055d42e94d33f6c322d87b29ab20d3c959b8f 

每一個區塊都必須要有自己的資料簽名即hash值,這個hash值依賴于自身的資訊(data)和上一個區塊的數字簽名(previousHash),但這個還不是區塊鍊,下面讓我們存儲區塊到數組中,這裡我會引入gson包,目的是可以用json方式檢視整個一條區塊鍊結構。

import java.util.ArrayList; 

import com.google.gson.GsonBuilder;

public static ArrayList<Block> blockchain = new ArrayList<Block>();      public static void main(String[] args) {             //add our blocks to the blockchain ArrayList:         blockchain.add(new Block("Hi im the first block", "0"));                 blockchain.add(new Block("Yo im the second block",blockchain.get(blockchain.size()-1).hash));          blockchain.add(new Block("Hey im the third block",blockchain.get(blockchain.size()-1).hash));         String blockchainJson = new GsonBuilder().setPrettyPrinting().create().toJson(blockchain);               System.out.println(blockchainJson);     }           

這樣的輸出結構就更類似于我們所期待的區塊鍊的樣子。

檢查區塊鍊的完整性

在主方法中增加一個isChainValid()方法,目的是循環區塊鍊中的所有區塊并且比較hash值,這個方法用來檢查hash值是否是于計算出來的hash值相等,同時previousHash值是否和前一個區塊的hash值相等。或許你會産生如下的疑問,我們就在一個主函數中建立區塊鍊中的區塊,是以不存在被修改的可能性,但是你要注意的是,區塊鍊中的一個核心概念就是去中心化,每一個區塊可能是在網絡中的某一個節點中産生的,是以很有可能某個節點把自己節點中的資料修改了,那麼根據上述的理論資料改變會導緻整個區塊鍊的破裂,也就是區塊鍊就無效了。

public static Boolean isChainValid() { 

Block currentBlock; 

Block previousBlock;

//loop through blockchain to check hashes:     for(int i=1; i < blockchain.size(); i++) {         currentBlock = blockchain.get(i);         previousBlock = blockchain.get(i-1);         //compare registered hash and calculated hash:         if(!currentBlock.hash.equals(currentBlock.calculateHash()) ){             System.out.println("Current Hashes not equal");                      return false;         }         //compare previous hash and registered previous hash         if(!previousBlock.hash.equals(currentBlock.previousHash) ) {             System.out.println("Previous Hashes not equal");             return false;         }     }     return true;           
  • 14
  • 15
  • 16
  • 17

任何區塊鍊中區塊的一絲一毫改變都會導緻這個函數傳回false,也就證明了區塊鍊無效了。

在比特币網絡中所有的網絡節點都分享了它們各自的區塊鍊,然而最長的有效區塊鍊是被全網所統一承認的,如果有人惡意來篡改之前的資料,然後建立一條更長的區塊鍊并全網釋出呈現在網絡中,我們該怎麼辦呢?這就涉及到了區塊鍊中另外一個重要的概念工作量證明,這裡就不得不提及一下hashcash,這個概念最早來自于Adam Back的一篇論文,主要應用于郵件過濾和比特币中防止雙重支付。

https://raw.githubusercontent.com/longfeizheng/longfeizheng.github.io/master/images/qukuai/qukuai02.gif

挖礦

這裡我們要求挖礦者做工作量證明,具體的方式是在區塊中嘗試不同的參數值直到它的hash值是從一系列的0開始的。讓我們添加一個名為nonce的int類型以包含在我們的calculatehash()方法中,以及需要的mineblock()方法

public String hash;     public String previousHash;      private String data; //our data will be a simple message.     private long timeStamp; //as number of milliseconds since 1/1/1970.     private int nonce;     //Block Constructor.       public Block(String data,String previousHash ) {         this.data = data;         this.previousHash = previousHash;         this.timeStamp = new Date().getTime();         this.hash = calculateHash(); //Making sure we do this after we set the other values.     }     //Calculate new hash based on blocks contents     public String calculateHash() {         String calculatedhash = StringUtil.applySha256(                  previousHash +                 Long.toString(timeStamp) +                 Integer.toString(nonce) +                  data                  );         return calculatedhash;     }     public void mineBlock(int difficulty) {         String target = new String(new char[difficulty]).replace('\0', '0'); //Create a string with difficulty * "0"          while(!hash.substring( 0, difficulty).equals(target)) {             nonce ++;             hash = calculateHash();         }         System.out.println("Block Mined!!! : " + hash);     }           
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

mineBlock()方法中引入了一個int值稱為difficulty難度,低的難度比如1和2,普通的電腦基本都可以馬上計算出來,我的建議是在4-6之間進行測試,普通電腦大概會花費3秒時間,在萊特币中難度大概圍繞在442592左右,而在比特币中每一次挖礦都要求大概在10分鐘左右,當然根據所有網絡中的計算能力,難度也會不斷的進行修改。

我們在NoobChain類 中增加difficulty這個靜态變量。

public static int difficulty = 5; 

這樣我們必須修改主方法中讓建立每個新區塊時必須觸發mineBlock()方法,而isChainValid()方法用來檢查每個區塊的hash值是否正确,整個區塊鍊是否是有效的。

public static ArrayList<Block> blockchain = new ArrayList<Block>();     public static int difficulty = 5;     public static void main(String[] args) {             //add our blocks to the blockchain ArrayList:         blockchain.add(new Block("Hi im the first block", "0"));         System.out.println("Trying to Mine block 1... ");         blockchain.get(0).mineBlock(difficulty);         blockchain.add(new Block("Yo im the second block",blockchain.get(blockchain.size()-1).hash));         System.out.println("Trying to Mine block 2... ");         blockchain.get(1).mineBlock(difficulty);         blockchain.add(new Block("Hey im the third block",blockchain.get(blockchain.size()-1).hash));         System.out.println("Trying to Mine block 3... ");         blockchain.get(2).mineBlock(difficulty);             System.out.println("\nBlockchain is Valid: " + isChainValid());         String blockchainJson = new GsonBuilder().setPrettyPrinting().create().toJson(blockchain);         System.out.println("\nThe block chain: ");         System.out.println(blockchainJson);     }     public static Boolean isChainValid() {         Block currentBlock;          Block previousBlock;         String hashTarget = new String(new char[difficulty]).replace('\0', '0');         //loop through blockchain to check hashes:         for(int i=1; i < blockchain.size(); i++) {             currentBlock = blockchain.get(i);             previousBlock = blockchain.get(i-1);             //compare registered hash and calculated hash:             if(!currentBlock.hash.equals(currentBlock.calculateHash()) ){                 System.out.println("Current Hashes not equal");                          return false;             }             //compare previous hash and registered previous hash             if(!previousBlock.hash.equals(currentBlock.previousHash) ) {                 System.out.println("Previous Hashes not equal");                 return false;             }             //check if hash is solved             if(!currentBlock.hash.substring( 0, difficulty).equals(hashTarget)) {                 System.out.println("This block hasn't been mined");                 return false;             }         }         return true;     }           
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53

Connected to the target VM, address: ‘127.0.0.1:61863’, transport: ‘socket’ 

Trying to Mine block 1… 

Block Mined!!! : 0000016667d4240e9c30f53015310b0ec6ce99032d7e1d66d670afc509cab082 

Trying to Mine block 2… 

Block Mined!!! : 000002ea55735bea4cac7e358c7b0d8d81e8ca24021f5f85211bf54fd4ac795a 

Trying to Mine block 3… 

Block Mined!!! : 000000576987e5e9afbdf19b512b2b7d0c56db0e6ca49b3a7e638177f617994b

Blockchain is Valid: true 

“hash”: “0000016667d4240e9c30f53015310b0ec6ce99032d7e1d66d670afc509cab082”, 

“previousHash”: “0”, 

“data”: “first”, 

“timeStamp”: 1520659506042, 

“nonce”: 618139 

}, 

“hash”: “000002ea55735bea4cac7e358c7b0d8d81e8ca24021f5f85211bf54fd4ac795a”, 

“previousHash”: “0000016667d4240e9c30f53015310b0ec6ce99032d7e1d66d670afc509cab082”, 

“data”: “second”, 

“timeStamp”: 1520659508825, 

“nonce”: 1819877 

“hash”: “000000576987e5e9afbdf19b512b2b7d0c56db0e6ca49b3a7e638177f617994b”, 

“previousHash”: “000002ea55735bea4cac7e358c7b0d8d81e8ca24021f5f85211bf54fd4ac795a”, 

“data”: “third”, 

“timeStamp”: 1520659515910, 

“nonce”: 1404341 

經過測試增加一個新的區塊即挖礦必須花費一定時間,大概是3秒左右,你可以提高difficulty難度來看,它是如何影響資料難題所花費的時間的

如果有人在你的區塊鍊系統中惡意篡改資料:

他們的區塊鍊是無效的。 

他們無法建立更長的區塊鍊 

網絡中誠實的區塊鍊會在長鍊中更有時間的優勢 

因為篡改的區塊鍊将無法趕上長鍊和有效鍊,除非他們比你網絡中所有的節點擁有更大的計算速度,可能是未來的量子計算機或者是其他什麼。

你已經完成了你的基本區塊鍊!

https://raw.githubusercontent.com/longfeizheng/longfeizheng.github.io/master/images/qukuai/qukuai03.gif

你的區塊鍊:

有很多區塊組成用來存儲資料 

有數字簽名讓你的區塊鍊連結在一起 

需要挖礦的工作量證明新的區塊 

可以用來檢查資料是否是有效的同時是未經篡改的 

https://raw.githubusercontent.com/longfeizheng/longfeizheng.github.io/master/images/qukuai/qukuai04.gif

原文連結:Creating Your First Blockchain with Java. Part 1.

代碼下載下傳

從我的 github 中下載下傳,

https://github.com/longfeizheng/blockchain-java

原文釋出時間為:2018年03月19日

本文作者:微紅W

本文來源:

CSDN

,如需轉載請聯系原作者。