All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.tdchain.Block Maven / Gradle / Ivy

There is a newer version: 3.0.1.TD1
Show newest version
/*
 * Copyright (c) 2017 Beijing Tiande Technology Co., Ltd.
 * All Rights Reserved.
 */
package cn.tdchain;

import cn.tdchain.cipher.rsa.Sha256Util;
import cn.tdchain.jbcc.BlockException;
import cn.tdchain.jbcc.MerkleUtil;
import cn.tdchain.jbcc.TransUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Description: 天德区账本Block实体
 *
 * @author xiaoming
 * 2019年4月18日
 */
public class Block extends BlockHead {
    protected List trans; // 交易列表

    public List getTrans() {
        return trans;
    }

    public void setTrans(List trans) {
        this.trans = trans;
    }

    /**
     * block自身检查,验证hash、merkle_tree是否正确
     */
    public void check() {
        // 1.验证 merkle_tree
        List t_list = this.getTrans();
        if (t_list == null || t_list.size() == 0) {
            throw new BlockException("block list is null.");
        }

        List blockHashList = new ArrayList<>(this.getCount());
        for (T trans : t_list) {
            String hash = TransUtil.getHash(trans);
            blockHashList.add(hash);//累加全部交易hash
        }

        String merkleRoot = MerkleUtil.getMerkleRoot(blockHashList);
        if (getMerkleRoot() == null || !merkleRoot.equals(getMerkleRoot())) {
            throw new BlockException("block merkle root error.");
        }

        // 2.验证 hash
        String hash = Sha256Util.hash(getMerkleRoot() + getPreHash() + getTimestamp());
        if (getHash() == null || !getHash().equals(hash)) {
            throw new BlockException("block hash error.");
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy