我是Blockchain的新手,想要自己在C ++中实现一个基本的区块链。我正在对链表进行类比,并且想知道,我究竟是如何使用哈希而不是指针将块链链接在一起?
考虑一下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;
}
现在,我究竟如何使用哈希而不是指针将这些块链接在一起?或者它应该像链接列表一样实现指针,但有一些功能来验证块的完整性?
该块包含标题和一些数据(通常是事务)。用于计算散列的唯一部分是块头。
块头包含以下内容:
{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.