view src/main/java/christie/blockchain/Transaction.java @ 198:dd3c0ba6a0a6

fix topology manager
author akahori
date Sat, 09 Mar 2019 21:53:37 +0900
parents cd2fab84cd8b
children
line wrap: on
line source

package christie.blockchain;

import org.msgpack.annotation.Message;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.PrivateKey;
import java.security.PublicKey;

@Message
public class Transaction {
    private byte[] hash;

    private long nonce;

    private PublicKey sendAddress;

    private PublicKey receiveAddress;

    private String data;

    private long timestamp;

    private byte[] signature;

    ECKey ecKey = new ECKey();


    //public ArrayList<TransactionInput> inputs = new ArrayList<TransactionInput>();
    //public ArrayList<TransactionOutput> outputs = new ArrayList<TransactionOutput>();


    public Transaction(PublicKey sendAddress, PublicKey receiveAddress, String data){
        this.sendAddress = sendAddress;
        this.receiveAddress = receiveAddress;
        this.data = data;

    }
/*
    public Transaction(byte[] from, byte[] to, byte[] value,  ArrayList<TransactionInput> inputs) {
        this.sendAddress = from;
        this.receiveAddress = to;
        this.value = value;
        this.inputs = inputs;
    }
*/

    public byte[] getParamByteArray(){

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        byte[] timestampByte = BigInteger.valueOf(this.timestamp).toByteArray();
        byte[] nonceByte = BigInteger.valueOf(this.nonce).toByteArray();
        try {
            output.write(sendAddress.getEncoded());
            output.write(receiveAddress.getEncoded());
            output.write(nonceByte);
            output.write(timestampByte);
            output.write(signature);
        } catch (IOException e) {
            e.printStackTrace();
        }


        return output.toByteArray();

    }

    public byte[] gethash() {

        return HashUtil.sha256(getParamByteArray());
    }

    public void generateSignature(PrivateKey privateKey) {
        ByteArrayOutputStream _data = new ByteArrayOutputStream();
        try {
            _data.write(sendAddress.getEncoded());
            _data.write(receiveAddress.getEncoded());
            _data.write(data.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        signature = ecKey.applyECDSASig(privateKey, _data.toByteArray());
    }
    //Verifies the data we signed hasnt been tampered with
    public boolean verifiySignature() {
        ByteArrayOutputStream _data = new ByteArrayOutputStream();
        try {
            _data.write(sendAddress.getEncoded());
            _data.write(receiveAddress.getEncoded());
            _data.write(data.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ecKey.verifyECDSASig(sendAddress, _data.toByteArray(), signature);
    }




}