风险提示:理性看待区块链,提高风险意识!
Bitcoin UTXO代码分析(三):与其它模块的交互
首页 > 币界资讯 > 区块链知识 2018-02-15 07:48:00

前两篇介绍了 UXTO 表示以及 CCoinViewCache的使用: Bitcoin UTXO代码分析(一):UTXO的相关表示 和 Bitcoin UTXO代码分析(二):CCoinsViewCache,这篇文章主要介绍 UTXO 和其他模块的交互:新块被激活的时候如何更新UTXO,内存池中的交易和 UTXO 如何交互,以及 UTXO 的存储。

programming-code

Blockchain激活

Blockchain 发生变化时 UTXO 相关的逻辑:

bool CChainState::ConnectTip(CValidationState& state, const CChainParams& chainparams, CBlockIndex* pindexNew, const std::shared_ptr& pblock, ConnectTrace& connectTrace, DisconnectedBlockTransactions &disconnectpool)
 {
 ....
 {
 CCoinsViewCache view(pcoinsTip.get());
 bool rv = ConnectBlock(blockConnecting, state, pindexNew, view, chainparams);
 GetMainSignals().BlockChecked(blockConnecting, state);
 if (!rv) {
 if (state.IsInvalid())
 InvalidBlockFound(pindexNew, state);
 return error("ConnectTip(): ConnectBlock %s failed", pindexNew->GetBlockHash().ToString());
 }
 nTime3 = GetTimeMicros();
 nTimeConnectTotal += nTime3 - nTime2;
 LogPrint(BCLog::BENCH, " - Connect total: %.2fms [%.2fs (%.2fms/blk)]\n", (nTime3 - nTime2) * MILLI, nTimeConnectTotal * MICRO, nTimeConnectTotal * MILLI / nBlocksTotal);
 bool flushed = view.Flush();
 assert(flushed);
 }
 .....
 }
bool CChainState::DisconnectTip(CValidationState& state, const CChainParams& chainparams, DisconnectedBlockTransactions *disconnectpool)
 {
 ...
 {
 CCoinsViewCache view(pcoinsTip.get());
 assert(view.GetBestBlock() == pindexDelete->GetBlockHash());
 if (DisconnectBlock(block, pindexDelete, view) != DISCONNECT_OK)
 return error("DisconnectTip(): DisconnectBlock %s failed", pindexDelete->GetBlockHash().ToString());
 bool flushed = view.Flush();
 assert(flushed);
 }
 ...
 }

在 blockchain 结构重新组织,当前activeChain发生变化时,某些 block 会链接上 activeChain, 某些 block 会断掉跟 activeChain 的链接,内部会调用CChainState::ConnectTipCChainState::DisconnectTip,这里会生成临时的 CCoinsViewCache 对象,后端连接上全局的另一个 CCoinsViewCache实例 pcoinsTip, 在调用 ConnectBlock,DisconnectBlock 后,更新自己的状态到 pcoinsTip

Mempool相关

有一个对象专门用来处理 Mempool 相关的 UTXO,对象为CCoinsViewMemPool:

class CCoinsViewMemPool : public CCoinsViewBacked
 {
 protected:
 const CTxMemPool& mempool;
 public:
 CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn);
 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
 };
 {
 ...
 CCoinsView viewDummy;
 CCoinsViewCache view(&viewDummy);
 {
 LOCK(mempool.cs);
 CCoinsViewCache &viewChain = *pcoinsTip;
 CCoinsViewMemPool viewMempool(&viewChain, mempool);
 view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
for (const CTxIn& txin : mtx.vin) {
 view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
 }
 view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
 }
 ...
 }

在 rpc 请求时,比如: signrawtransaction,combinerawtransaction,构造了临时 viewcache 对象, 临时 viewMempool 对象 CCoinsViewMemPoolCCoinsViewMemPool被设为 view 的后端,这样确保 mtx 交易的父交易,数据来源包括当前 activeChain 的内存部分,磁盘部分,还有 mempool。

gettxout请求:

UniValue gettxout(const JSONRPCRequest& request)
 {
 ...
 if (fMempool) {
 LOCK(mempool.cs);
 CCoinsViewMemPool view(pcoinsTip.get(), mempool);
 if (!view.GetCoin(out, coin) || mempool.isSpent(out)) {
 return NullUniValue;
 }
 } else {
 if (!pcoinsTip->GetCoin(out, coin)) {
 return NullUniValue;
 }
 }
 ...
 }

rpc 请求 gettxout 处理时,如果include_mempool 为 true,会构造临时 ViewMemPool,方便外部用户查询 utxo 时,引入 mempool 中的 utxo。

检查 timelock 交易的代码:

bool CheckSequenceLocks(const CTransaction &tx, int flags, LockPoints* lp, bool useExistingLockPoints)
 {
 ...
 {
 CCoinsViewMemPool viewMemPool(pcoinsTip.get(), mempool);
 std::vector prevheights;
 prevheights.resize(tx.vin.size());
 for (size_t txinIndex = 0; txinIndex < tx.vin.size(); txinIndex++) { const CTxIn& txin = tx.vin[txinIndex]; Coin coin; if (!viewMemPool.GetCoin(txin.prevout, coin)) { return error("%s: Missing input", __func__); } if (coin.nHeight == MEMPOOL_HEIGHT) { // Assume all mempool transaction confirm in the next block prevheights[txinIndex] = tip->nHeight + 1;
 } else {
 prevheights[txinIndex] = coin.nHeight;
 }
 }
}
 ...
 }

评估使用timelock的交易时,需要再次构造临时 ViewMemPool,查询当前blockchain tip 对应的 coin 集合与内存池的 coin 集合。

有交易进入内存池时:

static bool AcceptToMemoryPoolWorker(const CChainParams& chainparams, CTxMemPool& pool, CValidationState& state, const CTransactionRef& ptx,bool* pfMissingInputs, int64_t nAcceptTime, std::list* plTxnReplaced,bool bypass_limits, const CAmount& nAbsurdFee, std::vector& coins_to_uncache)
 {
 .....
 CCoinsView dummy;
 CCoinsViewCache view(&dummy);
 LockPoints lp;
 {
 LOCK(pool.cs);
 CCoinsViewMemPool viewMemPool(pcoinsTip.get(), pool);
 view.SetBackend(viewMemPool);
 // do all inputs exist?
 for (const CTxIn txin : tx.vin) {
 if (!pcoinsTip->HaveCoinInCache(txin.prevout)) {
 coins_to_uncache.push_back(txin.prevout);
 }
 if (!view.HaveCoin(txin.prevout)) {
 // Are inputs missing because we already have the tx?
 for (size_t out = 0; out < tx.vout.size(); out++) { // Optimistically just do efficient check of cache for outputs if (pcoinsTip->HaveCoinInCache(COutPoint(hash, out))) {
 return state.Invalid(false, REJECT_DUPLICATE, "txn-already-known");
 }
 }
 // Otherwise assume this might be an orphan tx for which we just haven't seen parents yet
 if (pfMissingInputs) {
 *pfMissingInputs = true;
 }
 return false; // fMissingInputs and !state.IsInvalid() is used to detect this condition, don't set state.Invalid()
 }
 }
 // Bring the best block into scope
 view.GetBestBlock();
 view.SetBackend(dummy);
 ......
 }

AcceptToMemoryPoolWorker中,构造了临时 ccoinsviewcache 对象 view,临时 ccoinsviewMemPool 对象 viewmempool,view 后端数据来源是viewmempool。

UTXO的存储

utxo 的磁盘存储使用了 leveldb 键值对数据库, 键的序列化格式:

C[32 bytes of outpoint->hash][varint(outpoint->n]

struct CoinEntry {
 COutPoint* outpoint;
 char key;
 explicit CoinEntry(const COutPoint* ptr) : outpoint(const_cast<COutPoint*>(ptr)), key(DB_COIN) {}
 template
 void Serialize(Stream &s) const {
 s << key;
 s << outpoint->hash;
 s << VARINT(outpoint->n);
 }
 template
 void Unserialize(Stream& s) {
 s >> key;
 s >> outpoint->hash;
 s >> VARINT(outpoint->n);
 }
 };

value 对应的存储格式是就是 coin 对象的序列化形式:

VARINT((coinbase?1: 0) | (height <<1))

CTxout 的序列化格式(使用 CTxOutCompressor 类定制特殊压缩方式)。

template
 void Serialize(Stream &s) const {
 assert(!IsSpent());
 uint32_t code = nHeight * 2 + fCoinBase;
 ::Serialize(s, VARINT(code));
 ::Serialize(s, CTxOutCompressor(REF(out)));
 }

在每一个 CTxout 对象本身之前, 加上了一个变长编码的code = nHeight * 2 + fCoinBase数字,接着就是 txcout 本身:

class CTxOutCompressor
 {
 inline void SerializationOp(Stream& s, Operation ser_action) {
 if (!ser_action.ForRead()) {
 uint64_t nVal = CompressAmount(txout.nValue);
 READWRITE(VARINT(nVal));
 } else {
 uint64_t nVal = 0;
 READWRITE(VARINT(nVal));
 txout.nValue = DecompressAmount(nVal);
 }
 CScriptCompressor cscript(REF(txout.scriptPubKey));
 READWRITE(cscript);
 }
 }

接着是被压缩的数目, 使用CompressAmount成员函数中的算法:

uint64_t CTxOutCompressor::CompressAmount(uint64_t n)
 {
 if (n == 0)
 return 0;
 int e = 0;
 while (((n % 10) == 0) && e < 9) {
 n /= 10;
 e++;
 }
 if (e < 9) { int d = (n % 10); assert(d >= 1 && d <= 9);
 n /= 10;
 return 1 + (n*9 + d - 1)*10 + e;
 } else {
 return 1 + (n - 1)*10 + 9;
 }
 }

CTxout 中的锁定脚本使用CScriptCompressor 对象压缩存储:

class CScriptCompressor
 {
 template
 void Serialize(Stream &s) const {
 std::vector compr;
 if (Compress(compr)) {
 s << CFlatData(compr);
 return;
 }
 unsigned int nSize = script.size() + nSpecialScripts;
 s << VARINT(nSize);
 s << CFlatData(script);
 }
 }

基本思路, 对于 p2pkh 类型的脚本, 比如:

OP_DUP OP_HASH160 ab68025513c3dbd2f7b92a94e0581f5d50f654e7 OP_EQUALVERIFY OP_CHECKSIG,

压缩成:

[0x00][ab68025513c3dbd2f7b92a94e0581f5d50f654e7]

总共 21 字节。

p2sh 类型脚本, 比如:

OP_HASH160 20 0x620a6eeaf538ec9eb89b6ae83f2ed8ef98566a03 OP_EQUAL

压缩成:

[0x01][620a6eeaf538ec9eb89b6ae83f2ed8ef98566a03]

总共 21 字节。

p2pk 类型脚本, 比如:

33 0x022df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da OP_CHECKSIG

压缩成:

[0x2][2df8750480ad5b26950b25c7ba79d3e37d75f640f8e5d9bcd5b150a0f85014da]

总共 33 字节, 未压缩的 p2pk 脚本, 首字节是 0×04|(pubkey[64]&0×01), 接着是 32 字节的 pubkey 的 x 坐标。

对于其它不能被压缩的脚本, 如 segwit 的 scriptPubKey,采用下面方法:

unsigned int nSize = script.size() + nSpecialScripts;
 s << VARINT(nSize);
 s << CFlatData(script);
上一篇: 比特币改进协议BIP 9 简述
下一篇: 以太坊探究:ETH交易部分分析
推荐专栏
web3首席知识博主
一位相信价值投资的币圈KOL。稳定盈利的缠论野生交易员 #BTC行情分析师 #价值投资 #链上数据分析
爱Web 3,爱生活,爱科技,爱炒币的老韭菜
热门币种
更多
币种
价格
24H涨跌幅
BTC比特币
¥264,723.74
37,091.22 USDT
+0.1%
ETH以太坊
¥14,416.22
2,019.90 USDT
-0.12%
USDT泰达币
¥7.20
1.01 USDT
0%
BNB币安币
¥1,625.40
227.74 USDT
+0.36%
XRP瑞波币
¥4.32
0.60460 USDT
+0.37%
USDC
¥7.14
1.00 USDT
+0.03%
SOLSolana
¥398.85
55.89 USDT
+1.54%
OKBOK币
¥398.61
55.85 USDT
-1.64%
ADA艾达币
¥2.68
0.37580 USDT
-1.16%
DOGE狗狗币
¥0.55160
0.07730 USDT
-1.52%
热搜币种
更多
币种
价格
24H涨跌幅
Terra Classic
¥0.00
9.402E-5 USDT
-18.95%
Gala
¥0.18
0.025374 USDT
-4.66%
dYdX
¥22.58
3.1918 USDT
-0.91%
比特股
¥0.05
0.006964 USDT
+4.28%
PancakeSwap
¥15.52
2.1936 USDT
-2.74%
Conflux
¥1.08
0.1524 USDT
-2.87%
Filecoin
¥31.45
4.4454 USDT
-0.69%
FTX Token
¥29.82
4.2155 USDT
+16.96%
Yield Guild Games
¥2.55
0.3608 USDT
-0.52%
Shiba Inu
¥0.00
8.14E-6 USDT
-2.51%
比特币
¥262,381.44
37091.22 USDT
+0.1%
比原链
¥0.07
0.010011 USDT
-4.38%
最新快讯
更多
汇丰、恒生、渣打、富邦华一四家外资银行入围首批“数字人民币”业务试点名单
2023-11-28 19:06:57
摩根大通和Apollo计划建立代币化“企业主网”
2023-11-28 19:03:57
Nansen2公测版本上线,新增链上数据异动、智能搜索等功能
2023-11-28 18:59:52
西班牙公民需在明年3月底前申报其海外平台上加密货币持仓
2023-11-28 18:53:43
Nansen2已公开测试
2023-11-28 18:53:38
dYdX基金会:主网启动以来超过1645万DYDX被质押
2023-11-28 18:52:07
NicCarter等比特币倡导者发文:比特币挖矿是清洁能源和平衡电网的关键工具
2023-11-28 18:47:58
下载币界网APP