6#ifndef VERIBLOCK_POP_CPP_STORAGE_UTIL_HPP
7#define VERIBLOCK_POP_CPP_STORAGE_UTIL_HPP
10#include <veriblock/pop/blockchain/alt_block_tree.hpp>
11#include <veriblock/pop/logger.hpp>
12#include <veriblock/pop/storage/block_reader.hpp>
13#include <veriblock/pop/validation_state.hpp>
15#include "block_batch.hpp"
22template <
typename BlockTreeT>
24 const typename BlockTreeT::hash_t& tiphash,
25 std::vector<typename BlockTreeT::stored_index_t>& blocks,
28 using stored_index_t =
typename BlockTreeT::stored_index_t;
30 if (blocks.size() == 0)
return true;
32 VBK_LOG_INFO(
"Loading %d %s blocks with tip %s",
34 BlockTreeT::block_t::name(),
36 VBK_ASSERT(tree.isBootstrapped() &&
"tree must be bootstrapped");
39 std::sort(blocks.begin(),
41 [](
const stored_index_t& a,
const stored_index_t& b) {
42 return a.height < b.height;
45 for (
const auto& block : blocks) {
47 if (!tree.loadBlockForward(block, fast_load, state)) {
48 return state.Invalid(
"load-tree");
52 if (!tree.loadTip(tiphash, state)) {
53 return state.Invalid(
"load-tree");
56 auto* t = tree.getBestChain().tip();
57 VBK_ASSERT(t !=
nullptr);
63template <
typename BlockIndexT>
64void validateBlockIndex(
const BlockIndexT&);
67template <
typename BlockTreeT>
71 std::function<
void(
const typename BlockTreeT::index_t&)> validator) {
72 using index_t =
typename BlockTreeT::index_t;
73 std::vector<const index_t*> dirty_indices;
76 for (
auto& index : tree.getAllBlocks()) {
77 if (index->isDirty()) {
79 dirty_indices.push_back(index);
86 std::sort(dirty_indices.begin(),
88 [](
const index_t* a,
const index_t* b) {
89 return b->getHeight() < a->getHeight();
93 for (
const index_t* index : dirty_indices) {
95 batch.writeBlock(index->getHash(),
96 tree.makePrevHash(index->getHash()),
97 index->toStoredBlockIndex());
100 batch.writeTip(tree.getBestChain().tip()->getHash());
104template <
typename BlockTreeT>
105void saveTree(BlockTreeT& tree, BlockBatch& batch) {
106 saveTree(tree, batch, &validateBlockIndex<typename BlockTreeT::index_t>);
Class that is used for storing validation state.
void saveTrees(const AltBlockTree &tree, BlockBatch &batch)
Save all (BTC/VBK/ALT) trees on disk in a single Batch.
std::string HexStr(const T itbegin, const T itend)
Convert bytes to hex.
bool loadTree(BlockTreeT &tree, const typename BlockTreeT::hash_t &tiphash, std::vector< typename BlockTreeT::stored_index_t > &blocks, bool fast_load, ValidationState &state)
efficiently loads blocks into tree (they must be sorted by height) and does validation of these block...
bool loadTrees(AltBlockTree &tree, bool fast_load, ValidationState &state)
Load all (ALT/VBK/BTC) trees from disk into memory.
Represents simplified view on Altchain's block tree, maintains VBK tree and BTC tree.
An interface which represents single write batch of a group of blocks.