當前位置:
首頁 > 最新 > Bitcoin UTXO代碼分析(一):UTXO的相關表示

Bitcoin UTXO代碼分析(一):UTXO的相關表示

在 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; ..... ..... }

數據元素除了中的幣值(nValue)、花費條件(scriptPubKey)之外, 還附帶了一些元信息:是否是coinbase, 所在交易在哪個高度被打包進入 Blockchain。

再使用抽象類表達整個 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 類作為介面類,有很多具體實現子類:

類主要服務於從 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; };

此類只有一個全局實例,在中定義:

std::unique_ptr pcoinsdbview;

在init.cpp中進程啟動時, 會對改對象進行初始化:

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

類本身沒什麼實際用處, 主要是作為多個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(); }

, , 三個定製實現在初始化時需要指定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
", e.what()); abort(); } } };

啟動時的初始化代碼:

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

類是一個內存緩存的實現,內部使用hashmap 存儲了某個outpoint 到對象的映射,有一個全局實例 , 指向atctiveChain 的utxo,後端是磁碟實現對象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_mapCCoinsMap;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的標記以及保存。


喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 巴比特資訊 的精彩文章:

加密貨幣交易所新用戶日增10萬+,多家交易所暫停接受新用戶註冊

TAG:巴比特資訊 |