系统启动流程第七步

2018-11-25  本文已影响0人  joepeak

如何接入比特币网络以及原理分析

以下内容为系统启动过程中,每一步骤的详细分析。

第7步,加载区块链(src/init.cpp::AppInitMain()

首先,计算缓存的大小。包括:区块索引数据库、区块状态数据库、内存中 UTXO 集。代码如下:

fReindex = gArgs.GetBoolArg("-reindex", false);
bool fReindexChainState = gArgs.GetBoolArg("-reindex-chainstate", false);

// cache size calculations
int64_t nTotalCache = (gArgs.GetArg("-dbcache", nDefaultDbCache) << 20);
nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache
int64_t nBlockTreeDBCache = std::min(nTotalCache / 8, nMaxBlockDBCache << 20);
nTotalCache -= nBlockTreeDBCache;
int64_t nTxIndexCache = std::min(nTotalCache / 8, gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxTxIndexCache << 20 : 0);
nTotalCache -= nTxIndexCache;
int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache
nTotalCache -= nCoinDBCache;
nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
int64_t nMempoolSizeMax = gArgs.GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
LogPrintf("Cache configuration:\n");
LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
if (gArgs.GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
    LogPrintf("* Using %.1fMiB for transaction index database\n", nTxIndexCache * (1.0 / 1024 / 1024));
}

上面代码中首先计算总的缓存大小,其用 nTotalCache 表示,通过-dbcache参数设置,然后这个值要取在 nMinDbCache 和 nMaxDbCache 之间。接下来计算 nBlockTreeDBCache 和 nCoinDBCache 以及 nCoinCacheUsage,并且 nTotalCache = nBlockTreeDBCache +nCoinDBCache + nCoinCacheUsage

然后,只要加载标志为真且没有收到关闭系统的请求,即进行以下 while 循环。

因为循环可能执行多次,所以在每次循环开始都要调用本方法来清除相关的一些变量。

主要设置包括:活跃区块链的栈顶指针为空、pindexBestInvalid 为空、pindexBestHeader 为空、清空交易池、mapBlocksUnlinked(键为缺少交易的区块索引,值为有对应交易的区块索引)集合为空、vinfoBlockFile 集合为空、最后区块文件句柄 nLastBlockFile 为0、脏区块 setDirtyBlockIndex 集合为空、脏区块文件(句柄)setDirtyFileInfo 集合为空、versionbitscache 缓存清空、清空区块索引集合 mapBlockIndex,等等。

后记

由于本人水平所限,文中错误在所难免,欢迎您踊跃指出错误,在下感激不尽。我的微信联系方式:joepeak。

原创不易,尤其寒冬,欢迎赞助我一杯咖啡。

比特币 微信 支付宝

版权声明:自由转载-非商用-非衍生-保持署名(创意共享4.0许可证)

上一篇 下一篇

猜你喜欢

热点阅读