我是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;
}

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

最佳答案

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

块头包含以下内容:

块头

{版本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.

09-26 17:59