-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathblock_log.cpp
1840 lines (1505 loc) · 82.2 KB
/
block_log.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <eosio/chain/block_log.hpp>
#include <eosio/chain/block_log_config.hpp>
#include <eosio/chain/exceptions.hpp>
#include <eosio/chain/log_catalog.hpp>
#include <eosio/chain/log_data_base.hpp>
#include <eosio/chain/log_index.hpp>
#include <fc/bitutil.hpp>
#include <fc/io/raw.hpp>
#include <mutex>
#include <string>
#if defined(__BYTE_ORDER__)
static_assert(__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__);
#endif
namespace eosio { namespace chain {
enum versions {
initial_version = 1, ///< complete block log from genesis
block_x_start_version = 2, ///< adds optional partial block log, cannot be used for replay without snapshot
///< this is in the form of an first_block_num that is written immediately after the version
genesis_state_or_chain_id_version = 3 ///< improvement on version 2 to not require the genesis state be provided when not starting from block 1
};
constexpr uint32_t block_log::min_supported_version = initial_version;
constexpr uint32_t block_log::max_supported_version = genesis_state_or_chain_id_version;
namespace detail {
constexpr uint32_t pruned_version_flag = 1 << 31;
}
// copy up to n bytes from src to dest
void copy_file_content(fc::cfile& src, fc::cfile& dest, uint64_t n) {
// calculate the number of bytes remaining in the src file can be copied
auto current_pos = src.tellp();
src.seek_end(0);
auto end_pos = src.tellp();
src.seek(current_pos);
uint64_t remaining = end_pos - current_pos;
// copy up to 4M bytes each iteration until done
remaining = std::min<uint64_t>(n, remaining);
std::vector<char> buf(4 * 1024 * 1024);
while (remaining > 0) {
uint64_t len = std::min<uint64_t>(remaining, buf.size());
src.read(buf.data(), len);
dest.write(buf.data(), len);
remaining -= len;
}
}
struct block_log_preamble {
uint32_t ver = 0;
uint32_t first_block_num = 0;
std::variant<genesis_state, chain_id_type> chain_context;
uint32_t version() const { return ver & ~detail::pruned_version_flag; }
bool is_currently_pruned() const { return ver & detail::pruned_version_flag; }
chain_id_type chain_id() const {
return std::visit(overloaded{ [](const chain_id_type& id) { return id; },
[](const genesis_state& state) { return state.compute_chain_id(); } },
chain_context);
}
constexpr static int nbytes_with_chain_id = // the bytes count when the preamble contains chain_id
sizeof(uint32_t) + sizeof(first_block_num) + sizeof(chain_id_type) + sizeof(block_log::npos);
template <typename Stream>
void read_from(Stream& ds, const std::filesystem::path& log_path) {
ds.read((char*)&ver, sizeof(ver));
EOS_ASSERT(version() > 0, block_log_exception, "Block log was not setup properly");
EOS_ASSERT(block_log::is_supported_version(version()), block_log_unsupported_version,
"Unsupported version of block log. Block log version is ${version} while code supports version(s) "
"[${min},${max}], log file: ${log}",
("version", version())("min", block_log::min_supported_version)(
"max", block_log::max_supported_version)("log", log_path));
first_block_num = 1;
if (version() != initial_version) {
ds.read(reinterpret_cast<char*>(&first_block_num), sizeof(first_block_num));
}
if (block_log::contains_genesis_state(version(), first_block_num)) {
chain_context.emplace<genesis_state>();
fc::raw::unpack(ds, std::get<genesis_state>(chain_context));
} else if (block_log::contains_chain_id(version(), first_block_num)) {
chain_context = chain_id_type::empty_chain_id();
ds >> std::get<chain_id_type>(chain_context);
} else {
EOS_THROW(block_log_exception,
"Block log is not supported. version: ${ver} and first_block_num: ${fbn} does not contain "
"a genesis_state nor a chain_id.",
("ver", version())("fbn", first_block_num));
}
if (version() != initial_version) {
auto expected_totem = block_log::npos;
std::decay_t<decltype(block_log::npos)> actual_totem;
ds.read((char*)&actual_totem, sizeof(actual_totem));
EOS_ASSERT(actual_totem == expected_totem, block_log_exception,
"Expected separator between block log header and blocks was not found( expected: ${e}, actual: "
"${a} )",
("e", fc::to_hex((char*)&expected_totem, sizeof(expected_totem)))(
"a", fc::to_hex((char*)&actual_totem, sizeof(actual_totem))));
}
}
template <typename Stream>
void write_exclude_version(Stream& ds) const {
// write the rest of header without the leading version field
if (version() != initial_version) {
ds.write(reinterpret_cast<const char*>(&first_block_num), sizeof(first_block_num));
std::visit(overloaded{ [&ds](const chain_id_type& id) { ds << id; },
[&ds](const genesis_state& state) {
auto data = fc::raw::pack(state);
ds.write(data.data(), data.size());
} },
chain_context);
auto totem = block_log::npos;
ds.write(reinterpret_cast<const char*>(&totem), sizeof(totem));
} else {
const auto& state = std::get<genesis_state>(chain_context);
auto data = fc::raw::pack(state);
ds.write(data.data(), data.size());
}
}
template <typename Stream>
void write_to(Stream& ds) const {
ds.write(reinterpret_cast<const char*>(&ver), sizeof(ver));
write_exclude_version(ds);
}
void write_to(fc::datastream<fc::cfile>& ds) const {
uint32_t local_ver = 0;
ds.write(reinterpret_cast<const char*>(&local_ver), sizeof(local_ver));
write_exclude_version(ds);
ds.flush();
ds.seek(0);
ds.write(reinterpret_cast<const char*>(&ver), sizeof(ver));
ds.flush();
}
};
namespace {
class index_writer {
public:
index_writer(const std::filesystem::path& block_index_name, uint32_t blocks_expected, bool create = true) {
index_file.set_file_path(block_index_name);
auto mode = create ? fc::cfile::truncate_rw_mode : fc::cfile::update_rw_mode;
index_file.open(mode);
index_file.seek(sizeof(uint64_t) * (blocks_expected - 1));
}
void write(uint64_t pos) {
index_file.write((const char*)&pos, sizeof(pos));
if (index_file.tellp() >= 2 * sizeof(uint64_t))
index_file.skip(-2 * sizeof(uint64_t));
}
void close() { index_file.close(); }
private:
fc::cfile index_file;
};
struct bad_block_exception {
std::exception_ptr inner;
};
template <typename Stream>
signed_block_ptr read_block(Stream&& ds, uint32_t expect_block_num = 0) {
auto block = std::make_shared<signed_block>();
fc::raw::unpack(ds, *block);
if (expect_block_num != 0) {
EOS_ASSERT(!!block && block->block_num() == expect_block_num, block_log_exception,
"Wrong block was read from block log.");
}
return block;
}
template <typename Stream>
std::vector<char> read_serialized_block(Stream&& ds, uint64_t block_size) {
std::vector<char> buff;
buff.resize(block_size);
ds.read(buff.data(), block_size);
return buff;
}
template <typename Stream>
signed_block_header read_block_header(Stream&& ds, uint32_t expect_block_num) {
signed_block_header bh;
fc::raw::unpack(ds, bh);
EOS_ASSERT(bh.block_num() == expect_block_num, block_log_exception,
"Wrong block header was read from block log.",
("returned", bh.block_num())("expected", expect_block_num));
return bh;
}
/// Provide the read only view of the blocks.log file
class block_log_data : public chain::log_data_base<block_log_data> {
block_log_preamble preamble;
uint64_t first_block_pos = 0;
std::size_t size_ = 0;
public:
block_log_data() = default;
block_log_data(const std::filesystem::path& path) { open(path); }
uint64_t first_block_position() const { return first_block_pos; }
const block_log_preamble& get_preamble() const { return preamble; }
void open(const std::filesystem::path& path) {
if (file.is_open())
file.close();
file.set_file_path(path);
file.open("rb");
preamble.read_from(file, file.get_file_path());
first_block_pos = file.tellp();
file.seek_end(0);
size_ = file.tellp();
}
uint64_t size() const { return size_; }
uint32_t version() { return preamble.version(); }
uint32_t first_block_num() const { return preamble.first_block_num; }
uint32_t number_of_blocks();
chain_id_type chain_id() { return preamble.chain_id(); }
bool is_currently_pruned() const { return preamble.is_currently_pruned(); }
uint64_t end_of_block_position() const { return is_currently_pruned() ? size() - sizeof(uint32_t) : size(); }
std::optional<genesis_state> get_genesis_state() {
return std::visit(
overloaded{ [](const chain_id_type&) { return std::optional<genesis_state>{}; },
[](const genesis_state& state) { return std::optional<genesis_state>{ state }; } },
preamble.chain_context);
}
uint32_t block_num_at(uint64_t position) {
// to derive blknum_offset==14 see block_header.hpp and note on disk struct is packed
// block_timestamp_type timestamp; //bytes 0:3
// account_name producer; //bytes 4:11
// uint16_t confirmed; //bytes 12:13
// block_id_type previous; //bytes 14:45, low 4 bytes is big endian block number
// of previous block
int blknum_offset = 14;
EOS_ASSERT(position + blknum_offset + sizeof(uint32_t) <= size(), block_log_exception,
"Read outside of file: position ${position}, blknum_offset ${o}, file size ${s}",
("position", position)("o", blknum_offset)("s", size()));
uint32_t prev_block_num = read_data_at<uint32_t>(file, position + blknum_offset);
return fc::endian_reverse_u32(prev_block_num) + 1;
}
auto& ro_stream_at(uint64_t pos) {
file.seek(pos);
return file;
}
uint64_t remaining() const { return size() - file.tellp(); }
/**
* Validate a block log entry WITHOUT deserializing the entire block data.
**/
void light_validate_block_entry_at(uint64_t pos, uint32_t expected_block_num) {
const uint32_t actual_block_num = block_num_at(pos);
EOS_ASSERT(actual_block_num == expected_block_num, block_log_exception,
"At position ${pos} expected to find block number ${exp_bnum} but found ${act_bnum}",
("pos", pos)("exp_bnum", expected_block_num)("act_bnum", actual_block_num));
}
/**
* Validate a block log entry by deserializing the entire block data.
*
* @returns The tuple of block number and block id in the entry
**/
std::tuple<uint32_t, block_id_type> full_validate_block_entry(uint32_t previous_block_num,
const block_id_type& previous_block_id,
signed_block& entry) {
uint64_t pos = file.tellp();
try {
fc::raw::unpack(file, entry);
} catch (...) { throw bad_block_exception{ std::current_exception() }; }
const block_header& header = entry;
auto id = header.calculate_id();
auto block_num = block_header::num_from_id(id);
if (block_num != previous_block_num + 1) {
elog("Block ${num} (${id}) skips blocks. Previous block in block log is block ${prev_num} (${previous})",
("num", block_num)("id", id)("prev_num", previous_block_num)("previous", previous_block_id));
}
if (!previous_block_id.empty() && previous_block_id != header.previous) {
elog("Block ${num} (${id}) does not link back to previous block. "
"Expected previous: ${expected}. Actual previous: ${actual}.",
("num", block_num)("id", id)("expected", previous_block_id)("actual", header.previous));
}
uint64_t tmp_pos = std::numeric_limits<uint64_t>::max();
if (remaining() >= sizeof(tmp_pos)) {
file.read(reinterpret_cast<char*>(&tmp_pos), sizeof(tmp_pos));
}
EOS_ASSERT(pos == tmp_pos, block_log_exception,
"the block position for block ${num} at the end of a block entry is incorrect",
("num", block_num));
return std::make_tuple(block_num, id);
}
std::tuple<uint64_t, uint32_t, std::string>
full_validate_blocks(uint32_t last_block_num, const std::filesystem::path& blocks_dir, fc::time_point now);
void construct_index(const std::filesystem::path& index_file_path);
};
using block_log_index = eosio::chain::log_index<block_log_exception>;
/// Provide the read only view for both blocks.log and blocks.index files
struct block_log_bundle {
std::filesystem::path block_file_name, index_file_name; // full pathname for blocks.log and blocks.index
block_log_data log_data;
block_log_index log_index;
block_log_bundle(std::filesystem::path block_file, std::filesystem::path index_file, bool validate_indx)
: block_file_name(std::move(block_file)), index_file_name(std::move(index_file)) {
log_data.open(block_file_name);
log_index.open(index_file_name);
EOS_ASSERT(!log_data.get_preamble().is_currently_pruned(), block_log_unsupported_version,
"Block log is currently in pruned format, it must be vacuumed before doing this operation");
if (validate_indx)
validate_index();
}
explicit block_log_bundle(const std::filesystem::path& block_dir, bool validate_index=true)
: block_log_bundle(block_dir / "blocks.log", block_dir / "blocks.index", validate_index) {}
// throws if not valid
void validate_index() {
uint32_t log_num_blocks = log_data.num_blocks();
uint32_t index_num_blocks = log_index.num_blocks();
EOS_ASSERT(
log_num_blocks == index_num_blocks, block_log_exception,
"${block_file_name} says it has ${log_num_blocks} blocks which disagrees with ${index_num_blocks} "
"indicated by ${index_file_name}",
("block_file_name", block_file_name)("log_num_blocks", log_num_blocks)(
"index_num_blocks", index_num_blocks)("index_file_name", index_file_name));
}
};
/// Used to traverse the block position (i.e. the last 8 bytes in each block log entry) of the blocks.log file
class reverse_block_position_iterator {
fc::datastream<fc::cfile>& file;
uint64_t first_block_pos;
uint64_t end_of_block_pos;
uint64_t current_position;
uint64_t get_value() {
EOS_ASSERT(
current_position > first_block_pos && current_position <= end_of_block_pos, block_log_exception,
"Block log file formatting is incorrect, it contains a block position value: ${pos}, which is not "
"in the range of (${begin_pos},${last_pos})",
("pos", current_position)("begin_pos", first_block_pos)("last_pos", end_of_block_pos));
uint64_t value;
file.seek(current_position - sizeof(uint64_t));
fc::raw::unpack(file, value);
return value;
}
public:
reverse_block_position_iterator(fc::datastream<fc::cfile>& data, uint64_t first_block_pos,
uint64_t end_of_block_pos)
: file(data), first_block_pos(first_block_pos), end_of_block_pos(end_of_block_pos),
current_position(end_of_block_pos) {}
uint64_t get_value_then_advance() {
current_position = get_value();
return current_position;
}
uint64_t add_value_then_advance(uint64_t offset) {
current_position = get_value() + offset;
file.skip(-sizeof(uint64_t));
fc::raw::pack(file, current_position);
return current_position;
}
bool done() const { return current_position <= first_block_pos; }
};
void adjust_block_positions(index_writer& index, fc::datastream<fc::cfile>& block_file,
uint64_t first_block_position, int64_t offset) {
block_file.seek_end(0);
// walk along the block position of each block entry and add its value by offset
auto iter = reverse_block_position_iterator{ block_file, first_block_position, block_file.tellp() };
while (!iter.done()) { index.write(iter.add_value_then_advance(offset)); }
}
uint32_t block_log_data::number_of_blocks() {
const uint32_t num_blocks =
first_block_position() == end_of_block_position() ? 0 : last_block_num() - first_block_num() + 1;
return num_blocks;
}
void block_log_data::construct_index(const std::filesystem::path& index_file_path) {
std::string index_file_name = index_file_path.generic_string();
ilog("Will write new blocks.index file ${file}", ("file", index_file_name));
const uint32_t num_blocks = number_of_blocks();
ilog("block log version= ${version}, number of blocks ${n}", ("version", this->version())("n", num_blocks));
if (num_blocks == 0) {
return;
}
ilog("first block= ${first} last block= ${last}",
("first", this->first_block_num())("last", (this->last_block_num())));
index_writer index(index_file_path, num_blocks);
uint32_t blocks_remaining = this->num_blocks();
for (auto iter = reverse_block_position_iterator{ file, first_block_position(), end_of_block_position() };
!iter.done() && blocks_remaining > 0; --blocks_remaining) {
auto pos = iter.get_value_then_advance();
index.write(pos);
if ((blocks_remaining & 0xfffff) == 0)
ilog("blocks remaining to index: ${blocks_left} position in log file: ${pos}",
("blocks_left", blocks_remaining)("pos", pos));
}
}
} // namespace
struct block_log_verifier {
chain_id_type chain_id = chain_id_type::empty_chain_id();
void verify(block_log_data& log, const std::filesystem::path& log_path) {
if (chain_id.empty()) {
chain_id = log.chain_id();
} else {
EOS_ASSERT(chain_id == log.chain_id(), block_log_exception,
"block log file ${path} has a different chain id", ("path", log_path));
}
}
};
using block_log_catalog = eosio::chain::log_catalog<block_log_data, block_log_index, block_log_verifier>;
namespace detail {
static bool is_pruned_log_and_mask_version(uint32_t& version) {
bool ret = version & pruned_version_flag;
version &= ~pruned_version_flag;
return ret;
}
struct block_log_impl {
inline static uint32_t default_initial_version = block_log::max_supported_version;
std::mutex mtx;
struct signed_block_with_id {
signed_block_ptr ptr;
block_id_type id;
};
std::optional<signed_block_with_id> head;
virtual ~block_log_impl() = default;
virtual uint32_t first_block_num() = 0;
virtual void append(const signed_block_ptr& b, const block_id_type& id,
const std::vector<char>& packed_block) = 0;
virtual uint64_t get_block_pos(uint32_t block_num) = 0;
virtual void reset(const genesis_state& gs, const signed_block_ptr& first_block) = 0;
virtual void reset(const chain_id_type& chain_id, uint32_t first_block_num) = 0;
virtual void flush() = 0;
virtual signed_block_ptr read_block_by_num(uint32_t block_num) = 0;
virtual std::vector<char> read_serialized_block_by_num(uint32_t block_num) = 0;
virtual std::optional<signed_block_header> read_block_header_by_num(uint32_t block_num) = 0;
virtual uint32_t version() const = 0;
virtual signed_block_ptr read_head() = 0;
void update_head(const signed_block_ptr& b, const std::optional<block_id_type>& id = {}) {
if (b)
head = { b, id ? *id : b->calculate_id() };
else
head = {};
}
static std::optional<block_log_preamble> extract_block_log_preamble(const std::filesystem::path& block_dir,
const std::filesystem::path& retained_dir);
}; // block_log_impl
/// Would remove pre-existing block log and index, never write blocks into disk.
struct empty_block_log final : block_log_impl {
uint32_t first_block_number = std::numeric_limits<uint32_t>::max();
explicit empty_block_log(const std::filesystem::path& log_dir) {
std::filesystem::remove(log_dir / "blocks.log");
std::filesystem::remove(log_dir / "blocks.index");
}
uint32_t first_block_num() final { return head ? head->ptr->block_num() : first_block_number; }
void append(const signed_block_ptr& b, const block_id_type& id, const std::vector<char>& packed_block) final {
update_head(b, id);
}
uint64_t get_block_pos(uint32_t block_num) final { return block_log::npos; }
void reset(const genesis_state& gs, const signed_block_ptr& first_block) final { update_head(first_block); }
void reset(const chain_id_type& chain_id, uint32_t first_block_num) final { first_block_number = first_block_num; }
void flush() final {}
signed_block_ptr read_block_by_num(uint32_t block_num) final { return {}; };
std::vector<char> read_serialized_block_by_num(uint32_t block_num) final { return {}; };
std::optional<signed_block_header> read_block_header_by_num(uint32_t block_num) final { return {}; };
uint32_t version() const final { return 0; }
signed_block_ptr read_head() final { return {}; };
};
struct basic_block_log : block_log_impl {
fc::datastream<fc::cfile> block_file;
fc::datastream<fc::cfile> index_file;
block_log_preamble preamble;
bool genesis_written_to_block_log = false;
basic_block_log() = default;
explicit basic_block_log(std::filesystem::path log_dir) { open(log_dir); }
static void ensure_file_exists(fc::cfile& f) {
if (std::filesystem::exists(f.get_file_path()))
return;
f.open(fc::cfile::create_or_update_rw_mode);
f.close();
}
virtual void transform_block_log() {
// convert from pruned block log to non-pruned if necessary
if (preamble.is_currently_pruned()) {
block_file.open(fc::cfile::update_rw_mode);
update_head(read_head());
if (head) {
index_file.open(fc::cfile::update_rw_mode);
vacuum(first_block_num_from_pruned_log(), preamble.first_block_num);
} else {
std::filesystem::resize_file(index_file.get_file_path(), 0);
}
preamble.ver = preamble.version();
}
}
uint32_t first_block_num() override { return preamble.first_block_num; }
uint32_t index_first_block_num() const { return preamble.first_block_num; }
virtual uint32_t working_block_file_first_block_num() { return preamble.first_block_num; }
virtual void post_append(uint64_t pos) {}
virtual signed_block_ptr retry_read_block_by_num(uint32_t block_num) { return {}; }
virtual std::vector<char> retry_read_serialized_block_by_num(uint32_t block_num) { return {}; }
virtual std::optional<signed_block_header> retry_read_block_header_by_num(uint32_t block_num) { return {}; }
void append(const signed_block_ptr& b, const block_id_type& id,
const std::vector<char>& packed_block) override {
try {
EOS_ASSERT(genesis_written_to_block_log, block_log_append_fail,
"Cannot append to block log until the genesis is first written");
block_file.seek_end(0);
index_file.seek_end(0);
// if pruned log, rewind over count trailer if any block is already present
if (preamble.is_currently_pruned() && head)
block_file.skip(-sizeof(uint32_t));
uint64_t pos = block_file.tellp();
EOS_ASSERT(index_file.tellp() == sizeof(uint64_t) * (b->block_num() - preamble.first_block_num),
block_log_append_fail, "Append to index file occurring at wrong position.",
("position", (uint64_t)index_file.tellp())(
"expected", (b->block_num() - preamble.first_block_num) * sizeof(uint64_t)));
block_file.write(packed_block.data(), packed_block.size());
block_file.write((char*)&pos, sizeof(pos));
index_file.write((char*)&pos, sizeof(pos));
index_file.flush();
update_head(b, id);
post_append(pos);
block_file.flush();
}
FC_LOG_AND_RETHROW()
}
uint64_t get_block_pos(uint32_t block_num) final {
if (!(head && block_num <= block_header::num_from_id(head->id) &&
block_num >= working_block_file_first_block_num()))
return block_log::npos;
index_file.seek(sizeof(uint64_t) * (block_num - index_first_block_num()));
uint64_t pos;
index_file.read((char*)&pos, sizeof(pos));
return pos;
}
block_pos_size_t get_block_position_and_size(uint32_t block_num) {
uint64_t pos = get_block_pos(block_num);
if (pos == block_log::npos) {
return block_pos_size_t {.position = block_log::npos, .size = 0};
}
assert(head);
uint32_t last_block_num = block_header::num_from_id(head->id);
EOS_ASSERT(block_num <= last_block_num, block_log_exception,
"block_num ${bn} should not be greater than last_block_num ${lbn}",
("bn", block_num)("lbn", last_block_num));
uint64_t block_size = 0;
constexpr uint32_t block_pos_size = sizeof(uint64_t); // size of block position field in the block log file
if (block_num < last_block_num) {
// current block is not the last block in the log file.
uint64_t next_block_pos = get_block_pos(block_num + 1);
EOS_ASSERT(next_block_pos > pos + block_pos_size, block_log_exception,
"next block position ${np} should be greater than current block position ${p} plus block position field size ${bps}",
("np", next_block_pos)("p", pos)("bps", block_pos_size));
block_size = next_block_pos - pos - block_pos_size;
} else {
// current block is the last block in the file.
block_file.seek_end(0);
auto file_size = block_file.tellp();
EOS_ASSERT(file_size > pos + block_pos_size, block_log_exception,
"block log file size ${fs} should be greater than current block position ${p} plus block position field size ${bps}",
("fs", file_size)("p", pos)("bps", block_pos_size));
block_size = file_size - pos - block_pos_size;
}
return block_pos_size_t {.position = pos, .size = block_size};
}
signed_block_ptr read_block_by_num(uint32_t block_num) final {
try {
uint64_t pos = get_block_pos(block_num);
if (pos != block_log::npos) {
block_file.seek(pos);
return read_block(block_file, block_num);
}
return retry_read_block_by_num(block_num);
}
FC_LOG_AND_RETHROW()
}
std::vector<char> read_serialized_block_by_num(uint32_t block_num) final {
try {
auto [ position, size ] = get_block_position_and_size(block_num);
if (position != block_log::npos) {
block_file.seek(position);
return read_serialized_block(block_file, size);
}
return retry_read_serialized_block_by_num(block_num);
}
FC_LOG_AND_RETHROW()
}
std::optional<signed_block_header> read_block_header_by_num(uint32_t block_num) final {
try {
uint64_t pos = get_block_pos(block_num);
if (pos != block_log::npos) {
block_file.seek(pos);
return read_block_header(block_file, block_num);
}
return retry_read_block_header_by_num(block_num);
}
FC_LOG_AND_RETHROW()
}
void open(const std::filesystem::path& data_dir) {
if (!std::filesystem::is_directory(data_dir))
std::filesystem::create_directories(data_dir);
this->block_file.set_file_path(data_dir / "blocks.log");
this->index_file.set_file_path(data_dir / "blocks.index");
/* On startup of the block log, there are several states the log file and the index file can be
* in relation to each other.
*
* Block Log
* Exists Is New
* +------------+------------+
* Exists | Check | Delete |
* Index | Head | Index |
* File +------------+------------+
* Is New | Replay | Do |
* | Log | Nothing |
* +------------+------------+
*
* Checking the heads of the files has several conditions as well.
* - If they are the same, do nothing.
* - If the index file head is not in the log file, delete the index and replay.
* - If the index file head is in the log, but not up to date, replay from index head.
*/
ensure_file_exists(block_file);
ensure_file_exists(index_file);
auto log_size = std::filesystem::file_size(this->block_file.get_file_path());
auto index_size = std::filesystem::file_size(this->index_file.get_file_path());
if (log_size) {
block_log_data log_data(block_file.get_file_path());
preamble = log_data.get_preamble();
// genesis state is not going to be useful afterwards, just convert it to chain id to save space
preamble.chain_context = preamble.chain_id();
genesis_written_to_block_log = true; // Assume it was constructed properly.
uint32_t number_of_blocks = log_data.number_of_blocks();
ilog("Log has ${n} blocks", ("n", number_of_blocks));
EOS_ASSERT(index_size || number_of_blocks == 0, block_log_exception,
"${index_file} file is empty, please use spring-util to fix the problem.",
("index_file", index_file.get_file_path().string()));
EOS_ASSERT(index_size % sizeof(uint64_t) == 0, block_log_exception,
"${index_file} file is invalid, please use spring-util to reconstruct the index.",
("index_file", index_file.get_file_path().string()));
if (index_size) {
block_log_index index(index_file.get_file_path());
auto last_block_pos = log_data.last_block_position();
auto last_index_pos = index.back();
EOS_ASSERT(last_block_pos == last_index_pos, block_log_exception,
"The last block position from ${block_file} is at ${block_pos} "
"which does not match the last block postion ${index_pos} from ${index_file}, please use "
"spring-util to fix the inconsistency.",
("block_pos", last_block_pos)("index_pos", last_index_pos)
("block_file", block_file.get_file_path().string())
("index_file", index_file.get_file_path().string()));
}
log_data.close();
transform_block_log();
} else if (index_size) {
ilog("Log file is empty while the index file is nonempty, discard the index file");
std::filesystem::resize_file(index_file.get_file_path(), 0);
}
if (!block_file.is_open())
block_file.open(fc::cfile::update_rw_mode);
if (!index_file.is_open())
index_file.open(fc::cfile::update_rw_mode);
if (log_size && !head)
update_head(read_head());
}
uint64_t first_block_num_from_pruned_log() {
uint32_t num_blocks;
this->block_file.seek_end(-sizeof(uint32_t));
fc::raw::unpack(this->block_file, num_blocks);
return this->head->ptr->block_num() - num_blocks + 1;
}
void reset(uint32_t first_bnum, std::variant<genesis_state, chain_id_type>&& chain_context, uint32_t version) {
block_file.open(fc::cfile::truncate_rw_mode);
preamble.ver = version | (preamble.ver & pruned_version_flag);
preamble.first_block_num = first_bnum;
preamble.chain_context = std::move(chain_context);
preamble.write_to(block_file);
// genesis state is not going to be useful afterwards, just convert it to chain id to save space
preamble.chain_context = preamble.chain_id();
genesis_written_to_block_log = true;
static_assert(block_log::max_supported_version > 0, "a version number of zero is not supported");
index_file.open(fc::cfile::truncate_rw_mode);
index_file.flush();
}
void reset(const genesis_state& gs, const signed_block_ptr& first_block) override {
this->reset(1, gs, default_initial_version);
this->append(first_block, first_block->calculate_id(), fc::raw::pack(*first_block));
}
void reset(const chain_id_type& chain_id, uint32_t first_block_num) override {
EOS_ASSERT(
first_block_num > 1, block_log_exception,
"Block log version ${ver} needs to be created with a genesis state if starting from block number 1.");
this->reset(first_block_num, chain_id, block_log::max_supported_version);
this->head.reset();
}
void flush() final {
block_file.flush();
index_file.flush();
}
signed_block_ptr read_head() final {
auto pos = read_head_position();
if (pos != block_log::npos) {
block_file.seek(pos);
return read_block(block_file, 0);
} else {
return {};
}
}
uint64_t read_head_position() {
uint64_t pos;
// Check that the file is not empty
this->block_file.seek_end(0);
if (this->block_file.tellp() <= sizeof(pos))
return block_log::npos;
// figure out if this is a pruned log or not. we can't just look at the configuration since
// read_head() is called early on, and this isn't hot enough to warrant a member bool to track it
this->block_file.seek(0);
uint32_t current_version;
fc::raw::unpack(this->block_file, current_version);
const bool is_currently_pruned = detail::is_pruned_log_and_mask_version(current_version);
this->block_file.seek_end(0);
int64_t skip_count = -sizeof(pos);
if (is_currently_pruned) {
skip_count += -sizeof(uint32_t); // skip the trailer containing block count
}
this->block_file.skip(skip_count);
fc::raw::unpack(this->block_file, pos);
return pos;
}
void vacuum(uint64_t first_block_num, uint64_t index_first_block_num) {
// go ahead and write a new valid header now. if the vacuum fails midway, at least this means maybe the
// block recovery can get through some blocks.
size_t copy_to_pos = convert_existing_header_to_vacuumed(first_block_num);
preamble.ver = block_log::max_supported_version;
// if there is no head block though, bail now, otherwise first_block_num won't actually be available
// and it'll mess this all up. Be sure to still remove the 4 byte trailer though.
if (!head) {
block_file.flush();
std::filesystem::resize_file(block_file.get_file_path(),
std::filesystem::file_size(block_file.get_file_path()) - sizeof(uint32_t));
return;
}
size_t copy_from_pos = get_block_pos(first_block_num);
block_file.seek_end(-sizeof(uint32_t));
size_t copy_sz = block_file.tellp() - copy_from_pos;
const uint32_t num_blocks_in_log = chain::block_header::num_from_id(head->id) - first_block_num + 1;
const size_t offset_bytes = copy_from_pos - copy_to_pos;
const size_t offset_blocks = first_block_num - index_first_block_num;
std::vector<char> buff;
buff.resize(4 * 1024 * 1024);
auto tick = std::chrono::time_point_cast<std::chrono::seconds>(std::chrono::system_clock::now());
while (copy_sz) {
const size_t copy_this_round = std::min(buff.size(), copy_sz);
block_file.seek(copy_from_pos);
block_file.read(buff.data(), copy_this_round);
block_file.punch_hole(copy_to_pos, copy_from_pos + copy_this_round);
block_file.seek(copy_to_pos);
block_file.write(buff.data(), copy_this_round);
copy_from_pos += copy_this_round;
copy_to_pos += copy_this_round;
copy_sz -= copy_this_round;
const auto tock = std::chrono::time_point_cast<std::chrono::seconds>(std::chrono::system_clock::now());
if (tick < tock - std::chrono::seconds(5)) {
ilog("Vacuuming pruned block log, ${b} bytes remaining", ("b", copy_sz));
tick = tock;
}
}
block_file.flush();
std::filesystem::resize_file(block_file.get_file_path(), block_file.tellp());
index_file.flush();
{
boost::interprocess::mapped_region index_mapped(index_file, boost::interprocess::read_write);
uint64_t* index_ptr = (uint64_t*)index_mapped.get_address();
for (uint32_t new_block_num = 0; new_block_num < num_blocks_in_log; ++new_block_num) {
const uint64_t new_pos = index_ptr[new_block_num + offset_blocks] - offset_bytes;
index_ptr[new_block_num] = new_pos;
if (new_block_num + 1 != num_blocks_in_log)
block_file.seek(index_ptr[new_block_num + offset_blocks + 1] - offset_bytes - sizeof(uint64_t));
else
block_file.seek_end(-sizeof(uint64_t));
block_file.write((char*)&new_pos, sizeof(new_pos));
}
}
std::filesystem::resize_file(index_file.get_file_path(), num_blocks_in_log * sizeof(uint64_t));
preamble.first_block_num = first_block_num;
}
size_t convert_existing_header_to_vacuumed(uint32_t first_block_num) {
uint32_t old_version;
uint32_t old_first_block_num;
const auto totem = block_log::npos;
block_file.seek(0);
fc::raw::unpack(block_file, old_version);
fc::raw::unpack(block_file, old_first_block_num);
EOS_ASSERT(is_pruned_log_and_mask_version(old_version), block_log_exception,
"Trying to vacuumed a non-pruned block log");
if (block_log::contains_genesis_state(old_version, old_first_block_num)) {
// we'll always write a v3 log, but need to possibly mutate the genesis_state to a chainid should we have
// pruned a log starting with a genesis_state
genesis_state gs;
auto ds = block_file.create_datastream();
fc::raw::unpack(ds, gs);
block_file.seek(0);
fc::raw::pack(block_file, block_log::max_supported_version);
fc::raw::pack(block_file, first_block_num);
if (first_block_num == 1) {
EOS_ASSERT(old_first_block_num == 1, block_log_exception, "expected an old first blocknum of 1");
fc::raw::pack(block_file, gs);
} else
fc::raw::pack(block_file, gs.compute_chain_id());
fc::raw::pack(block_file, totem);
} else {
// read in the existing chainid, to parrot back out
fc::sha256 chainid;
fc::raw::unpack(block_file, chainid);
block_file.seek(0);
fc::raw::pack(block_file, block_log::max_supported_version);
fc::raw::pack(block_file, first_block_num);
fc::raw::pack(block_file, chainid);
fc::raw::pack(block_file, totem);
}
return block_file.tellp();
}
static void write_incomplete_block_data(const std::filesystem::path& blocks_dir, fc::time_point now, uint32_t block_num,
fc::cfile& strm) {
auto tail_path = blocks_dir / std::string("blocks-bad-tail-").append(now.to_iso_string()).append(".log");
fc::cfile tail;
tail.set_file_path(tail_path);
tail.open(fc::cfile::create_or_update_rw_mode);
copy_file_content(strm, tail);
ilog("Data at tail end of block log which should contain the (incomplete) serialization of block ${num} "
"has been written out to '${tail_path}'.",
("num", block_num + 1)("tail_path", tail_path));
}
bool recover_from_incomplete_block_head(block_log_data& log_data, block_log_index& index) {
const uint64_t pos = index.back();
if (log_data.size() <= pos) {
// index refers to an invalid position, we cannot recover from it
return false;
}
const uint32_t expected_block_num = log_data.first_block_num() + index.num_blocks() - 1;
auto& ds = log_data.ro_stream_at(pos);
try {
signed_block entry;
fc::raw::unpack(ds, entry);
if (entry.block_num() != expected_block_num) {
return false;