【问题标题】:How exactly do I link 2 blocks using the hash of the previous block?如何使用前一个块的哈希链接 2 个块?
【发布时间】:2019-03-20 21:08:06
【问题描述】:

我是区块链新手,想自己用 C++ 实现一个基本的区块链。我在类比链表,想知道如何使用哈希而不是指针将块链链接在一起?

考虑一下 C++ 中链表实现的这个 sn-p:

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

现在,我如何使用哈希而不是指针将这些块链接在一起?或者它只是应该像带有指针的链表一样实现,但具有一些用于验证块完整性的功能?

【问题讨论】:

    标签: c++ pointers hash blockchain


    【解决方案1】:

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

    区块头包含以下内容:

    块头

    {version 4B} {previous block hash 32B} {merkle root hash 32B} {time 4B} {bits 4B} {nonce 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.
    

    【讨论】:

    • 不,这不是我要问的。请查看我的更新说明,这可能有助于更好地理解我的问题。
    • second.prev_hash=genesis.hash; 这就是您链接它们的方式,您已经完成了。您不想像链表一样将所有块加载到内存中,您将没有足够的内存。例如,您可以将它们保存在数据库中,并将它们的哈希值作为索引。然后,在将任何新块添加到数据库之前,通过检查它们的数据、标头和散列的有效性来验证它们,包括之前的块散列存在并且数据是有效的(例如,没有双花)
    • 好的,现在知道了。非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-30
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多