41 _(
"The -txindex upgrade started by a previous version can not "
42 "be completed. Restart with the previous version or run a "
45 bool txindex_legacy_flag{
false};
46 block_tree_db.
ReadFlag(
"txindex", txindex_legacy_flag);
47 if (txindex_legacy_flag) {
49 if (!block_tree_db.
WriteFlag(
"txindex",
false)) {
51 "Failed to write block index db flag 'txindex'='0'")};
54 _(
"The block index db contains a legacy 'txindex'. To clear the "
55 "occupied disk space, run a full -reindex, otherwise ignore "
56 "this error. This error message will not be displayed again.")};
66 explicit CoinEntry(
const COutPoint *ptr)
67 : outpoint(const_cast<COutPoint *>(ptr)), key(
DB_COIN) {}
70 TxId id = obj.outpoint->GetTxId();
71 uint32_t n = obj.outpoint->GetN();
73 SER_READ(obj, *obj.outpoint = COutPoint(
id, n));
79 : m_db_params{
std::move(db_params)}, m_options{
std::move(options)},
96 return m_db->Read(CoinEntry(&outpoint), coin);
100 return m_db->Exists(CoinEntry(&outpoint));
108 return hashBestChain;
112 std::vector<BlockHash> vhashHeadBlocks;
114 return std::vector<BlockHash>();
116 return vhashHeadBlocks;
130 if (old_heads.size() == 2) {
131 assert(old_heads[0] == hashBlock);
132 old_tip = old_heads[1];
143 for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) {
145 CoinEntry entry(&it->first);
146 if (it->second.coin.IsSpent()) {
149 batch.
Write(entry, it->second.coin);
154 it = erase ? mapCoins.erase(it) : std::next(it);
158 m_db->WriteBatch(batch);
163 LogPrintf(
"Simulating a crash. Goodbye.\n");
176 bool ret =
m_db->WriteBatch(batch);
178 "Committed %u changed transaction outputs (out of "
179 "%u) to coin database...\n",
180 (
unsigned int)changed, (
unsigned int)
count);
219 CoinEntry entry(&i->
keyTmp.second);
221 i->
keyTmp.first = entry.key;
239 return pcursor->GetValue(coin);
243 return pcursor->GetValueSize();
252 CoinEntry entry(&
keyTmp.second);
263 const std::vector<std::pair<int, const CBlockFileInfo *>> &fileInfo,
264 int nLastFile,
const std::vector<const CBlockIndex *> &blockinfo) {
266 for (std::vector<std::pair<int, const CBlockFileInfo *>>::const_iterator
267 it = fileInfo.begin();
268 it != fileInfo.end(); it++) {
272 for (std::vector<const CBlockIndex *>::const_iterator it =
274 it != blockinfo.end(); it++) {
283 fValue ? uint8_t{
'1'} : uint8_t{
'0'});
291 fValue = ch == uint8_t{
'1'};
299 std::unique_ptr<CDBIterator> pcursor(
NewIterator());
301 uint64_t version = 0;
302 pcursor->Seek(
"version");
303 if (pcursor->Valid()) {
304 pcursor->GetValue(version);
308 return error(
"%s: Invalid block index database version: %s", __func__,
315 while (pcursor->Valid()) {
319 std::pair<uint8_t, uint256> key;
325 if (!pcursor->GetValue(diskindex)) {
326 return error(
"%s : failed to read value", __func__);
334 pindexNew->nFile = diskindex.nFile;
335 pindexNew->nDataPos = diskindex.nDataPos;
336 pindexNew->nUndoPos = diskindex.nUndoPos;
342 pindexNew->nStatus = diskindex.nStatus;
343 pindexNew->
nTx = diskindex.
nTx;
347 return error(
"%s: CheckProofOfWork failed: %s", __func__,
366 std::vector<CTxOut> vout;
372 CCoins() : fCoinBase(false), vout(0),
nHeight(0) {}
374 template <
typename Stream>
void Unserialize(Stream &s) {
377 unsigned int nVersionDummy = 0;
381 fCoinBase = nCode & 1;
382 std::vector<bool> vAvail(2,
false);
383 vAvail[0] = (nCode & 2) != 0;
384 vAvail[1] = (nCode & 4) != 0;
385 uint32_t nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1);
387 while (nMaskCode > 0) {
390 for (
unsigned int p = 0; p < 8; p++) {
391 bool f = (chAvail & (1 << p)) != 0;
399 vout.assign(vAvail.size(),
CTxOut());
400 for (
size_t i = 0; i < vAvail.size(); i++) {
417 std::unique_ptr<CDBIterator> pcursor(
m_db->NewIterator());
419 if (!pcursor->Valid()) {
424 LogPrintf(
"Upgrading utxo-set database...\n");
425 size_t batch_size = 1 << 24;
428 std::pair<uint8_t, uint256> key;
430 while (pcursor->Valid()) {
435 if (!pcursor->GetKey(key) || key.first !=
DB_COINS) {
439 if (
count++ % 256 == 0) {
441 0x100 * *key.second.
begin() + *(key.second.begin() + 1);
442 int percentageDone = (int)(high * 100.0 / 65536.0 + 0.5);
444 percentageDone,
true);
445 if (reportDone < percentageDone / 10) {
448 reportDone = percentageDone / 10;
453 if (!pcursor->GetValue(old_coins)) {
454 return error(
"%s: cannot parse CCoins record", __func__);
457 const TxId id(key.second);
458 for (
size_t i = 0; i < old_coins.vout.size(); ++i) {
459 if (!old_coins.vout[i].IsNull() &&
460 !old_coins.vout[i].scriptPubKey.IsUnspendable()) {
461 Coin newcoin(std::move(old_coins.vout[i]), old_coins.nHeight,
462 old_coins.fCoinBase);
463 COutPoint outpoint(
id, i);
464 CoinEntry entry(&outpoint);
465 batch.
Write(entry, newcoin);
471 m_db->WriteBatch(batch);
473 m_db->CompactRange(prev_key, key);
480 m_db->WriteBatch(batch);
491 std::unique_ptr<CDBIterator> pcursor(
NewIterator());
493 uint64_t version = 0;
494 pcursor->Seek(
"version");
495 if (pcursor->Valid()) {
496 pcursor->GetValue(version);
510 "\nThe database is too old. The block index cannot be upgraded "
511 "and reindexing is required.\n");
518 LogPrintf(
"Updating the block index database version to %d\n",
The block chain is a tree shaped structure starting with the genesis block at the root,...
std::string ToString() const
CBlockIndex * pprev
pointer to the index of the predecessor of this block
unsigned int nTx
Number of transactions in this block.
int32_t nVersion
block header
BlockHash GetBlockHash() const
int nHeight
height of the entry in the chain. The genesis block has height 0
Access to the block database (blocks/index/)
bool ReadBlockFileInfo(int nFile, CBlockFileInfo &info)
bool Upgrade()
Attempt to update from an older database format.
bool WriteReindexing(bool fReindexing)
bool IsReindexing() const
bool WriteBatchSync(const std::vector< std::pair< int, const CBlockFileInfo * > > &fileInfo, int nLastFile, const std::vector< const CBlockIndex * > &blockinfo)
bool ReadFlag(const std::string &name, bool &fValue)
bool ReadLastBlockFile(int &nFile)
bool LoadBlockIndexGuts(const Consensus::Params ¶ms, std::function< CBlockIndex *(const BlockHash &)> insertBlockIndex) EXCLUSIVE_LOCKS_REQUIRED(
bool WriteFlag(const std::string &name, bool fValue)
Cursor for iterating over CoinsView state.
Specialization of CCoinsViewCursor to iterate over a CCoinsViewDB.
std::unique_ptr< CDBIterator > pcursor
bool GetKey(COutPoint &key) const override
bool GetValue(Coin &coin) const override
bool Valid() const override
unsigned int GetValueSize() const override
std::pair< char, COutPoint > keyTmp
BlockHash GetBestBlock() const override
Retrieve the block hash whose state this CCoinsView currently represents.
std::vector< BlockHash > GetHeadBlocks() const override
Retrieve the range of blocks that may have been only partially written.
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override
Retrieve the Coin (unspent transaction output) for a given outpoint.
bool HaveCoin(const COutPoint &outpoint) const override
Just check whether a given outpoint is unspent.
std::unique_ptr< CDBWrapper > m_db
bool Upgrade()
Attempt to update from an older database format.
CCoinsViewCursor * Cursor() const override
Get a cursor to iterate over the whole state.
CCoinsViewDB(DBParams db_params, CoinsViewOptions options)
bool BatchWrite(CCoinsMap &mapCoins, const BlockHash &hashBlock, bool erase=true) override
Do a bulk modification (multiple Coin changes + BestBlock change).
void ResizeCache(size_t new_cache_size) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Dynamically alter the underlying leveldb cache size.
CoinsViewOptions m_options
size_t EstimateSize() const override
Estimate database size (0 if not implemented)
Batch of changes queued to be written to a CDBWrapper.
size_t SizeEstimate() const
void Write(const K &key, const V &value)
bool WriteBatch(CDBBatch &batch, bool fSync=false)
bool Read(const K &key, V &value) const
CDBIterator * NewIterator()
bool Erase(const K &key, bool fSync=false)
bool Write(const K &key, const V &value, bool fSync=false)
bool Exists(const K &key) const
Used to marshal pointers into hashes for db storage.
static constexpr int TRACK_SIZE_VERSION
BlockHash ConstructBlockHash() const
An output of a transaction.
uint64_t randrange(uint64_t range) noexcept
Generate a random integer in the range [0..range).
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
std::unordered_map< COutPoint, CCoinsCacheEntry, SaltedOutpointHasher, std::equal_to< COutPoint >, PoolAllocator< std::pair< const COutPoint, CCoinsCacheEntry >, sizeof(std::pair< const COutPoint, CCoinsCacheEntry >)+sizeof(void *) *4 > > CCoinsMap
PoolAllocator's MAX_BLOCK_SIZE_BYTES parameter here uses sizeof the data, and adds the size of 4 poin...
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
bool error(const char *fmt, const Args &...args)
#define LogPrint(category,...)
#define LogPrintfToBeContinued
These are aliases used to explicitly state that the message should not end with a newline character.
Implement std::hash so RCUPtr can be used as a key for maps or sets.
bool CheckProofOfWork(const BlockHash &hash, uint32_t nBits, const Consensus::Params ¶ms)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
#define VARINT_MODE(obj, mode)
#define SERIALIZE_METHODS(cls, obj)
Implement the Serialize and Unserialize methods by delegating to a single templated static method tha...
void Unserialize(Stream &, char)=delete
#define SER_READ(obj, code)
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
A BlockHash is a unqiue identifier for a block.
Describes a place in the block chain to another node such that if the other node doesn't have the sam...
@ DIRTY
DIRTY means the CCoinsCacheEntry is potentially different from the version in the parent cache.
User-controlled performance and debug options.
int simulate_crash_ratio
If non-zero, randomly exit when the database is flushed with (1/ratio) probability.
size_t batch_write_bytes
Maximum database write batch size in bytes.
Parameters that influence chain consensus.
Application-specific storage settings.
bool wipe_data
If true, remove all existing data.
size_t cache_bytes
Configures various leveldb cache settings.
bool memory_only
If true, use leveldb's memory environment.
A TxId is the identifier of a transaction.
bilingual_str _(const char *psz)
Translation function.
bilingual_str Untranslated(std::string original)
Mark a bilingual_str as untranslated.
static constexpr uint8_t DB_TXINDEX_BLOCK
static constexpr uint8_t DB_LAST_BLOCK
static constexpr uint8_t DB_HEAD_BLOCKS
static constexpr uint8_t DB_REINDEX_FLAG
static constexpr uint8_t DB_BEST_BLOCK
util::Result< void > CheckLegacyTxindex(CBlockTreeDB &block_tree_db)
static constexpr uint8_t DB_COIN
static constexpr uint8_t DB_FLAG
static constexpr uint8_t DB_COINS
static constexpr uint8_t DB_BLOCK_FILES
static constexpr uint8_t DB_BLOCK_INDEX
CClientUIInterface uiInterface
std::vector< typename std::common_type< Args... >::type > Vector(Args &&...args)
Construct a vector with the specified elements.