比特币源码解析(7) - 数据结构 - 区块
https://blog.csdn.net/u012183589/article/details/77776730
0x00 摘要
区块是区块链的组成基本结构,也是交易信息的载体,矿工通过挖矿的形式来产生新的区块并获得奖励,新块产生的过程也是一个交易打包的过程,只有加入到区块中的交易才会被系统所有其他节点所认可,才是有效的。
0x01 CBlockHeader
/**
* 网络中的节点不断收集新的交易,然后一个Merkle树的形式打包进区块中,
* 打包的过程就是要完成工作量证明的要求,当节点解出了当前的随机数时,
* 它就把当前的区块广播到其他所有节点,并且加到区块链上。
* 区块中的第一笔交易称之为CoinBase交易,是产生的新币,发送给区块的产生者
*/
class CBlockHeader
{
public:
// header
int32_t nVersion; // 版本
uint256 hashPrevBlock; //前一个区块的hash
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;
}
};
- 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
0x02 CBlock
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();
*((CBlockHeader*)this) = header;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(*(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;
};