比特币代码分析 8 区块校验和确认
比特币节点收到一个区块后,会进行校验和确认,如下网络图所示:
关键看代码进一步验证区块中的交易:
1.//第一笔交易必须是coinbase,其余的不能是
2.if (vtx.empty() || !vtx[0].IsCoinBase())
return error("CheckBlock() : first tx is not coinbase");
4.for (int i = 1; i < vtx.size(); i++)if (vtx[i].IsCoinBase())return error("CheckBlock() : more than one coinbase");
8.// Check transactions 循环检查所有交易比特币源码解析,这一步很关键,所以交易不能随便改比特币源码解析,大家都在检查
9.foreach(const CTransaction& tx, vtx)
if (!tx.CheckTransaction()) return error("CheckBlock() : CheckTransaction failed");
13.// 检查工作证明是否与申请金额相符
14.if (CBigNum().SetCompact(nBits) > bnProofOfWorkLimit)
return error("CheckBlock() : nBits below minimum work");
16.if (GetHash() > CBigNum().SetCompact(nBits).getuint256())return error("CheckBlock() : hash doesn't match nBits");
19.// 检查 merkleroot
20.if (hashMerkleRoot != BuildMerkleTree())
返回错误(“CheckBlock():hashMerkleRoot不匹配”);