Scorum
block_log.hpp
Go to the documentation of this file.
1 #pragma once
2 #include <fc/filesystem.hpp>
4 
5 namespace scorum {
6 namespace chain {
7 
8 using namespace scorum::protocol;
9 
10 namespace detail {
11 class block_log_impl;
12 }
13 
14 /* The block log is an external append only log of the blocks. Blocks should only be written
15  * to the log after they irreverisble as the log is append only. The log is a doubly linked
16  * list of blocks. There is a secondary index file of only block positions that enables O(1)
17  * random access lookup by block number.
18  *
19  * +---------+----------------+---------+----------------+-----+------------+-------------------+
20  * | Block 1 | Pos of Block 1 | Block 2 | Pos of Block 2 | ... | Head Block | Pos of Head Block |
21  * +---------+----------------+---------+----------------+-----+------------+-------------------+
22  *
23  * +----------------+----------------+-----+-------------------+
24  * | Pos of Block 1 | Pos of Block 2 | ... | Pos of Head Block |
25  * +----------------+----------------+-----+-------------------+
26  *
27  * The block log can be walked in order by deserializing a block, skipping 8 bytes, deserializing a
28  * block, repeat... The head block of the file can be found by seeking to the position contained
29  * in the last 8 bytes the file. The block log can be read backwards by jumping back 8 bytes, following
30  * the position, reading the block, jumping back 8 bytes, etc.
31  *
32  * Blocks can be accessed at random via block number through the index file. Seek to 8 * (block_num - 1)
33  * to find the position of the block in the main file.
34  *
35  * The main file is the only file that needs to persist. The index file can be reconstructed during a
36  * linear scan of the main file.
37  */
38 
39 class block_log
40 {
41 public:
42  block_log();
43  ~block_log();
44 
45  void open(const fc::path& file);
46  void close();
47  bool is_open() const;
48 
49  static fc::path block_log_index_path(const fc::path& block_log_file);
50 
51  uint64_t append(const signed_block& b);
52  void flush();
53  std::pair<signed_block, uint64_t> read_block(uint64_t file_pos) const;
54  optional<signed_block> read_block_by_num(uint32_t block_num) const;
55 
59  uint64_t get_block_pos(uint32_t block_num) const;
60  signed_block read_head() const;
61  const optional<signed_block>& head() const;
62 
63  static const uint64_t npos = std::numeric_limits<uint64_t>::max();
64 
65 private:
66  void construct_index();
67 
68  std::unique_ptr<detail::block_log_impl> my;
69 };
70 }
71 }
Definition: asset.cpp:15