简介

区块是区块链的基本组成机构,也是交易信息的载体,矿工通过挖矿的形式来产生新的区块并获得奖励,新块产生的过程也是一个交易打包的过程,只有加入到区块中的交易才会被系统所有其他节点所认可,才是有效的。

文件名 //block.h

1
class CBlockHeader

01 class CBlockHeader

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/** Nodes collect new transactions into a block, hash them into a hash tree,
* and scan through nonce values to make the block's hash satisfy proof-of-work
* requirements. When they solve the proof-of-work, they broadcast the block
* to everyone and the block is added to the block chain. The first transaction
* in the block is a special one that creates a new coin owned by the creator
* of the block.
* -------------
* 网络中的节点不断收集新的交易,然后以一个Merkle树的形式打包进区块block中,
* 打包的过程就是要完成工作量证明的要求,当节点解出了当前的随机数时,
* 网络就把当前的区块广播到其他所有节点,并且加到区块链上。
* 区块中的第一笔交易称之为CoinBase交易,是产生的新币,发送给区块的产生者
*/
class CBlockHeader //区块头 类
{
public:
// header
int32_t nVersion; //版本号
uint256 hashPrevBlock; //前一个区块的哈希
uint256 hashMerkleRoot; //Merkle 树根
uint32_t nTime; //时间戳
uint32_t nBits; //POW难度
uint32_t nNonce; //要找的随机数

CBlockHeader()
{
SetNull();
}

ADD_SERIALIZE_METHODS;

template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(this->nVersion);
READWRITE(hashPrevBlock);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
}

void SetNull()
{
nVersion = 0;
hashPrevBlock.SetNull();
hashMerkleRoot.SetNull();
nTime = 0;
nBits = 0;
nNonce = 0;
}

bool IsNull() const
{
return (nBits == 0);
}

uint256 GetHash() const;

int64_t GetBlockTime() const
{
return (int64_t)nTime;
}
};

01 class CBlock

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// 区块类
class CBlock : public CBlockHeader
{
public:
// network and disk
std::vector<CTransactionRef> vtx; //所有的交易集合

// memory only
mutable bool fChecked; //交易是否验证过并构成Merkle树

CBlock()
{
SetNull();
}

CBlock(const CBlockHeader &header)
{
SetNull();
*(static_cast<CBlockHeader*>(this)) = header;
}

ADD_SERIALIZE_METHODS;

template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(*static_cast<CBlockHeader*>(this));
READWRITE(vtx);
}

void SetNull()
{
CBlockHeader::SetNull();
vtx.clear();
fChecked = false;
}

//获得区块头信息
CBlockHeader GetBlockHeader() const
{
CBlockHeader block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrevBlock;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block;
}

std::string ToString() const;
};