风险提示:理性看待区块链,提高风险意识!
Bitcoin UTXO代码分析(一):UTXO的相关表示
首页 > 币界资讯 > 区块链知识 2018-02-08 15:00:00

在 Bitcoin 代码中,使用 Coin 类来表示单个交易对象中某个输出的币:

class Coin
 {
 public:
 //! unspent transaction output
 CTxOut out;
 //! whether containing transaction was a coinbase
 unsigned int fCoinBase : 1;
 //! at which height this containing transaction was included in the active block chain
 uint32_t nHeight : 31;
 .....
 .....
 }

数据元素除了CTxOut中的币值(nValue)、花费条件(scriptPubKey)之外, 还附带了一些元信息:是否是coinbase, 所在交易在哪个高度被打包进入 Blockchain。

再使用CCoinsView抽象类表达整个 blockchain 上的币的集合:

class CCoinsView
 {
 public:
 /** Retrieve the Coin (unspent transaction output) for a given outpoint.
 * Returns true only when an unspent coin was found, which is returned in coin.
 * When false is returned, coin's value is unspecified.
 */
 virtual bool GetCoin(const COutPoint &outpoint, Coin &coin) const; //! Just check whether a given outpoint is unspent.
 virtual bool HaveCoin(const COutPoint &outpoint) const; //! Retrieve the block hash whose state this CCoinsView currently represents
 virtual uint256 GetBestBlock() const; //! Retrieve the range of blocks that may have been only partially written.
 //! If the database is in a consistent state, the result is the empty vector.
 //! Otherwise, a two-element vector is returned consisting of the new and
 //! the old block hash, in that order.
 virtual std::vector GetHeadBlocks() const; //! Do a bulk modification (multiple Coin changes + BestBlock change).
 //! The passed mapCoins can be modified.
 virtual bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock); //! Get a cursor to iterate over the whole state
 virtual CCoinsViewCursor *Cursor() const; //! As we use CCoinsViews polymorphically, have a virtual destructor
 virtual ~CCoinsView() {} //! Estimate database size (0 if not implemented)
 virtual size_t EstimateSize() const { return 0; }
 };

Cinsview 类作为接口类,有很多具体实现子类:

1

CoinsViewDB类主要服务于从 Bitcoin 数据目录下的 chainstate 子目录下保存和读取存盘的 UTXO 集合:

class CCoinsViewDB final : public CCoinsView
 {
 protected:
 CDBWrapper db;
 public:
 explicit CCoinsViewDB(size_t nCacheSize, bool fMemory = false, bool fWipe = false);
 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
 bool HaveCoin(const COutPoint &outpoint) const override;
 uint256 GetBestBlock() const override;
 std::vector GetHeadBlocks() const override;
 bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override;
 CCoinsViewCursor *Cursor() const override;
 //! Attempt to update from an older database format. Returns whether an error occurred.
 bool Upgrade();
 size_t EstimateSize() const override;
 };

此类只有一个全局实例,在validation.cpp中定义:

std::unique_ptr pcoinsdbview;

在init.cpp中进程启动时, 会对改对象进行初始化:

pcoinsdbview.reset(new CCoinsViewDB(nCoinDBCache, false, fReset || fReindexChainState));

CCoinsViewBacked本身没什么实际用处, 主要是作为多个Coinview层级之间的转接层, 它的数据成员 CCoinView *base 指向的就是后端即parent view , 如果某个coinsviewBacked的子类没有覆盖接口类CCoinsView 中的方法, 就会调用base指向的后端相应的方法。

class CCoinsViewBacked : public CCoinsView
 {
 protected:
 CCoinsView *base;public:
 CCoinsViewBacked(CCoinsView *viewIn);
 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
 bool HaveCoin(const COutPoint &outpoint) const override;
 uint256 GetBestBlock() const override;
 std::vector GetHeadBlocks() const override;
 void SetBackend(CCoinsView &viewIn);
 bool BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) override;
 CCoinsViewCursor *Cursor() const override;
 size_t EstimateSize() const override;
 };
CCoinsViewBacked::CCoinsViewBacked(CCoinsView *viewIn) : base(viewIn) { }
 bool CCoinsViewBacked::GetCoin(const COutPoint &outpoint, Coin &coin) const { return base->GetCoin(outpoint, coin); }
 bool CCoinsViewBacked::HaveCoin(const COutPoint &outpoint) const { return base->HaveCoin(outpoint); }
 uint256 CCoinsViewBacked::GetBestBlock() const { return base->GetBestBlock(); }
 std::vector CCoinsViewBacked::GetHeadBlocks() const { return base->GetHeadBlocks(); }
 void CCoinsViewBacked::SetBackend(CCoinsView &viewIn) { base = &viewIn; }
 bool CCoinsViewBacked::BatchWrite(CCoinsMap &mapCoins, const uint256 &hashBlock) { return base->BatchWrite(mapCoins, hashBlock); }
 CCoinsViewCursor *CCoinsViewBacked::Cursor() const { return base->Cursor(); }
 size_t CCoinsViewBacked::EstimateSize() const { return base->EstimateSize(); }

CCoinsViewErrorCatcher , CCoinsViewMemPool , CCoinsViewCache 三个定制实现在初始化时需要指定parent view,所以要继承于CCoinsViewBacked类。

coinsviewErrorCatcher 主要用途是包装对数据库读取做错误处理,后端是全局的磁盘实现pcoinsdbview。

class CCoinsViewErrorCatcher final : public CCoinsViewBacked
 {
 public:
 explicit CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
 bool GetCoin(const COutPoint &outpoint, Coin &coin) const override {
 try {
 return CCoinsViewBacked::GetCoin(outpoint, coin);
 } catch(const std::runtime_error& e) {
 uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
 LogPrintf("Error reading from database: %s\n", e.what());
 abort();
 }
 }
 };

启动时的初始化代码:

//init.cpp
 AppInitMain()
 pcoinscatcher.reset(new CCoinsViewErrorCatcher(pcoinsdbview.get()));

CCoinsViewCache 类是一个内存缓存的实现,内部使用hashmap 存储了某个outpoint 到Coin对象的映射,有一个全局实例pcoinsTip , 指向atctiveChain 的utxo,后端是磁盘实现CCoinsViewDB对象pcoinsdbview。

class CCoinsViewCache : public CCoinsViewBacked
 {
 protected:
 /**
 * Make mutable so that we can "fill the cache" even from Get-methods
 * declared as "const".
 */
 mutable uint256 hashBlock;
 mutable CCoinsMap cacheCoins; /* Cached dynamic memory usage for the inner Coin objects. */
 mutable size_t cachedCoinsUsage;
 ...
 ...
 }

启动时的初始化代码:

//init.cpp
 AppInitMain()
 pcoinsTip.reset(new CCoinsViewCache(pcoinscatcher.get()));

它的内部hashmap使用了定制的hash 方法siphash, 没有使用默认的std::hash方法(不是加密学安全的hash), 估计是防止hash的key冲突,:

typedef std::unordered_map<COutPoint, CCoinsCacheEntry, SaltedOutpointHasher> CCoinsMap;class SaltedOutpointHasher
 {
 private:
 /** Salt */
 const uint64_t k0, k1;public:
 SaltedOutpointHasher();
size_t operator()(const COutPoint& id) const {
 return SipHashUint256Extra(k0, k1, id.hash, id.n);
 }
 };

这篇文章介绍了表示UTXO的相关表示的数据结构,下一篇文章将会UTXO的标记以及保存。

上一篇: BIP125:交易信号的添加
下一篇: 区块链技术(13):Solidity开发神器Remix
推荐专栏
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