比特币学习笔记-区块验证与交易验证
区块校验
比特币区块的校验标准如下:
1、区块头的的哈希值满足当前目标值(工作量证明)
2、重构Merkle树得到的树根与区块头中hashMerkleRoot值一致(验证MerkleRoot是否由区块中交易得到)
3、区块大小在长度限制内
4、第一个交易是coinbase交易,且其他交易都不是coinbase交易
5、遍历区块内所有交易,[检查交易]合法性
以上的校验标准主要在比特币核心客户端的[CheckBlock]函数中获得,具体源码如下:
bool CheckBlock(const CBlock& block, CValidationState& state, const Consensus::Params& consensusParams, bool fCheckPOW, bool fCheckMerkleRoot)
{
// These are checks that are independent of context.
// 如果区块已经检查过,则直接返回结果true
if (block.fChecked)
return true;
// 检查区块头是否满足工作量要求
if (!CheckBlockHeader(block, state, consensusParams, fCheckPOW))
return false;
// 判断是否校验MerkleRoot 若检查,则校验MerkleRoot是否符合要求,是否存在重复交易
if (fCheckMerkleRoot) {
bool mutated;
// 重新构建一遍Merkle树,返回MerkleRoot
uint256 hashMerkleRoot2 = BlockMerkleRoot(block, &mutated);
if (block.hashMerkleRoot != hashMerkleRoot2)
return state.DoS(100, false, REJECT_INVALID, "bad-txnmrklroot",true, "hashMerkleRoot mismatch");
// Check for merkle tree malleability (CVE-2012-2459): repeating sequences
// of transactions in a block without affecting the merkle root of a block,
// while still invalidating it.
if (mutated)
return state.DoS(100, false, REJECT_INVALID, "bad-txns-duplicate",true, "duplicate transaction");
}
// 在我们做任何的交易校验之前,应该首先做潜在的问题校验,这样一旦我们发现问题,便可以将区块头标记为无效 隔离见证数据并不在此处校验
// 大小限制
// 区块交易不为空,至少存在coinbase交易
// 区块size和weight符合要求
if (block.vtx.empty() || block.vtx.size() * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT || ::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION| SERIALIZE_TRANSACTION_NO_WITNESS) * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT)
return state.DoS(100, false, REJECT_INVALID, "bad-blk-length",false, "size limits failed");
// First transaction must be coinbase, the rest must not be
// 校验首个交易是否是coinbase交易
if (block.vtx.empty() || !block.vtx[0]->IsCoinBase())
return state.DoS(100, false, REJECT_INVALID, "bad-cb-missing", false,"first tx is not coinbase");
// 校验coinbase交易是否唯一
for (unsigned int i = 1; i < block.vtx.size(); i++)
if (block.vtx[i]->IsCoinBase())
return state.DoS(100, false, REJECT_INVALID, "bad-cb-multiple",false, "more than one coinbase");
// Check transactions
// 校验交易是否符合要求,此函数将在比特币挖矿之交易校验中具体介绍
for (const auto& tx : block.vtx)
if (!CheckTransaction(*tx, state, false))
return state.Invalid(false, state.GetRejectCode(),state.GetRejectReason(),strprintf("Transaction check failed (tx hash %s) %s", tx->GetHash().ToString(), state.GetDebugMessage()));
unsigned int nSigOps = 0;
for (const auto& tx : block.vtx)
{
nSigOps += GetLegacySigOpCount(*tx);
}
if (nSigOps * WITNESS_SCALE_FACTOR > MAX_BLOCK_SIGOPS_COST)
return state.DoS(100, false, REJECT_INVALID, "bad-blk-sigops", false,"out-of-bounds SigOpCount");
if (fCheckPOW && fCheckMerkleRoot)
block.fChecked = true;
return ture;
}
检查区块头是否满足工作量要求
static bool CheckBlockHeader(const CBlockHeader& block, CValidationState&state, const Consensus::Params& consensusParams, bool fCheckPOW = true)
{
// Check proof of work matches claimed amount
// 检查工作量难度是否满足声明要求
// CheckProofOfWork方法已经在比特币挖矿之随机数中介绍过
if (fCheckPOW && !CheckProofOfWork(block.GetHash(), block.nBits,consensusParams))
return state.DoS(50, false, REJECT_INVALID, "high-hash", false, "proof of work failed");
return ture;
}
交易验证
每一个独立节点在校验每一笔接收到的交易时,都遵循如下标准:
1、交易的语法和数据结构必须正确
2、交易的字节大小在限制范围内
3、每一个输出值,必须在规定的范围内
4、没有哈希等于0,N等于-1的输入
5、锁定时间在限制范围内
6、交易的字节大小不小于100
7、交易中的签名不大于签名操作的上限
8、解锁脚本,锁定脚本格式规范
9、池中或位于主分支区块中的一个匹配交易必须是存在的
10、对于每一个输入,如果引用的输出存在于池中任何的交易,该交易将被拒绝
11、对于每一个输入,在主分支和交易池中寻找引用的输出交易。如果输出交易缺少任何一个输入,该交易将成为一个孤立的交易。如果与其匹配的交易还没有出现在池中,那么将被加入孤儿交易池
12、对于每一个输入,如果引用的输出交易是一个coinbase输出,该输入需要等待100个确认才能生效
13、对于每一个输入,引用的输出必须是存在的,并且没有被花费
14、使用引用的输出交易获得输入值,并检查每一个输入值和总值是否在规定值的范围内
15、如果输入值的总和小于输出值的总和,交易将被中止
16、如果交易费用太低以至于无法进入一个空的区块,交易将被拒绝
17、每一个输入的解锁脚本必须一句相应的锁定脚本来验证
以上的校验标准主要在比特币核心客户端CheckTransaction函数中获得,具体源码实现如下:
bool CheckTransaction(const CTransaction& tx, CValidationState &state, bool fCheckDuplicateInputs)
{
// 不依赖于上下文的基础性检查
// 校验输入是否为空,每笔交易都需有来源
if (tx.vin.empty())
return state.DoS(10, false, REJECT_INVALID, "bad-txns-vin-empty");
// 校验输出是否为空,每笔钱都应有去向
if (tx.vout.empty())
return state.DoS(10, false, REJECT_INVALID, "bad-txns-vout-empty");
// 大小校验 不考虑隔离见证数据
if (::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS) * WITNESS_SCALE_FACTOR > MAX_BLOCK_WEIGHT)
return state.DoS(100, false, REJECT_INVALID, "bad-txns-oversize");
// 校验输出值是否有效
CAmount nValueOut = 0;
for (const auto& txout : tx.vout)
{
if (txout.nValue < 0)
return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-negative");
if (txout.nValue > MAX_MONEY)
return state.DoS(100, false, REJECT_INVALID, "bad-txns-vout-toolarge");
nValueOut += txout.nValue;
if (!MoneyRange(nValueOut))
return state.DoS(100, false, REJECT_INVALID, "bad-txns-txouttotal-toolarge");
}
// 校验重复输入 注意该校验比较耗时,所以我们在CheckBlock时,跳过该步骤
if (fCheckDuplicateInputs) {
std::set<COutPoint> vInOutPoints;
for (const auto& txin : tx.vin)
{
if (!vInOutPoints.insert(txin.prevout).second)
return state.DoS(100, false, REJECT_INVALID, "bad-txns-inputs-duplicate");
}
}
// 对coinbase交易进行校验
if (tx.IsCoinBase())
{
// 检验coinbase的scriptSig大小是否在[2,100]范围内
if (tx.vin[0].scriptSig.size() < 2 || tx.vin[0].scriptSig.size() > 100)
return state.DoS(100, false, REJECT_INVALID, "bad-cb-length");
}
else
{
for (const auto& txin : tx.vin)
// 每笔交易必须有来源
if (txin.prevout.IsNull())
return state.DoS(10, false, REJECT_INVALID, "bad-txns-prevout-null");
}
return true;
}
// 检查指定交易的所有输入是否有效(不存在双花)
bool CheckInputs(const CTransaction& tx, CValidationState &state, const CCoinsViewCache &inputs, bool fScriptChecks, unsigned int flags, bool cacheSigStore, bool cacheFullScriptStore, PrecomputedTransactionData& txdata, std::vector<CScriptCheck> *pvChecks)
{
if (!tx.IsCoinBase())
{
if (pvChecks)
pvChecks->reserve(tx.vin.size());
if (fScriptChecks) {
uint256 hashCacheEntry;
static_assert(55 - sizeof(flags) - 32 >= 128/8, "Want at least 128 bits of nonce for script execution cache");
CSHA256().Write(scriptExecutionCacheNonce.begin(), 55 - sizeof(flags) - 32).Write(tx.GetWitnessHash().begin(), 32).Write((unsigned char*)&flags, sizeof(flags)).Finalize(hashCacheEntry.begin());
AssertLockHeld(cs_main);
if (scriptExecutionCache.contains(hashCacheEntry, !cacheFullScriptStore)) {
return true;
}
for (unsigned int i = 0; i < tx.vin.size(); i++) {
const COutPoint &prevout = tx.vin[i].prevout;
const Coin& coin = inputs.AccessCoin(prevout);
assert(!coin.IsSpent());
CScriptCheck check(coin.out, tx, i, flags, cacheSigStore, &txdata);
if (pvChecks) {
pvChecks->push_back(CScriptCheck());
check.swap(pvChecks->back());
} else if (!check()) {
if (flags & STANDARD_NOT_MANDATORY_VERIFY_FLAGS) {
CScriptCheck check2(coin.out, tx, i, flags & ~STANDARD_NOT_MANDATORY_VERIFY_FLAGS, cacheSigStore, &txdata);
if (check2())
return state.Invalid(false, REJECT_NONSTANDARD, strprintf("non-mandatory-script-verify-flag (%s)", ScriptErrorString(check.GetScriptError())));
}
return state.DoS(100,false, REJECT_INVALID, strprintf("mandatory-script-verify-flag-failed (%s)", ScriptErrorString(check.GetScriptError())));
}
}
if (cacheFullScriptStore && !pvChecks) {
scriptExecutionCache.insert(hashCacheEntry);
}
}
return true;
}
以上摘抄自 © 碳60 区块链