风险提示:理性看待区块链,提高风险意识!
Bitcoin UTXO代码分析(一):UTXO的相关表示
首页 > 币界资讯 > 区块链知识 2018-02-08 15:00
摘要
在 Bitcoin 代码中,使用 Coin 类来表示单个交易对象中某个输出的币:class Coin { public: //! unspent transaction output CTxOut out; //! whether containing transaction was a coinb 。
币界网报道:

在 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的标记以及保存。

发表评论
发表评论
暂无评论
    相关阅读
    未来一年可以说是最难以预测的一年。地缘政治错综复杂、美国监管政策不确定。尽管美国股市似乎无法停止上涨,利率也只能下降,但我们知道,这两件事都不是板上钉钉的事。
    区块链
    2025-01-08 11:31:18
    周一,比特币和以太坊 ETF 共计流入 11 亿美元,在现货基金年初出现 3.2 亿美元流入后,形成了积极的势头。
    比特币
    2025-01-08 10:31:17
    Ripple宣布已集成Chainlink,为用户提供实时RLUSD定价数据,增强了稳定币在DeFi上的实用性和访问权限。DeFi开发人员还可以将RLUSD支持集成到他们的应用程序中,用于贷款和交易等多种用例。
    区块链
    2025-01-08 10:03:08
    莱特币在看涨突破后一周内上涨12%——282美元的目标现在就在眼前!
    区块链
    2025-01-08 09:41:19
    除了 Twitter 之外,还有其他地方可以追踪 AI 代理。
    区块链
    2025-01-08 09:31:18
    推荐专栏
    Boss Wallet Web3 Econom Pass
    Fully On-Chain & AI-Powered Meme Trading | #Xbit #DEX #Web3 | English: @XBITDEX | Chinese 华语 : @XBITDEX_ZH | Support: @XbitHelpDesk
    一位相信价值投资的币圈KOL。稳定盈利的缠论野生交易员 #BTC行情分析师 #价值投资 #链上数据分析
    爱Web 3,爱生活,爱科技,爱炒币的老韭菜
    热门币种
    更多
    币种
    美元价格
    24H涨跌幅
    BTC比特币
    117,343.66 USDT
    ¥859,712.46
    +0.56%
    ETH以太坊
    4,221.96 USDT
    ¥30,931.98
    +8.25%
    BNB币安币
    812.49 USDT
    ¥5,952.67
    +3.34%
    USDT泰达币
    1.02 USDT
    ¥7.25
    -0.19%
    SOL
    135.96 USDT
    ¥970.36
    +7.66%
    USDC
    1.00 USDT
    ¥7.15
    -0.01%
    TON
    7.59 USDT
    ¥54.14
    +4.55%
    XRP瑞波币
    0.47720 USDT
    ¥3.41
    +0.48%
    DOGE狗狗币
    0.23768 USDT
    ¥1.74
    +6.66%
    ADA艾达币
    0.39050 USDT
    ¥2.79
    +3.88%
    热搜币种
    更多
    币种
    美元价格
    24H涨跌幅
    狗狗币
    0.23768 USDT
    ¥1.74
    +6.66%
    Filecoin
    5.3381 USDT
    ¥39.11
    -10.48%
    比特币
    117,343.66 USDT
    ¥859,712.46
    +0.56%
    Gatechain Token
    17.9689 USDT
    ¥131.65
    -2.85%
    Horizen
    23.2652 USDT
    ¥170.45
    -17.39%
    dYdX
    1.4038 USDT
    ¥10.28
    -13.8%
    Solana
    198.71 USDT
    ¥1,455.84
    -8.68%
    柚子
    0.814 USDT
    ¥5.96
    -10.6%
    Shiba Inu
    2.174E-5 USDT
    ¥0.00
    -9.45%
    艾达币
    0.998 USDT
    ¥7.31
    -8.29%
    FTX Token
    2.9131 USDT
    ¥21.34
    -13.97%
    火币积分
    0.9291 USDT
    ¥6.81
    -29.01%
    最新快讯
    更多
    美国现货比特币ETF昨日净流入5346万美元
    2025-01-08 12:00:02
    昨日美国比特币现货ETF净流入5348万美元
    2025-01-08 11:59:02
    CertiKAlert:7天前部署的IPC代币存在漏洞,黑客通过闪电贷保护机制盗取约59万美元
    2025-01-08 11:58:42
    IREN:2024全年比特币挖矿产出达3984枚BTC
    2025-01-08 11:57:41
    昨日贝莱德IBIT净流入5.9718亿美元,交易量达31亿美元
    2025-01-08 11:54:57
    IPC代币疑遭攻击,损失约59万美元
    2025-01-08 11:53:10
    NOWPayments:比特币达到10万美元里程碑后,商家加密支付激增8%
    2025-01-08 11:53:03