如何使用上一个块的哈希值正确链接2个块?

时间:2019-03-20 03:38:58

标签: c++ pointers hash blockchain

我是Blockchain的新手,并且想自己用C ++实现基本的Blockchain。我正在对一个链表进行类比,想知道,我到底如何使用散列而不是指针将块链链接在一起?

考虑以下C ++中的链表实现片段:

struct node
    {
        node *prev;
        string data;
    }

main()
{
    node *first=new node;
    node *second=new node;
    second->prev=first;
}

现在考虑区块链的这种准系统块结构:

class block
    {
        string hash;
        string prev_hash;
        string data;

        public:
        string calc_hash();
    }

main()                       
{
    block genesis;
    genesis.data="name,gender,age";
    genesis.hash=calc_hash(data);
    genesis.prev_hash=0000;
    block second;
    second.data="name,gender,age";
    second.hash=calc_hash(data);
    second.prev_hash=genesis.hash;
}

现在,我如何使用散列而不是指针将这些块准确地链接在一起?还是应该像带有指针的链表那样实现它,但具有一些用于验证块完整性的功能?

1 个答案:

答案 0 :(得分:1)

该块包含一个标题和一些数据(通常是事务)。唯一用于计算哈希的部分是块头。

块头包含以下内容:

块头

{版本4B} {上一个块哈希32B} {merkle根哈希32B} {时间4B} {位4B} {即刻4B}

version (4 Bytes) - Block format version.
previous block hash (32 Bytes) - The hash of the preceding block. This is important to include in the header because the hash of the block is calculated from the header, and thus depends on the value of the previous block, linking each new block to the last. This is the link in the chain of the blockchain.
merkle root hash (32 Bytes) - The hash of the merkle tree root of all transactions in the block. If any transaction is changed, removed, or reordered, it will change the merkle root hash. This is what locks all of the transactions in the block.
time (4 Bytes) - Timestamp in Unix Time (seconds). Since the clocks of each node around the world is not guaranteed to be synchronized, this is just required to be within of the rest of the network.
bits (4 Bytes) - Target hash value in Compact Format. The block hash must be equal to or less than this value in order to be considered valid.
nonce (4 Bytes) - Can be any 4 Byte value, and is continuously changed while mining until a valid block hash is found.