Mercurial > hg > Database > Christie
changeset 109:2e64b927388c
fix add BlockHeader.java
author | akahori |
---|---|
date | Mon, 05 Nov 2018 10:16:28 +0900 |
parents | 31f87de2a1d4 |
children | eab161e557bd |
files | src/main/java/christie/blockchain/BlockHeader.java |
diffstat | 1 files changed, 81 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/java/christie/blockchain/BlockHeader.java Mon Nov 05 10:16:28 2018 +0900 @@ -0,0 +1,81 @@ +package christie.blockchain; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.math.BigInteger; +import java.nio.charset.Charset; + +public class BlockHeader { + + private byte[] presentHash; + + private byte[] parentHash; + + private long timestamp; + + private long nonce; + + public BlockHeader(byte[] parentHash, long timestamp) { + this.parentHash = parentHash; + this.timestamp = timestamp; + this.presentHash = calcHash(); + } + + public byte[] calcHash(){ + HashUtil hashUtil = new HashUtil(); + + byte[] timestampByte = BigInteger.valueOf(this.timestamp).toByteArray(); + + byte[] nonceByte = BigInteger.valueOf(this.nonce).toByteArray(); + + ByteArrayOutputStream output = new ByteArrayOutputStream(); + + try { + output.write(parentHash); + output.write(timestampByte); + output.write(nonceByte); + } catch (IOException e) { + e.printStackTrace(); + } + + return hashUtil.sha256(output.toByteArray()); + + } + + public byte[] getParentHash() { + return parentHash; + } + + public byte[] getPresentHash() { + if(this.presentHash == null){ + this.presentHash = calcHash(); + } + return this.presentHash; + } + + + public long getTimestamp() { + return timestamp; + } + + public void setTimestamp(long timestamp) { + this.timestamp = timestamp; + } + + public void mineBlock(int difficulty) { + String target = new String(new char[difficulty]).replace('\0', '0'); + String hashStr = new String(presentHash, Charset.forName("utf-16")); + + while(!hashStr.substring( 0, difficulty).equals(target)) { + this.nonce ++; + this.presentHash = calcHash(); + hashStr = new String(this.presentHash, Charset.forName("utf-16")); + } + System.out.println("Block Mined!!! : " + hashStr); + } + + public long getNonce(){ + return this.nonce; + } + +}