view src/main/java/christie/blockchain/BlockHeader.java @ 146:0ef25958ac04

add transaction
author akahori
date Mon, 07 Jan 2019 16:02:26 +0900
parents 694ea96a557a
children cd2fab84cd8b
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 difficulty;

    private long number;

    private long timestamp;

    private long nonce;

    HashUtil hashUtil = new HashUtil();

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

    public byte[] getParamByteArray(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(getParamByteArray(true));
    }

    public byte[] getByteArrayWithoutNonce(){

        return getParamByteArray(false);
    }

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

    public long getTimestamp() {
        return timestamp;
    }

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

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

    public void setNumber(long number) {
        this.number = number;
    }

    public long getNumber() {
        return number;
    }

    public void setDifficulty(long difficulty) {
        this.difficulty = difficulty;
    }

    public long getDifficulty() {
        return difficulty;
    }
}