Bitcoin ABC 0.30.9
P2P Digital Currency
blockstorage.cpp
Go to the documentation of this file.
1// Copyright (c) 2011-2022 The Bitcoin developers
2// Distributed under the MIT software license, see the accompanying
3// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5#include <node/blockstorage.h>
6
9#include <chain.h>
10#include <clientversion.h>
11#include <common/system.h>
12#include <config.h>
14#include <flatfile.h>
15#include <hash.h>
16#include <kernel/chainparams.h>
17#include <logging.h>
18#include <pow/pow.h>
19#include <reverse_iterator.h>
20#include <shutdown.h>
21#include <streams.h>
22#include <undo.h>
23#include <util/batchpriority.h>
24#include <util/fs.h>
25#include <validation.h>
26
27#include <map>
28#include <unordered_map>
29
30namespace node {
31std::atomic_bool fReindex(false);
32
33std::vector<CBlockIndex *> BlockManager::GetAllBlockIndices() {
35 std::vector<CBlockIndex *> rv;
36 rv.reserve(m_block_index.size());
37 for (auto &[_, block_index] : m_block_index) {
38 rv.push_back(&block_index);
39 }
40 return rv;
41}
42
45 BlockMap::iterator it = m_block_index.find(hash);
46 return it == m_block_index.end() ? nullptr : &it->second;
47}
48
51 BlockMap::const_iterator it = m_block_index.find(hash);
52 return it == m_block_index.end() ? nullptr : &it->second;
53}
54
56 CBlockIndex *&best_header) {
58
59 const auto [mi, inserted] =
60 m_block_index.try_emplace(block.GetHash(), block);
61 if (!inserted) {
62 return &mi->second;
63 }
64 CBlockIndex *pindexNew = &(*mi).second;
65
66 // We assign the sequence id to blocks only when the full data is available,
67 // to avoid miners withholding blocks but broadcasting headers, to get a
68 // competitive advantage.
69 pindexNew->nSequenceId = 0;
70
71 pindexNew->phashBlock = &((*mi).first);
72 BlockMap::iterator miPrev = m_block_index.find(block.hashPrevBlock);
73 if (miPrev != m_block_index.end()) {
74 pindexNew->pprev = &(*miPrev).second;
75 pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
76 pindexNew->BuildSkip();
77 }
78 pindexNew->nTimeReceived = GetTime();
79 pindexNew->nTimeMax =
80 (pindexNew->pprev
81 ? std::max(pindexNew->pprev->nTimeMax, pindexNew->nTime)
82 : pindexNew->nTime);
83 pindexNew->nChainWork =
84 (pindexNew->pprev ? pindexNew->pprev->nChainWork : 0) +
85 GetBlockProof(*pindexNew);
87 if (best_header == nullptr ||
88 best_header->nChainWork < pindexNew->nChainWork) {
89 best_header = pindexNew;
90 }
91
92 m_dirty_blockindex.insert(pindexNew);
93 return pindexNew;
94}
95
96void BlockManager::PruneOneBlockFile(const int fileNumber) {
99
100 for (auto &entry : m_block_index) {
101 CBlockIndex *pindex = &entry.second;
102 if (pindex->nFile == fileNumber) {
103 pindex->nStatus = pindex->nStatus.withData(false).withUndo(false);
104 pindex->nFile = 0;
105 pindex->nDataPos = 0;
106 pindex->nUndoPos = 0;
107 m_dirty_blockindex.insert(pindex);
108
109 // Prune from m_blocks_unlinked -- any block we prune would have
110 // to be downloaded again in order to consider its chain, at which
111 // point it would be considered as a candidate for
112 // m_blocks_unlinked or setBlockIndexCandidates.
113 auto range = m_blocks_unlinked.equal_range(pindex->pprev);
114 while (range.first != range.second) {
115 std::multimap<CBlockIndex *, CBlockIndex *>::iterator _it =
116 range.first;
117 range.first++;
118 if (_it->second == pindex) {
119 m_blocks_unlinked.erase(_it);
120 }
121 }
122 }
123 }
124
125 m_blockfile_info[fileNumber].SetNull();
126 m_dirty_fileinfo.insert(fileNumber);
127}
128
129void BlockManager::FindFilesToPruneManual(std::set<int> &setFilesToPrune,
130 int nManualPruneHeight,
131 int chain_tip_height) {
132 assert(IsPruneMode() && nManualPruneHeight > 0);
133
135 if (chain_tip_height < 0) {
136 return;
137 }
138
139 // last block to prune is the lesser of (user-specified height,
140 // MIN_BLOCKS_TO_KEEP from the tip)
141 unsigned int nLastBlockWeCanPrune{std::min(
142 (unsigned)nManualPruneHeight, chain_tip_height - MIN_BLOCKS_TO_KEEP)};
143 int count = 0;
144 for (int fileNumber = 0; fileNumber < m_last_blockfile; fileNumber++) {
145 if (m_blockfile_info[fileNumber].nSize == 0 ||
146 m_blockfile_info[fileNumber].nHeightLast > nLastBlockWeCanPrune) {
147 continue;
148 }
149 PruneOneBlockFile(fileNumber);
150 setFilesToPrune.insert(fileNumber);
151 count++;
152 }
153 LogPrintf("Prune (Manual): prune_height=%d removed %d blk/rev pairs\n",
154 nLastBlockWeCanPrune, count);
155}
156
157void BlockManager::FindFilesToPrune(std::set<int> &setFilesToPrune,
158 uint64_t nPruneAfterHeight,
159 int chain_tip_height, int prune_height,
160 bool is_ibd) {
162 if (chain_tip_height < 0 || GetPruneTarget() == 0) {
163 return;
164 }
165 if (uint64_t(chain_tip_height) <= nPruneAfterHeight) {
166 return;
167 }
168
169 unsigned int nLastBlockWeCanPrune = std::min(
170 prune_height, chain_tip_height - static_cast<int>(MIN_BLOCKS_TO_KEEP));
171 uint64_t nCurrentUsage = CalculateCurrentUsage();
172 // We don't check to prune until after we've allocated new space for files,
173 // so we should leave a buffer under our target to account for another
174 // allocation before the next pruning.
175 uint64_t nBuffer = BLOCKFILE_CHUNK_SIZE + UNDOFILE_CHUNK_SIZE;
176 uint64_t nBytesToPrune;
177 int count = 0;
178
179 if (nCurrentUsage + nBuffer >= GetPruneTarget()) {
180 // On a prune event, the chainstate DB is flushed.
181 // To avoid excessive prune events negating the benefit of high dbcache
182 // values, we should not prune too rapidly.
183 // So when pruning in IBD, increase the buffer a bit to avoid a re-prune
184 // too soon.
185 if (is_ibd) {
186 // Since this is only relevant during IBD, we use a fixed 10%
187 nBuffer += GetPruneTarget() / 10;
188 }
189
190 for (int fileNumber = 0; fileNumber < m_last_blockfile; fileNumber++) {
191 nBytesToPrune = m_blockfile_info[fileNumber].nSize +
192 m_blockfile_info[fileNumber].nUndoSize;
193
194 if (m_blockfile_info[fileNumber].nSize == 0) {
195 continue;
196 }
197
198 // are we below our target?
199 if (nCurrentUsage + nBuffer < GetPruneTarget()) {
200 break;
201 }
202
203 // don't prune files that could have a block within
204 // MIN_BLOCKS_TO_KEEP of the main chain's tip but keep scanning
205 if (m_blockfile_info[fileNumber].nHeightLast >
206 nLastBlockWeCanPrune) {
207 continue;
208 }
209
210 PruneOneBlockFile(fileNumber);
211 // Queue up the files for removal
212 setFilesToPrune.insert(fileNumber);
213 nCurrentUsage -= nBytesToPrune;
214 count++;
215 }
216 }
217
219 "Prune: target=%dMiB actual=%dMiB diff=%dMiB "
220 "max_prune_height=%d removed %d blk/rev pairs\n",
221 GetPruneTarget() / 1024 / 1024, nCurrentUsage / 1024 / 1024,
222 (int64_t(GetPruneTarget()) - int64_t(nCurrentUsage)) / 1024 / 1024,
223 nLastBlockWeCanPrune, count);
224}
225
226void BlockManager::UpdatePruneLock(const std::string &name,
227 const PruneLockInfo &lock_info) {
229 m_prune_locks[name] = lock_info;
230}
231
234
235 if (hash.IsNull()) {
236 return nullptr;
237 }
238
239 const auto [mi, inserted] = m_block_index.try_emplace(hash);
240 CBlockIndex *pindex = &(*mi).second;
241 if (inserted) {
242 pindex->phashBlock = &((*mi).first);
243 }
244 return pindex;
245}
246
249 if (!m_block_tree_db->LoadBlockIndexGuts(
250 GetConsensus(),
251 [this](const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main) {
252 return this->InsertBlockIndex(hash);
253 })) {
254 return false;
255 }
256
257 // Calculate nChainWork
258 std::vector<CBlockIndex *> vSortedByHeight{GetAllBlockIndices()};
259 std::sort(vSortedByHeight.begin(), vSortedByHeight.end(),
261
262 for (CBlockIndex *pindex : vSortedByHeight) {
263 if (ShutdownRequested()) {
264 return false;
265 }
266 pindex->nChainWork = (pindex->pprev ? pindex->pprev->nChainWork : 0) +
267 GetBlockProof(*pindex);
268 pindex->nTimeMax =
269 (pindex->pprev ? std::max(pindex->pprev->nTimeMax, pindex->nTime)
270 : pindex->nTime);
271
272 // We can link the chain of blocks for which we've received
273 // transactions at some point, or blocks that are assumed-valid on the
274 // basis of snapshot load (see PopulateAndValidateSnapshot()).
275 // Pruned nodes may have deleted the block.
276 if (pindex->nTx > 0) {
277 if (!pindex->UpdateChainStats() && pindex->pprev) {
278 m_blocks_unlinked.insert(std::make_pair(pindex->pprev, pindex));
279 }
280 }
281
282 if (!pindex->nStatus.hasFailed() && pindex->pprev &&
283 pindex->pprev->nStatus.hasFailed()) {
284 pindex->nStatus = pindex->nStatus.withFailedParent();
285 m_dirty_blockindex.insert(pindex);
286 }
287
288 if (pindex->pprev) {
289 pindex->BuildSkip();
290 }
291 }
292
293 return true;
294}
295
296bool BlockManager::WriteBlockIndexDB() {
297 std::vector<std::pair<int, const CBlockFileInfo *>> vFiles;
298 vFiles.reserve(m_dirty_fileinfo.size());
299 for (int i : m_dirty_fileinfo) {
300 vFiles.push_back(std::make_pair(i, &m_blockfile_info[i]));
301 }
302
303 m_dirty_fileinfo.clear();
304
305 std::vector<const CBlockIndex *> vBlocks;
306 vBlocks.reserve(m_dirty_blockindex.size());
307 for (const CBlockIndex *cbi : m_dirty_blockindex) {
308 vBlocks.push_back(cbi);
309 }
310
311 m_dirty_blockindex.clear();
312
313 if (!m_block_tree_db->WriteBatchSync(vFiles, m_last_blockfile, vBlocks)) {
314 return false;
315 }
316 return true;
317}
318
319bool BlockManager::LoadBlockIndexDB() {
320 if (!LoadBlockIndex()) {
321 return false;
322 }
323
324 // Load block file info
325 m_block_tree_db->ReadLastBlockFile(m_last_blockfile);
327 LogPrintf("%s: last block file = %i\n", __func__, m_last_blockfile);
328 for (int nFile = 0; nFile <= m_last_blockfile; nFile++) {
329 m_block_tree_db->ReadBlockFileInfo(nFile, m_blockfile_info[nFile]);
330 }
331 LogPrintf("%s: last block file info: %s\n", __func__,
333 for (int nFile = m_last_blockfile + 1; true; nFile++) {
334 CBlockFileInfo info;
335 if (m_block_tree_db->ReadBlockFileInfo(nFile, info)) {
336 m_blockfile_info.push_back(info);
337 } else {
338 break;
339 }
340 }
341
342 // Check presence of blk files
343 LogPrintf("Checking all blk files are present...\n");
344 std::set<int> setBlkDataFiles;
345 for (const auto &[_, block_index] : m_block_index) {
346 if (block_index.nStatus.hasData()) {
347 setBlkDataFiles.insert(block_index.nFile);
348 }
349 }
350
351 for (const int i : setBlkDataFiles) {
352 FlatFilePos pos(i, 0);
354 .IsNull()) {
355 return false;
356 }
357 }
358
359 // Check whether we have ever pruned block & undo files
360 m_block_tree_db->ReadFlag("prunedblockfiles", m_have_pruned);
361 if (m_have_pruned) {
362 LogPrintf(
363 "LoadBlockIndexDB(): Block files have previously been pruned\n");
364 }
365
366 // Check whether we need to continue reindexing
367 if (m_block_tree_db->IsReindexing()) {
368 fReindex = true;
369 }
370
371 return true;
372}
373
374void BlockManager::ScanAndUnlinkAlreadyPrunedFiles() {
376 if (!m_have_pruned) {
377 return;
378 }
379
380 std::set<int> block_files_to_prune;
381 for (int file_number = 0; file_number < m_last_blockfile; file_number++) {
382 if (m_blockfile_info[file_number].nSize == 0) {
383 block_files_to_prune.insert(file_number);
384 }
385 }
386
387 UnlinkPrunedFiles(block_files_to_prune);
388}
389
390const CBlockIndex *
392 const MapCheckpoints &checkpoints = data.mapCheckpoints;
393
394 for (const MapCheckpoints::value_type &i : reverse_iterate(checkpoints)) {
395 const BlockHash &hash = i.second;
396 const CBlockIndex *pindex = LookupBlockIndex(hash);
397 if (pindex) {
398 return pindex;
399 }
400 }
401
402 return nullptr;
403}
404
405bool BlockManager::IsBlockPruned(const CBlockIndex *pblockindex) {
407 return (m_have_pruned && !pblockindex->nStatus.hasData() &&
408 pblockindex->nTx > 0);
409}
410
411const CBlockIndex *
412BlockManager::GetFirstStoredBlock(const CBlockIndex &start_block) {
414 const CBlockIndex *last_block = &start_block;
415 while (last_block->pprev && (last_block->pprev->nStatus.hasData())) {
416 last_block = last_block->pprev;
417 }
418 return last_block;
419}
420
421// If we're using -prune with -reindex, then delete block files that will be
422// ignored by the reindex. Since reindexing works by starting at block file 0
423// and looping until a blockfile is missing, do the same here to delete any
424// later block files after a gap. Also delete all rev files since they'll be
425// rewritten by the reindex anyway. This ensures that m_blockfile_info is in
426// sync with what's actually on disk by the time we start downloading, so that
427// pruning works correctly.
429 std::map<std::string, fs::path> mapBlockFiles;
430
431 // Glob all blk?????.dat and rev?????.dat files from the blocks directory.
432 // Remove the rev files immediately and insert the blk file paths into an
433 // ordered map keyed by block file index.
434 LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for "
435 "-reindex with -prune\n");
436 for (const auto &file : fs::directory_iterator{m_opts.blocks_dir}) {
437 const std::string path = fs::PathToString(file.path().filename());
438 if (fs::is_regular_file(file) && path.length() == 12 &&
439 path.substr(8, 4) == ".dat") {
440 if (path.substr(0, 3) == "blk") {
441 mapBlockFiles[path.substr(3, 5)] = file.path();
442 } else if (path.substr(0, 3) == "rev") {
443 remove(file.path());
444 }
445 }
446 }
447
448 // Remove all block files that aren't part of a contiguous set starting at
449 // zero by walking the ordered map (keys are block file indices) by keeping
450 // a separate counter. Once we hit a gap (or if 0 doesn't exist) start
451 // removing block files.
452 int contiguousCounter = 0;
453 for (const auto &item : mapBlockFiles) {
454 if (atoi(item.first) == contiguousCounter) {
455 contiguousCounter++;
456 continue;
457 }
458 remove(item.second);
459 }
460}
461
464
465 return &m_blockfile_info.at(n);
466}
467
469 const CBlockUndo &blockundo, FlatFilePos &pos, const BlockHash &hashBlock,
470 const CMessageHeader::MessageMagic &messageStart) const {
471 // Open history file to append
473 if (fileout.IsNull()) {
474 return error("%s: OpenUndoFile failed", __func__);
475 }
476
477 // Write index header
478 unsigned int nSize = GetSerializeSize(blockundo, fileout.GetVersion());
479 fileout << messageStart << nSize;
480
481 // Write undo data
482 long fileOutPos = ftell(fileout.Get());
483 if (fileOutPos < 0) {
484 return error("%s: ftell failed", __func__);
485 }
486 pos.nPos = (unsigned int)fileOutPos;
487 fileout << blockundo;
488
489 // calculate & write checksum
490 HashWriter hasher{};
491 hasher << hashBlock;
492 hasher << blockundo;
493 fileout << hasher.GetHash();
494
495 return true;
496}
497
499 const CBlockIndex &index) const {
500 const FlatFilePos pos{WITH_LOCK(::cs_main, return index.GetUndoPos())};
501
502 if (pos.IsNull()) {
503 return error("%s: no undo data available", __func__);
504 }
505
506 // Open history file to read
507 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
508 if (filein.IsNull()) {
509 return error("%s: OpenUndoFile failed", __func__);
510 }
511
512 // Read block
513 uint256 hashChecksum;
514 // We need a CHashVerifier as reserializing may lose data
515 CHashVerifier<CAutoFile> verifier(&filein);
516 try {
517 verifier << index.pprev->GetBlockHash();
518 verifier >> blockundo;
519 filein >> hashChecksum;
520 } catch (const std::exception &e) {
521 return error("%s: Deserialize or I/O error - %s", __func__, e.what());
522 }
523
524 // Verify checksum
525 if (hashChecksum != verifier.GetHash()) {
526 return error("%s: Checksum mismatch", __func__);
527 }
528
529 return true;
530}
531
532void BlockManager::FlushUndoFile(int block_file, bool finalize) {
533 FlatFilePos undo_pos_old(block_file,
534 m_blockfile_info[block_file].nUndoSize);
535 if (!UndoFileSeq().Flush(undo_pos_old, finalize)) {
536 AbortNode("Flushing undo file to disk failed. This is likely the "
537 "result of an I/O error.");
538 }
539}
540
541void BlockManager::FlushBlockFile(bool fFinalize, bool finalize_undo) {
543
544 if (m_blockfile_info.empty()) {
545 // Return if we haven't loaded any blockfiles yet. This happens during
546 // chainstate init, when we call
547 // ChainstateManager::MaybeRebalanceCaches() (which then calls
548 // FlushStateToDisk()), resulting in a call to this function before we
549 // have populated `m_blockfile_info` via LoadBlockIndexDB().
550 return;
551 }
552 assert(static_cast<int>(m_blockfile_info.size()) > m_last_blockfile);
553
554 FlatFilePos block_pos_old(m_last_blockfile,
556 if (!BlockFileSeq().Flush(block_pos_old, fFinalize)) {
557 AbortNode("Flushing block file to disk failed. This is likely the "
558 "result of an I/O error.");
559 }
560 // we do not always flush the undo file, as the chain tip may be lagging
561 // behind the incoming blocks,
562 // e.g. during IBD or a sync after a node going offline
563 if (!fFinalize || finalize_undo) {
564 FlushUndoFile(m_last_blockfile, finalize_undo);
565 }
566}
567
570
571 uint64_t retval = 0;
572 for (const CBlockFileInfo &file : m_blockfile_info) {
573 retval += file.nSize + file.nUndoSize;
574 }
575
576 return retval;
577}
578
580 const std::set<int> &setFilesToPrune) const {
581 std::error_code error_code;
582 for (const int i : setFilesToPrune) {
583 FlatFilePos pos(i, 0);
584 const bool removed_blockfile{
585 fs::remove(BlockFileSeq().FileName(pos), error_code)};
586 const bool removed_undofile{
587 fs::remove(UndoFileSeq().FileName(pos), error_code)};
588 if (removed_blockfile || removed_undofile) {
589 LogPrint(BCLog::BLOCKSTORE, "Prune: %s deleted blk/rev (%05u)\n",
590 __func__, i);
591 }
592 }
593}
594
596 return FlatFileSeq(m_opts.blocks_dir, "blk",
597 m_opts.fast_prune ? 0x4000 /* 16kb */
599}
600
603}
604
606 bool fReadOnly) const {
607 return BlockFileSeq().Open(pos, fReadOnly);
608}
609
611FILE *BlockManager::OpenUndoFile(const FlatFilePos &pos, bool fReadOnly) const {
612 return UndoFileSeq().Open(pos, fReadOnly);
613}
614
616 return BlockFileSeq().FileName(pos);
617}
618
619bool BlockManager::FindBlockPos(FlatFilePos &pos, unsigned int nAddSize,
620 unsigned int nHeight, uint64_t nTime,
621 bool fKnown) {
623
624 unsigned int nFile = fKnown ? pos.nFile : m_last_blockfile;
625 if (m_blockfile_info.size() <= nFile) {
626 m_blockfile_info.resize(nFile + 1);
627 }
628
629 bool finalize_undo = false;
630 if (!fKnown) {
631 unsigned int max_blockfile_size{MAX_BLOCKFILE_SIZE};
632 // Use smaller blockfiles in test-only -fastprune mode - but avoid
633 // the possibility of having a block not fit into the block file.
634 if (m_opts.fast_prune) {
635 max_blockfile_size = 0x10000; // 64kiB
636 if (nAddSize >= max_blockfile_size) {
637 // dynamically adjust the blockfile size to be larger than the
638 // added size
639 max_blockfile_size = nAddSize + 1;
640 }
641 }
642 // TODO: we will also need to dynamically adjust the blockfile size
643 // or raise MAX_BLOCKFILE_SIZE when we reach block sizes larger than
644 // 128 MiB
645 assert(nAddSize < max_blockfile_size);
646 while (m_blockfile_info[nFile].nSize + nAddSize >= max_blockfile_size) {
647 // when the undo file is keeping up with the block file, we want to
648 // flush it explicitly when it is lagging behind (more blocks arrive
649 // than are being connected), we let the undo block write case
650 // handle it
651 finalize_undo = (m_blockfile_info[nFile].nHeightLast ==
653 nFile++;
654 if (m_blockfile_info.size() <= nFile) {
655 m_blockfile_info.resize(nFile + 1);
656 }
657 }
658 pos.nFile = nFile;
659 pos.nPos = m_blockfile_info[nFile].nSize;
660 }
661
662 if ((int)nFile != m_last_blockfile) {
663 if (!fKnown) {
664 LogPrint(BCLog::BLOCKSTORE, "Leaving block file %i: %s\n",
667 }
668 FlushBlockFile(!fKnown, finalize_undo);
669 m_last_blockfile = nFile;
670 // No undo data yet in the new file, so reset our undo-height tracking.
672 }
673
674 m_blockfile_info[nFile].AddBlock(nHeight, nTime);
675 if (fKnown) {
676 m_blockfile_info[nFile].nSize =
677 std::max(pos.nPos + nAddSize, m_blockfile_info[nFile].nSize);
678 } else {
679 m_blockfile_info[nFile].nSize += nAddSize;
680 }
681
682 if (!fKnown) {
683 bool out_of_space;
684 size_t bytes_allocated =
685 BlockFileSeq().Allocate(pos, nAddSize, out_of_space);
686 if (out_of_space) {
687 return AbortNode("Disk space is too low!",
688 _("Disk space is too low!"));
689 }
690 if (bytes_allocated != 0 && IsPruneMode()) {
691 m_check_for_pruning = true;
692 }
693 }
694
695 m_dirty_fileinfo.insert(nFile);
696 return true;
697}
698
700 FlatFilePos &pos, unsigned int nAddSize) {
701 pos.nFile = nFile;
702
704
705 pos.nPos = m_blockfile_info[nFile].nUndoSize;
706 m_blockfile_info[nFile].nUndoSize += nAddSize;
707 m_dirty_fileinfo.insert(nFile);
708
709 bool out_of_space;
710 size_t bytes_allocated =
711 UndoFileSeq().Allocate(pos, nAddSize, out_of_space);
712 if (out_of_space) {
713 return AbortNode(state, "Disk space is too low!",
714 _("Disk space is too low!"));
715 }
716 if (bytes_allocated != 0 && IsPruneMode()) {
717 m_check_for_pruning = true;
718 }
719
720 return true;
721}
722
724 const CBlock &block, FlatFilePos &pos,
725 const CMessageHeader::MessageMagic &messageStart) const {
726 // Open history file to append
728 if (fileout.IsNull()) {
729 return error("WriteBlockToDisk: OpenBlockFile failed");
730 }
731
732 // Write index header
733 unsigned int nSize = GetSerializeSize(block, fileout.GetVersion());
734 fileout << messageStart << nSize;
735
736 // Write block
737 long fileOutPos = ftell(fileout.Get());
738 if (fileOutPos < 0) {
739 return error("WriteBlockToDisk: ftell failed");
740 }
741
742 pos.nPos = (unsigned int)fileOutPos;
743 fileout << block;
744
745 return true;
746}
747
748bool BlockManager::WriteUndoDataForBlock(const CBlockUndo &blockundo,
750 CBlockIndex &block) {
752 // Write undo information to disk
753 if (block.GetUndoPos().IsNull()) {
754 FlatFilePos _pos;
755 if (!FindUndoPos(state, block.nFile, _pos,
756 ::GetSerializeSize(blockundo, CLIENT_VERSION) + 40)) {
757 return error("ConnectBlock(): FindUndoPos failed");
758 }
759 if (!UndoWriteToDisk(blockundo, _pos, block.pprev->GetBlockHash(),
760 GetParams().DiskMagic())) {
761 return AbortNode(state, "Failed to write undo data");
762 }
763 // rev files are written in block height order, whereas blk files are
764 // written as blocks come in (often out of order) we want to flush the
765 // rev (undo) file once we've written the last block, which is indicated
766 // by the last height in the block file info as below; note that this
767 // does not catch the case where the undo writes are keeping up with the
768 // block writes (usually when a synced up node is getting newly mined
769 // blocks) -- this case is caught in the FindBlockPos function
770 if (_pos.nFile < m_last_blockfile &&
771 static_cast<uint32_t>(block.nHeight) ==
772 m_blockfile_info[_pos.nFile].nHeightLast) {
773 FlushUndoFile(_pos.nFile, true);
774 } else if (_pos.nFile == m_last_blockfile &&
775 static_cast<uint32_t>(block.nHeight) >
778 }
779 // update nUndoPos in block index
780 block.nUndoPos = _pos.nPos;
781 block.nStatus = block.nStatus.withUndo();
782 m_dirty_blockindex.insert(&block);
783 }
784
785 return true;
786}
787
789 const FlatFilePos &pos) const {
790 block.SetNull();
791
792 // Open history file to read
793 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
794 if (filein.IsNull()) {
795 return error("ReadBlockFromDisk: OpenBlockFile failed for %s",
796 pos.ToString());
797 }
798
799 // Read block
800 try {
801 filein >> block;
802 } catch (const std::exception &e) {
803 return error("%s: Deserialize or I/O error - %s at %s", __func__,
804 e.what(), pos.ToString());
805 }
806
807 // Check the header
808 if (!CheckProofOfWork(block.GetHash(), block.nBits, GetConsensus())) {
809 return error("ReadBlockFromDisk: Errors in block header at %s",
810 pos.ToString());
811 }
812
813 return true;
814}
815
817 const CBlockIndex &index) const {
818 const FlatFilePos block_pos{WITH_LOCK(cs_main, return index.GetBlockPos())};
819
820 if (!ReadBlockFromDisk(block, block_pos)) {
821 return false;
822 }
823
824 if (block.GetHash() != index.GetBlockHash()) {
825 return error("ReadBlockFromDisk(CBlock&, CBlockIndex*): GetHash() "
826 "doesn't match index for %s at %s",
827 index.ToString(), block_pos.ToString());
828 }
829
830 return true;
831}
832
834 const FlatFilePos &pos) const {
835 // Open history file to read
836 CAutoFile filein(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION);
837 if (filein.IsNull()) {
838 return error("ReadTxFromDisk: OpenBlockFile failed for %s",
839 pos.ToString());
840 }
841
842 // Read tx
843 try {
844 filein >> tx;
845 } catch (const std::exception &e) {
846 return error("%s: Deserialize or I/O error - %s at %s", __func__,
847 e.what(), pos.ToString());
848 }
849
850 return true;
851}
852
854 const FlatFilePos &pos) const {
855 // Open undo file to read
856 CAutoFile filein(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION);
857 if (filein.IsNull()) {
858 return error("ReadTxUndoFromDisk: OpenUndoFile failed for %s",
859 pos.ToString());
860 }
861
862 // Read undo data
863 try {
864 filein >> tx_undo;
865 } catch (const std::exception &e) {
866 return error("%s: Deserialize or I/O error - %s at %s", __func__,
867 e.what(), pos.ToString());
868 }
869
870 return true;
871}
872
874 const FlatFilePos *dbp) {
875 unsigned int nBlockSize = ::GetSerializeSize(block, CLIENT_VERSION);
876 FlatFilePos blockPos;
877 const auto position_known{dbp != nullptr};
878 if (position_known) {
879 blockPos = *dbp;
880 } else {
881 // When known, blockPos.nPos points at the offset of the block data in
882 // the blk file. That already accounts for the serialization header
883 // present in the file (the 4 magic message start bytes + the 4 length
884 // bytes = 8 bytes = BLOCK_SERIALIZATION_HEADER_SIZE). We add
885 // BLOCK_SERIALIZATION_HEADER_SIZE only for new blocks since they will
886 // have the serialization header added when written to disk.
887 nBlockSize +=
888 static_cast<unsigned int>(BLOCK_SERIALIZATION_HEADER_SIZE);
889 }
890 if (!FindBlockPos(blockPos, nBlockSize, nHeight, block.GetBlockTime(),
891 position_known)) {
892 error("%s: FindBlockPos failed", __func__);
893 return FlatFilePos();
894 }
895 if (!position_known) {
896 if (!WriteBlockToDisk(block, blockPos, GetParams().DiskMagic())) {
897 AbortNode("Failed to write block");
898 return FlatFilePos();
899 }
900 }
901 return blockPos;
902}
903
905 std::atomic<bool> &m_importing;
906
907public:
908 ImportingNow(std::atomic<bool> &importing) : m_importing{importing} {
909 assert(m_importing == false);
910 m_importing = true;
911 }
913 assert(m_importing == true);
914 m_importing = false;
915 }
916};
917
920 std::vector<fs::path> vImportFiles,
921 const fs::path &mempool_path) {
923
924 {
925 ImportingNow imp{chainman.m_blockman.m_importing};
926
927 // -reindex
928 if (fReindex) {
929 int nFile = 0;
930 // Map of disk positions for blocks with unknown parent (only used
931 // for reindex); parent hash -> child disk position, multiple
932 // children can have the same parent.
933 std::multimap<BlockHash, FlatFilePos> blocks_with_unknown_parent;
934 while (true) {
935 FlatFilePos pos(nFile, 0);
936 if (!fs::exists(chainman.m_blockman.GetBlockPosFilename(pos))) {
937 // No block files left to reindex
938 break;
939 }
940 FILE *file = chainman.m_blockman.OpenBlockFile(pos, true);
941 if (!file) {
942 // This error is logged in OpenBlockFile
943 break;
944 }
945 LogPrintf("Reindexing block file blk%05u.dat...\n",
946 (unsigned int)nFile);
947 chainman.LoadExternalBlockFile(
948 file, &pos, &blocks_with_unknown_parent, avalanche);
949 if (ShutdownRequested()) {
950 LogPrintf("Shutdown requested. Exit %s\n", __func__);
951 return;
952 }
953 nFile++;
954 }
955 WITH_LOCK(
956 ::cs_main,
957 chainman.m_blockman.m_block_tree_db->WriteReindexing(false));
958 fReindex = false;
959 LogPrintf("Reindexing finished\n");
960 // To avoid ending up in a situation without genesis block, re-try
961 // initializing (no-op if reindexing worked):
962 chainman.ActiveChainstate().LoadGenesisBlock();
963 }
964
965 // -loadblock=
966 for (const fs::path &path : vImportFiles) {
967 FILE *file = fsbridge::fopen(path, "rb");
968 if (file) {
969 LogPrintf("Importing blocks file %s...\n",
970 fs::PathToString(path));
971 chainman.LoadExternalBlockFile(
972 file, /*dbp=*/nullptr,
973 /*blocks_with_unknown_parent=*/nullptr, avalanche);
974 if (ShutdownRequested()) {
975 LogPrintf("Shutdown requested. Exit %s\n", __func__);
976 return;
977 }
978 } else {
979 LogPrintf("Warning: Could not open blocks file %s\n",
980 fs::PathToString(path));
981 }
982 }
983
984 // Reconsider blocks we know are valid. They may have been marked
985 // invalid by, for instance, running an outdated version of the node
986 // software.
987 const MapCheckpoints &checkpoints =
989 for (const MapCheckpoints::value_type &i : checkpoints) {
990 const BlockHash &hash = i.second;
991
992 LOCK(cs_main);
993 CBlockIndex *pblockindex =
994 chainman.m_blockman.LookupBlockIndex(hash);
995 if (pblockindex && !pblockindex->nStatus.isValid()) {
996 LogPrintf("Reconsidering checkpointed block %s ...\n",
997 hash.GetHex());
998 chainman.ActiveChainstate().ResetBlockFailureFlags(pblockindex);
999 }
1000
1001 if (pblockindex && pblockindex->nStatus.isOnParkedChain()) {
1002 LogPrintf("Unparking checkpointed block %s ...\n",
1003 hash.GetHex());
1004 chainman.ActiveChainstate().UnparkBlockAndChildren(pblockindex);
1005 }
1006 }
1007
1008 // scan for better chains in the block chain database, that are not yet
1009 // connected in the active best chain
1010
1011 // We can't hold cs_main during ActivateBestChain even though we're
1012 // accessing the chainman unique_ptrs since ABC requires us not to be
1013 // holding cs_main, so retrieve the relevant pointers before the ABC
1014 // call.
1015 for (Chainstate *chainstate :
1016 WITH_LOCK(::cs_main, return chainman.GetAll())) {
1018 if (!chainstate->ActivateBestChain(state, nullptr, avalanche)) {
1019 LogPrintf("Failed to connect best block (%s)\n",
1020 state.ToString());
1021 StartShutdown();
1022 return;
1023 }
1024 }
1025
1026 if (chainman.m_blockman.StopAfterBlockImport()) {
1027 LogPrintf("Stopping after block import\n");
1028 StartShutdown();
1029 return;
1030 }
1031 } // End scope of ImportingNow
1032 chainman.ActiveChainstate().LoadMempool(mempool_path);
1033}
1034} // namespace node
void ScheduleBatchPriority()
On platforms that support it, tell the kernel the calling thread is CPU-intensive and non-interactive...
@ TREE
All parent headers found, difficulty matches, timestamp >= median previous, checkpoint.
arith_uint256 GetBlockProof(const CBlockIndex &block)
Definition: chain.cpp:74
bool IsNull() const
Return true if the wrapped FILE* is nullptr, false otherwise.
Definition: streams.h:570
FILE * Get() const
Get wrapped FILE* without transfer of ownership.
Definition: streams.h:567
int GetVersion() const
Definition: streams.h:640
Nodes collect new transactions into a block, hash them into a hash tree, and scan through nonce value...
Definition: block.h:23
BlockHash GetHash() const
Definition: block.cpp:11
uint32_t nBits
Definition: block.h:30
BlockHash hashPrevBlock
Definition: block.h:27
int64_t GetBlockTime() const
Definition: block.h:57
Definition: block.h:60
void SetNull()
Definition: block.h:80
The block chain is a tree shaped structure starting with the genesis block at the root,...
Definition: blockindex.h:25
std::string ToString() const
Definition: blockindex.cpp:28
CBlockIndex * pprev
pointer to the index of the predecessor of this block
Definition: blockindex.h:32
void BuildSkip()
Build the skiplist pointer for this entry.
Definition: blockindex.cpp:83
arith_uint256 nChainWork
(memory only) Total amount of work (expected number of hashes) in the chain up to and including this ...
Definition: blockindex.h:51
const BlockHash * phashBlock
pointer to the hash of the block, if any.
Definition: blockindex.h:29
uint32_t nTime
Definition: blockindex.h:92
unsigned int nTimeMax
(memory only) Maximum nTime in the chain up to and including this block.
Definition: blockindex.h:104
int32_t nSequenceId
(memory only) Sequential id assigned to distinguish order in which blocks are received.
Definition: blockindex.h:98
FlatFilePos GetUndoPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: blockindex.h:123
unsigned int nTx
Number of transactions in this block.
Definition: blockindex.h:60
bool RaiseValidity(enum BlockValidity nUpTo) EXCLUSIVE_LOCKS_REQUIRED(
Raise the validity level of this block index entry.
Definition: blockindex.h:226
int64_t nTimeReceived
(memory only) block header metadata
Definition: blockindex.h:101
BlockHash GetBlockHash() const
Definition: blockindex.h:146
int nHeight
height of the entry in the chain. The genesis block has height 0
Definition: blockindex.h:38
FlatFilePos GetBlockPos() const EXCLUSIVE_LOCKS_REQUIRED(
Definition: blockindex.h:113
Undo information for a CBlock.
Definition: undo.h:73
const CCheckpointData & Checkpoints() const
Definition: chainparams.h:134
Reads data from an underlying stream, while hashing the read data.
Definition: hash.h:170
std::array< uint8_t, MESSAGE_START_SIZE > MessageMagic
Definition: protocol.h:46
A mutable version of CTransaction.
Definition: transaction.h:274
Restore the UTXO in a Coin at a given COutPoint.
Definition: undo.h:62
Chainstate stores and provides an API to update our local knowledge of the current best chain.
Definition: validation.h:699
Provides an interface for creating and interacting with one or two chainstates: an IBD chainstate gen...
Definition: validation.h:1154
void LoadExternalBlockFile(FILE *fileIn, FlatFilePos *dbp=nullptr, std::multimap< BlockHash, FlatFilePos > *blocks_with_unknown_parent=nullptr, avalanche::Processor *const avalanche=nullptr)
Import blocks from an external file.
SnapshotCompletionResult MaybeCompleteSnapshotValidation(std::function< void(bilingual_str)> shutdown_fnc=[](bilingual_str msg) { AbortNode(msg.original, msg);}) EXCLUSIVE_LOCKS_REQUIRED(Chainstate & ActiveChainstate() const
Once the background validation chainstate has reached the height which is the base of the UTXO snapsh...
const CChainParams & GetParams() const
Definition: validation.h:1248
Chainstate &InitializeChainstate(CTxMemPool *mempool) EXCLUSIVE_LOCKS_REQUIRED(std::vector< Chainstate * GetAll)()
Instantiate a new chainstate.
Definition: validation.h:1359
node::BlockManager m_blockman
A single BlockManager instance is shared across each constructed chainstate to avoid duplicating bloc...
Definition: validation.h:1294
FlatFileSeq represents a sequence of numbered files storing raw data.
Definition: flatfile.h:49
fs::path FileName(const FlatFilePos &pos) const
Get the name of the file at the given position.
Definition: flatfile.cpp:24
size_t Allocate(const FlatFilePos &pos, size_t add_size, bool &out_of_space)
Allocate additional space in a file after the given starting position.
Definition: flatfile.cpp:51
FILE * Open(const FlatFilePos &pos, bool read_only=false)
Open a handle to the file at the given position.
Definition: flatfile.cpp:28
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:100
uint256 GetHash()
Compute the double-SHA256 hash of all data written to this object.
Definition: hash.h:114
std::string ToString() const
Definition: validation.h:125
bool IsNull() const
Definition: uint256.h:32
std::string GetHex() const
Definition: uint256.cpp:16
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
const kernel::BlockManagerOpts m_opts
Definition: blockstorage.h:181
std::set< int > m_dirty_fileinfo
Dirty block file entries.
Definition: blockstorage.h:169
bool ReadBlockFromDisk(CBlock &block, const FlatFilePos &pos) const
Functions for disk access for blocks.
bool WriteBlockToDisk(const CBlock &block, FlatFilePos &pos, const CMessageHeader::MessageMagic &messageStart) const
FlatFileSeq UndoFileSeq() const
RecursiveMutex cs_LastBlockFile
Definition: blockstorage.h:140
const CChainParams & GetParams() const
Definition: blockstorage.h:78
void FindFilesToPrune(std::set< int > &setFilesToPrune, uint64_t nPruneAfterHeight, int chain_tip_height, int prune_height, bool is_ibd)
Prune block and undo files (blk???.dat and undo???.dat) so that the disk space used is less than a us...
bool WriteUndoDataForBlock(const CBlockUndo &blockundo, BlockValidationState &state, CBlockIndex &block) EXCLUSIVE_LOCKS_REQUIRED(FlatFilePos SaveBlockToDisk(const CBlock &block, int nHeight, const FlatFilePos *dbp)
Store block on disk.
Definition: blockstorage.h:242
void FindFilesToPruneManual(std::set< int > &setFilesToPrune, int nManualPruneHeight, int chain_tip_height)
Calculate the block/rev files to delete based on height specified by user with RPC command pruneblock...
FlatFileSeq BlockFileSeq() const
void FlushUndoFile(int block_file, bool finalize=false)
const CBlockIndex *GetFirstStoredBlock(const CBlockIndex &start_block) EXCLUSIVE_LOCKS_REQUIRED(bool m_have_pruned
Find the first block that is not pruned.
Definition: blockstorage.h:275
FILE * OpenUndoFile(const FlatFilePos &pos, bool fReadOnly=false) const
Open an undo file (rev?????.dat)
bool StopAfterBlockImport() const
Definition: blockstorage.h:257
bool LoadBlockIndex() EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Load the blocktree off disk and into memory.
void PruneOneBlockFile(const int fileNumber) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Mark one block file as pruned (modify associated database entries)
CBlockIndex * LookupBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
bool ReadTxFromDisk(CMutableTransaction &tx, const FlatFilePos &pos) const
Functions for disk access for txs.
const Consensus::Params & GetConsensus() const
Definition: blockstorage.h:79
CBlockIndex * InsertBlockIndex(const BlockHash &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Create a new block index entry for a given block hash.
bool ReadTxUndoFromDisk(CTxUndo &tx, const FlatFilePos &pos) const
bool UndoReadFromDisk(CBlockUndo &blockundo, const CBlockIndex &index) const
fs::path GetBlockPosFilename(const FlatFilePos &pos) const
Translation to a filesystem path.
bool FindBlockPos(FlatFilePos &pos, unsigned int nAddSize, unsigned int nHeight, uint64_t nTime, bool fKnown)
uint64_t GetPruneTarget() const
Attempt to stay below this number of bytes of block files.
Definition: blockstorage.h:249
void UnlinkPrunedFiles(const std::set< int > &setFilesToPrune) const
Actually unlink the specified files.
bool WriteBlockIndexDB() EXCLUSIVE_LOCKS_REQUIRED(bool LoadBlockIndexDB() EXCLUSIVE_LOCKS_REQUIRED(void ScanAndUnlinkAlreadyPrunedFiles() EXCLUSIVE_LOCKS_REQUIRED(CBlockIndex * AddToBlockIndex(const CBlockHeader &block, CBlockIndex *&best_header) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Remove any pruned block & undo files that are still on disk.
uint64_t CalculateCurrentUsage()
Calculate the amount of disk space the block & undo files currently use.
bool UndoWriteToDisk(const CBlockUndo &blockundo, FlatFilePos &pos, const BlockHash &hashBlock, const CMessageHeader::MessageMagic &messageStart) const
const CBlockIndex * GetLastCheckpoint(const CCheckpointData &data) EXCLUSIVE_LOCKS_REQUIRED(cs_main)
Returns last CBlockIndex* that is a checkpoint.
std::set< CBlockIndex * > m_dirty_blockindex
Dirty block index entries.
Definition: blockstorage.h:166
bool m_check_for_pruning
Global flag to indicate we should check to see if there are block/undo files that should be deleted.
Definition: blockstorage.h:161
bool FindUndoPos(BlockValidationState &state, int nFile, FlatFilePos &pos, unsigned int nAddSize)
bool IsPruneMode() const
Whether running in -prune mode.
Definition: blockstorage.h:246
void CleanupBlockRevFiles() const
std::atomic< bool > m_importing
Definition: blockstorage.h:189
std::vector< CBlockFileInfo > m_blockfile_info
Definition: blockstorage.h:141
CBlockFileInfo * GetBlockFileInfo(size_t n)
Get block file info entry for one block file.
bool IsBlockPruned(const CBlockIndex *pblockindex) EXCLUSIVE_LOCKS_REQUIRED(void UpdatePruneLock(const std::string &name, const PruneLockInfo &lock_info) EXCLUSIVE_LOCKS_REQUIRED(FILE OpenBlockFile)(const FlatFilePos &pos, bool fReadOnly=false) const
Check whether the block associated with this index entry is pruned or not.
Definition: blockstorage.h:288
unsigned int m_undo_height_in_last_blockfile
Definition: blockstorage.h:154
std::vector< CBlockIndex * > GetAllBlockIndices() EXCLUSIVE_LOCKS_REQUIRED(std::multimap< CBlockIndex *, CBlockIndex * > m_blocks_unlinked
All pairs A->B, where A (or one of its ancestors) misses transactions, but B has transactions.
Definition: blockstorage.h:193
void FlushBlockFile(bool fFinalize=false, bool finalize_undo=false)
ImportingNow(std::atomic< bool > &importing)
std::atomic< bool > & m_importing
256-bit opaque blob.
Definition: uint256.h:129
static constexpr int CLIENT_VERSION
bitcoind-res.rc includes this file, but it cannot cope with real c++ code.
Definition: clientversion.h:38
RecursiveMutex cs_main
Mutex to guard access to validation specific variables, such as reading or changing the chainstate.
Definition: cs_main.cpp:7
std::map< int, BlockHash > MapCheckpoints
Definition: chainparams.h:31
bool error(const char *fmt, const Args &...args)
Definition: logging.h:263
#define LogPrint(category,...)
Definition: logging.h:238
#define LogPrintf(...)
Definition: logging.h:227
unsigned int nHeight
@ PRUNE
Definition: logging.h:54
@ BLOCKSTORE
Definition: logging.h:68
static bool exists(const path &p)
Definition: fs.h:102
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:142
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:30
Definition: init.h:28
static const unsigned int UNDOFILE_CHUNK_SIZE
The pre-allocation chunk size for rev?????.dat files (since 0.8)
Definition: blockstorage.h:45
void ThreadImport(ChainstateManager &chainman, avalanche::Processor *const avalanche, std::vector< fs::path > vImportFiles, const fs::path &mempool_path)
static constexpr unsigned int BLOCKFILE_CHUNK_SIZE
The pre-allocation chunk size for blk?????.dat files (since 0.8)
Definition: blockstorage.h:43
static constexpr size_t BLOCK_SERIALIZATION_HEADER_SIZE
Size of header written by WriteBlockToDisk before a serialized CBlock.
Definition: blockstorage.h:50
static const unsigned int MAX_BLOCKFILE_SIZE
The maximum size of a blk?????.dat file (since 0.8)
Definition: blockstorage.h:47
std::atomic_bool fReindex
bool CheckProofOfWork(const BlockHash &hash, uint32_t nBits, const Consensus::Params &params)
Check whether a block hash satisfies the proof-of-work requirement specified by nBits.
Definition: pow.cpp:87
const char * name
Definition: rest.cpp:47
reverse_range< T > reverse_iterate(T &x)
@ SER_DISK
Definition: serialize.h:153
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1258
bool AbortNode(const std::string &strMessage, bilingual_str user_message)
Abort with a message.
Definition: shutdown.cpp:20
bool ShutdownRequested()
Returns true if a shutdown is requested, false otherwise.
Definition: shutdown.cpp:85
void StartShutdown()
Request shutdown of the application.
Definition: shutdown.cpp:55
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:100
A BlockHash is a unqiue identifier for a block.
Definition: blockhash.h:13
MapCheckpoints mapCheckpoints
Definition: chainparams.h:34
int nFile
Definition: flatfile.h:15
std::string ToString() const
Definition: flatfile.cpp:20
unsigned int nPos
Definition: flatfile.h:16
bool IsNull() const
Definition: flatfile.h:40
#define LOCK2(cs1, cs2)
Definition: sync.h:309
#define LOCK(cs)
Definition: sync.h:306
#define WITH_LOCK(cs, code)
Run code while locking a mutex.
Definition: sync.h:357
static int count
Definition: tests.c:31
#define EXCLUSIVE_LOCKS_REQUIRED(...)
Definition: threadsafety.h:56
int64_t GetTime()
DEPRECATED Use either ClockType::now() or Now<TimePointType>() if a cast is needed.
Definition: time.cpp:109
bilingual_str _(const char *psz)
Translation function.
Definition: translation.h:68
int atoi(const std::string &str)
AssertLockHeld(pool.cs)
assert(!tx.IsCoinBase())
static const unsigned int MIN_BLOCKS_TO_KEEP
Block files containing a block-height within MIN_BLOCKS_TO_KEEP of ActiveChain().Tip() will not be pr...
Definition: validation.h:95