view src/main/java/christie/blockchain/BlockHeader.java @ 121:8949d0ecf1f6

refactor Topology
author akahori
date Tue, 11 Dec 2018 15:46:09 +0900
parents eab161e557bd
children 694ea96a557a
line wrap: on
line source

package christie.blockchain;

import org.bouncycastle.util.BigIntegers;

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;

    HashUtil hashUtil = new HashUtil();

    public BlockHeader(byte[] parentHash, long timestamp) {
        this.parentHash = parentHash;
        this.timestamp = timestamp;
    }

    public byte[] getHash(boolean withNonce){

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        byte[] timestampByte = BigInteger.valueOf(this.timestamp).toByteArray();

        try {
            output.write(parentHash);
            output.write(timestampByte);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(withNonce){
            byte[] nonceByte = BigInteger.valueOf(this.nonce).toByteArray();
            try {
                output.write(nonceByte);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return output.toByteArray();

    }

    public byte[] getParentHash() {
        return parentHash;
    }

    public byte[] getPresentHash() {
        return hashUtil.sha256(getHash(true));
    }

    public byte[] getPresentHashWithoutNonce(){
        return getHash(false);
    }

    public long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }

    public void setNonce(long nonce) { this.nonce = nonce; }

    public long getNonce(){
        return this.nonce;
    }

}