public String hash; public String previousHash; private String data; //our data will be a simple message. privatelong timeStamp; //as number of milliseconds since 1/1/1970.
public String calculateHash() { Stringcalculatedhash= StringUtil.applySha256( previousHash + Long.toString(timeStamp) + data ); return calculatedhash; }
 现在,让我们将这个方法添加到 Block 的构造函数中
1 2 3 4 5 6
publicBlock(String data,String previousHash ) { this.data = data; this.previousHash = previousHash; this.timeStamp = newDate().getTime(); this.hash = calculateHash(); //Making sure we do this after we set the other values. }
publicstaticvoidmain(String[] args) { BlockgenesisBlock=newBlock("Hi im the first block", "0"); System.out.println("Hash for block 1 : " + genesisBlock.hash); BlocksecondBlock=newBlock("Yo im the second block",genesisBlock.hash); System.out.println("Hash for block 2 : " + secondBlock.hash); BlockthirdBlock=newBlock("Hey im the third block",secondBlock.hash); System.out.println("Hash for block 3 : " + thirdBlock.hash); } }
publicstaticvoidmain(String[] args) { //add our blocks to the blockchain ArrayList: blockchain.add(newBlock("Hi im the first block", "0")); blockchain.add(newBlock("Yo im the second block",blockchain.get(blockchain.size()-1).hash)); blockchain.add(newBlock("Hey im the third block",blockchain.get(blockchain.size()-1).hash)); StringblockchainJson=newGsonBuilder().setPrettyPrinting().create().toJson(blockchain); System.out.println(blockchainJson); }
publicclassBlock { public String hash; public String previousHash; private String data; //our data will be a simple message. privatelong timeStamp; //as number of milliseconds since 1/1/1970. privateint nonce; //Block Constructor. publicBlock(String data,String previousHash ) { this.data = data; this.previousHash = previousHash; this.timeStamp = newDate().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() { Stringcalculatedhash= StringUtil.applySha256( previousHash + Long.toString(timeStamp) + Integer.toString(nonce) + data ); return calculatedhash; } publicvoidmineBlock(int difficulty) { Stringtarget=newString(newchar[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); } }