-
Notifications
You must be signed in to change notification settings - Fork 1
/
pbft_database.cpp
1602 lines (1322 loc) · 69.7 KB
/
pbft_database.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/pbft_database.hpp>
#include <fc/io/fstream.hpp>
#include <fstream>
#include <eosio/chain/global_property_object.hpp>
namespace eosio {
namespace chain {
pbft_database::pbft_database(controller &ctrl) :
ctrl(ctrl) {
checkpoint_index = pbft_checkpoint_state_multi_index_type{};
view_state_index = pbft_view_state_multi_index_type{};
prepare_watermarks = vector<block_num_type>{};
pbft_db_dir = ctrl.state_dir();
checkpoints_dir = ctrl.blocks_dir();
chain_id = ctrl.get_chain_id();
if (!fc::is_directory(pbft_db_dir)) fc::create_directories(pbft_db_dir);
auto pbft_db_dat = pbft_db_dir / config::pbftdb_filename;
if (fc::exists(pbft_db_dat)) {
string content;
fc::read_file_contents(pbft_db_dat, content);
fc::datastream<const char *> ds(content.data(), content.size());
//skip current_view in pbftdb.dat.
ds.seekp(ds.tellp() + 4);
unsigned_int size;
fc::raw::unpack(ds, size);
for (uint32_t i = 0, n = size.value; i < n; ++i) {
pbft_state s;
fc::raw::unpack(ds, s);
set(std::make_shared<pbft_state>(move(s)));
}
} else {
pbft_state_index = pbft_state_multi_index_type{};
}
if (!fc::is_directory(checkpoints_dir)) fc::create_directories(checkpoints_dir);
auto checkpoints_db = checkpoints_dir / config::checkpoints_filename;
if (fc::exists(checkpoints_db)) {
string content;
fc::read_file_contents(checkpoints_db, content);
fc::datastream<const char *> ds(content.data(), content.size());
unsigned_int checkpoint_size;
fc::raw::unpack(ds, checkpoint_size);
for (uint32_t j = 0, m = checkpoint_size.value; j < m; ++j) {
pbft_checkpoint_state cs;
fc::raw::unpack(ds, cs);
set(std::make_shared<pbft_checkpoint_state>(move(cs)));
}
ilog("checkpoint index size: ${cs}", ("cs", checkpoint_index.size()));
} else {
checkpoint_index = pbft_checkpoint_state_multi_index_type{};
}
fc::remove(checkpoints_db);
}
void pbft_database::close() {
fc::path checkpoints_db = checkpoints_dir / config::checkpoints_filename;
std::ofstream c_out(checkpoints_db.generic_string().c_str(),
std::ios::out | std::ios::binary | std::ofstream::trunc);
uint32_t num_records_in_checkpoint_db = checkpoint_index.size();
fc::raw::pack(c_out, unsigned_int{num_records_in_checkpoint_db});
for (auto const &s: checkpoint_index) {
fc::raw::pack(c_out, *s);
}
fc::path pbft_db_dat = pbft_db_dir / config::pbftdb_filename;
std::ofstream out(pbft_db_dat.generic_string().c_str(),
std::ios::out | std::ios::binary | std::ofstream::app);
uint32_t num_records_in_db = pbft_state_index.size();
fc::raw::pack(out, unsigned_int{num_records_in_db});
for (auto const &s : pbft_state_index) {
fc::raw::pack(out, *s);
}
pbft_state_index.clear();
checkpoint_index.clear();
}
pbft_database::~pbft_database() {
close();
}
void pbft_database::add_pbft_prepare(pbft_prepare &p) {
if (!is_valid_prepare(p)) return;
auto &by_block_id_index = pbft_state_index.get<by_block_id>();
auto current = ctrl.fetch_block_state_by_id(p.block_info.block_id);
while ((current) && (current->block_num > ctrl.last_irreversible_block_num())) {
auto curr_itr = by_block_id_index.find(current->id);
if (curr_itr == by_block_id_index.end()) {
try {
auto curr_ps = pbft_state{current->id, current->block_num, {p}};
auto curr_psp = make_shared<pbft_state>(curr_ps);
pbft_state_index.insert(curr_psp);
} catch (...) {
elog( "prepare insert failure: ${p}", ("p", p));
}
} else {
auto prepares = (*curr_itr)->prepares;
auto p_itr = find_if(prepares.begin(), prepares.end(),
[&](const pbft_prepare &prep) {
return prep.common.sender == p.common.sender
&& prep.view == p.view;
});
if (p_itr == prepares.end()) {
by_block_id_index.modify(curr_itr, [&](const pbft_state_ptr &psp) {
psp->prepares.emplace_back(p);
std::sort(psp->prepares.begin(), psp->prepares.end(), less<>());
});
}
}
curr_itr = by_block_id_index.find(current->id);
if (curr_itr == by_block_id_index.end()) return;
auto cpsp = *curr_itr;
auto prepares = cpsp->prepares;
auto as = current->active_schedule.producers;
auto threshold = as.size()* 2 / 3 + 1;
if (prepares.size() >= threshold && !cpsp->is_prepared && is_less_than_high_watermark(cpsp->block_num)) {
flat_map<pbft_view_type, uint32_t> prepare_count;
for (auto const &pre: prepares) {
if (prepare_count.find(pre.view) == prepare_count.end()) prepare_count[pre.view] = 0;
}
for (auto const &sp: as) {
for (auto const &pp: prepares) {
if (sp.block_signing_key == pp.common.sender) prepare_count[pp.view] += 1;
}
}
for (auto const &e: prepare_count) {
if (e.second >= threshold) {
mark_as_prepared(cpsp->block_id);
}
}
}
current = ctrl.fetch_block_state_by_id(current->prev());
}
}
void pbft_database::mark_as_prepared(const block_id_type &bid) {
auto &by_block_id_index = pbft_state_index.get<by_block_id>();
auto itr = by_block_id_index.find(bid);
auto bnum = block_info_type{bid}.block_num();
if (itr == by_block_id_index.end()) {
auto ps = pbft_state{bid, bnum, .is_prepared = true};
auto psp = make_shared<pbft_state>(ps);
pbft_state_index.insert(psp);
return;
}
by_block_id_index.modify(itr, [&](const pbft_state_ptr &p) { p->is_prepared = true; });
}
vector<pbft_prepare> pbft_database::send_and_add_pbft_prepare(const vector<pbft_prepare> &pv, pbft_view_type current_view) {
auto head_block_num = ctrl.head_block_num();
if (head_block_num <= 1) return vector<pbft_prepare>{};
auto my_prepare = ctrl.get_pbft_my_prepare();
auto reserve_prepare = [&](const block_id_type &in) {
if (in == block_id_type() || !ctrl.fetch_block_state_by_id(in)) return false;
auto lib = ctrl.last_irreversible_block_id();
if (lib == block_id_type()) return true;
auto forks = ctrl.fork_db().fetch_branch_from(in, lib);
return !forks.first.empty() && forks.second.empty();
};
vector<pbft_prepare> new_pv;
new_pv.reserve(ctrl.my_signature_providers().size());
if (!pv.empty()) {
for (auto p : pv) {
//change uuid, sign again, update cache, then emit
auto uuid = boost::uuids::to_string(uuid_generator());
p.common.uuid = uuid;
p.common.timestamp = time_point::now();
p.sender_signature = ctrl.my_signature_providers()[p.common.sender](p.digest());
emit(pbft_outgoing_prepare, p);
}
return vector<pbft_prepare>{};
} else if (reserve_prepare(my_prepare)) {
for (auto const &sp : ctrl.my_signature_providers()) {
auto uuid = boost::uuids::to_string(uuid_generator());
pbft_prepare p;
p.common.uuid=uuid; p.view=current_view; p.block_info={my_prepare}; p.common.sender=sp.first; p.common.chain_id=chain_id;
p.sender_signature = sp.second(p.digest());
emit(pbft_outgoing_prepare, p);
new_pv.emplace_back(p);
}
return new_pv;
} else {
auto current_watermark = get_current_pbft_watermark();
auto lib = ctrl.last_irreversible_block_num();
uint32_t high_watermark_block_num = head_block_num;
if ( current_watermark > 0 ) {
high_watermark_block_num = std::min(head_block_num, current_watermark);
}
if (high_watermark_block_num <= lib) return vector<pbft_prepare>{};
if (auto hwbs = ctrl.fork_db().get_block_in_current_chain_by_num(high_watermark_block_num)) {
for (auto const &sp : ctrl.my_signature_providers()) {
auto uuid = boost::uuids::to_string(uuid_generator());
pbft_prepare p;
p.common.uuid=uuid; p.view=current_view; p.block_info={hwbs->id}; p.common.sender=sp.first; p.common.chain_id=chain_id;
p.sender_signature = sp.second(p.digest());
add_pbft_prepare(p);
emit(pbft_outgoing_prepare, p);
new_pv.emplace_back(p);
}
ctrl.set_pbft_my_prepare(hwbs->id);
}
return new_pv;
}
}
bool pbft_database::should_prepared() {
auto const &by_prepare_and_num_index = pbft_state_index.get<by_prepare_and_num>();
auto itr = by_prepare_and_num_index.begin();
if (itr == by_prepare_and_num_index.end()) return false;
pbft_state_ptr psp = *itr;
if (psp->is_prepared && (psp->block_num > ctrl.last_irreversible_block_num())) {
ctrl.set_pbft_prepared((*itr)->block_id);
return true;
}
return false;
}
bool pbft_database::is_valid_prepare(const pbft_prepare &p) {
if (!is_valid_pbft_message(p.common)) return false;
// a prepare msg under lscb (which is no longer in fork_db), can be treated as null, thus true.
if (p.block_info.block_num() <= ctrl.last_stable_checkpoint_block_num()) return true;
if (!p.is_signature_valid()) return false;
return should_recv_pbft_msg(p.common.sender);
}
void pbft_database::add_pbft_commit(pbft_commit &c) {
if (!is_valid_commit(c)) return;
auto &by_block_id_index = pbft_state_index.get<by_block_id>();
auto current = ctrl.fetch_block_state_by_id(c.block_info.block_id);
while ((current) && (current->block_num > ctrl.last_irreversible_block_num())) {
auto curr_itr = by_block_id_index.find(current->id);
if (curr_itr == by_block_id_index.end()) {
try {
auto curr_ps = pbft_state{current->id, current->block_num, .commits={c}};
auto curr_psp = make_shared<pbft_state>(curr_ps);
pbft_state_index.insert(curr_psp);
} catch (...) {
elog("commit insertion failure: ${c}", ("c", c));
}
} else {
auto commits = (*curr_itr)->commits;
auto p_itr = find_if(commits.begin(), commits.end(),
[&](const pbft_commit &comm) {
return comm.common.sender == c.common.sender
&& comm.view == c.view;
});
if (p_itr == commits.end()) {
by_block_id_index.modify(curr_itr, [&](const pbft_state_ptr &psp) {
psp->commits.emplace_back(c);
std::sort(psp->commits.begin(), psp->commits.end(), less<>());
});
}
}
curr_itr = by_block_id_index.find(current->id);
if (curr_itr == by_block_id_index.end()) return;
auto cpsp = *curr_itr;
auto as = current->active_schedule.producers;
auto threshold = as.size()* 2 / 3 + 1;
auto commits = cpsp->commits;
if (commits.size() >= threshold && !cpsp->is_committed && is_less_than_high_watermark(cpsp->block_num)) {
flat_map<pbft_view_type, uint32_t> commit_count;
for (auto const &com: commits) {
if (commit_count.find(com.view) == commit_count.end()) commit_count[com.view] = 0;
}
for (auto const &sp: as) {
for (auto const &pc: commits) {
if (sp.block_signing_key == pc.common.sender) commit_count[pc.view] += 1;
}
}
for (auto const &e: commit_count) {
if (e.second >= threshold) {
mark_as_committed(cpsp->block_id);
}
}
}
current = ctrl.fetch_block_state_by_id(current->prev());
}
}
vector<pbft_commit> pbft_database::send_and_add_pbft_commit(const vector<pbft_commit> &cv, pbft_view_type current_view) {
if (!cv.empty()) {
for (auto c : cv) {
//change uuid, sign again, update cache, then emit
auto uuid = boost::uuids::to_string(uuid_generator());
c.common.uuid = uuid;
c.common.timestamp = time_point::now();
c.sender_signature = ctrl.my_signature_providers()[c.common.sender](c.digest());
emit(pbft_outgoing_commit, c);
}
return vector<pbft_commit>{};
} else {
auto const &by_prepare_and_num_index = pbft_state_index.get<by_prepare_and_num>();
auto itr = by_prepare_and_num_index.begin();
if (itr == by_prepare_and_num_index.end()) return vector<pbft_commit>{};
pbft_state_ptr psp = *itr;
auto bs = ctrl.fork_db().get_block(psp->block_id);
if (!bs) return vector<pbft_commit>{};
vector<pbft_commit> new_cv;
new_cv.reserve(ctrl.my_signature_providers().size());
if (psp->is_prepared && (psp->block_num > ctrl.last_irreversible_block_num())) {
for (auto const &sp : ctrl.my_signature_providers()) {
auto uuid = boost::uuids::to_string(uuid_generator());
pbft_commit c;
c.common.uuid=uuid; c.view=current_view; c.block_info={psp->block_id}; c.common.sender=sp.first; c.common.chain_id=chain_id;
c.sender_signature = sp.second(c.digest());
add_pbft_commit(c);
emit(pbft_outgoing_commit, c);
new_cv.emplace_back(c);
}
}
return new_cv;
}
}
void pbft_database::mark_as_committed(const block_id_type &bid) {
auto &by_block_id_index = pbft_state_index.get<by_block_id>();
auto itr = by_block_id_index.find(bid);
if (itr == by_block_id_index.end()) return;
by_block_id_index.modify(itr, [&](const pbft_state_ptr &p) { p->is_committed = true; });
}
bool pbft_database::should_committed() {
auto const &by_commit_and_num_index = pbft_state_index.get<by_commit_and_num>();
auto itr = by_commit_and_num_index.begin();
if (itr == by_commit_and_num_index.end()) return false;
pbft_state_ptr psp = *itr;
return (psp->is_committed && (psp->block_num > ctrl.last_irreversible_block_num()));
}
pbft_view_type pbft_database::get_committed_view() {
pbft_view_type new_view = 0;
if (!should_committed()) return new_view;
auto const &by_commit_and_num_index = pbft_state_index.get<by_commit_and_num>();
auto itr = by_commit_and_num_index.begin();
pbft_state_ptr psp = *itr;
auto blk_state = ctrl.fetch_block_state_by_id((*itr)->block_id);
if (!blk_state) return new_view;
auto as = blk_state->active_schedule.producers;
auto commits = (*itr)->commits;
flat_map<pbft_view_type, uint32_t> commit_count;
for (auto const &com: commits) {
if (commit_count.find(com.view) == commit_count.end()) {
commit_count[com.view] = 1;
} else {
commit_count[com.view] += 1;
}
}
for (auto const &e: commit_count) {
if (e.second >= as.size() * 2 / 3 + 1 && e.first > new_view) {
new_view = e.first;
}
}
return new_view;
}
bool pbft_database::is_valid_commit(const pbft_commit &c) {
if (!is_valid_pbft_message(c.common)) return false;
if (c.block_info.block_num() <= ctrl.last_stable_checkpoint_block_num()) return true;
if (!c.is_signature_valid()) return false;
return should_recv_pbft_msg(c.common.sender);
}
void pbft_database::commit_local() {
auto const &by_commit_and_num_index = pbft_state_index.get<by_commit_and_num>();
auto itr = by_commit_and_num_index.begin();
if (itr == by_commit_and_num_index.end()) return;
pbft_state_ptr psp = *itr;
ctrl.pbft_commit_local(psp->block_id);
}
bool pbft_database::pending_pbft_lib() {
return ctrl.pending_pbft_lib();
}
void pbft_database::add_pbft_view_change(pbft_view_change &vc) {
if (!is_valid_view_change(vc)) return;
auto active_bps = lscb_active_producers().producers;
auto &by_view_index = view_state_index.get<by_view>();
auto itr = by_view_index.find(vc.target_view);
if (itr == by_view_index.end()) {
auto vs = pbft_view_change_state{vc.target_view, .view_changes={vc}};
auto vsp = make_shared<pbft_view_change_state>(vs);
view_state_index.insert(vsp);
} else {
auto pvs = (*itr);
auto view_changes = pvs->view_changes;
auto p_itr = find_if(view_changes.begin(), view_changes.end(),
[&](const pbft_view_change &existed) {
return existed.common.sender == vc.common.sender;
});
if (p_itr == view_changes.end()) {
by_view_index.modify(itr, [&](const pbft_view_change_state_ptr &pvsp) {
pvsp->view_changes.emplace_back(vc);
});
}
}
itr = by_view_index.find(vc.target_view);
if (itr == by_view_index.end()) return;
auto vsp = *itr;
auto threshold = active_bps.size() * 2 / 3 + 1;
if (vsp->view_changes.size() >= threshold && !vsp->is_view_changed) {
auto vc_count = 0;
for (auto const &sp: active_bps) {
for (auto const &v: (*itr)->view_changes) {
if (sp.block_signing_key == v.common.sender) vc_count += 1;
}
}
if (vc_count >= threshold) {
by_view_index.modify(itr, [&](const pbft_view_change_state_ptr &pvsp) { pvsp->is_view_changed = true; });
}
}
}
pbft_view_type pbft_database::should_view_change() {
pbft_view_type nv = 0;
auto &by_view_index = view_state_index.get<by_view>();
auto itr = by_view_index.begin();
if (itr == by_view_index.end()) return nv;
while (itr != by_view_index.end()) {
auto active_bps = lscb_active_producers().producers;
auto vc_count = 0;
auto pvs = (*itr);
for (auto const &bp: active_bps) {
for (auto const &pp: pvs->view_changes) {
if (bp.block_signing_key == pp.common.sender) vc_count += 1;
}
}
//if contains self or view_change >= f+1, transit to view_change and send view change
if (vc_count >= active_bps.size() / 3 + 1) {
nv = pvs->view;
break;
}
++itr;
}
return nv;
}
vector<pbft_view_change> pbft_database::send_and_add_pbft_view_change(
const vector<pbft_view_change> &vcv,
const pbft_prepared_certificate &ppc,
const vector<pbft_committed_certificate> &pcc,
pbft_view_type current_view,
pbft_view_type new_view) {
if (!vcv.empty()) {
for (auto vc : vcv) {
//change uuid, sign again, update cache, then emit
auto uuid = boost::uuids::to_string(uuid_generator());
vc.common.uuid = uuid;
vc.common.timestamp = time_point::now();
vc.sender_signature = ctrl.my_signature_providers()[vc.common.sender](vc.digest());
emit(pbft_outgoing_view_change, vc);
}
return vector<pbft_view_change>{};
} else {
vector<pbft_view_change> new_vcv;
new_vcv.reserve(ctrl.my_signature_providers().size());
for (auto const &my_sp : ctrl.my_signature_providers()) {
auto my_lsc = get_stable_checkpoint_by_id(ctrl.last_stable_checkpoint_block_id());
auto uuid = boost::uuids::to_string(uuid_generator());
pbft_view_change vc;
vc.common.uuid=uuid; vc.current_view=current_view; vc.target_view=new_view; vc.prepared_cert=ppc; vc.committed_cert=pcc; vc.stable_checkpoint=my_lsc; vc.common.sender=my_sp.first; vc.common.chain_id=chain_id;
vc.sender_signature = my_sp.second(vc.digest());
emit(pbft_outgoing_view_change, vc);
add_pbft_view_change(vc);
new_vcv.emplace_back(vc);
}
return new_vcv;
}
}
bool pbft_database::should_new_view(const pbft_view_type target_view) {
auto &by_view_index = view_state_index.get<by_view>();
auto itr = by_view_index.find(target_view);
if (itr == by_view_index.end()) return false;
return (*itr)->is_view_changed;
}
pbft_view_type pbft_database::get_proposed_new_view_num() {
auto &by_count_and_view_index = view_state_index.get<by_count_and_view>();
auto itr = by_count_and_view_index.begin();
if (itr == by_count_and_view_index.end() || !(*itr)->is_view_changed) return 0;
return (*itr)->view;
}
bool pbft_database::is_new_primary(const pbft_view_type target_view) {
auto primary_key = get_new_view_primary_key(target_view);
if (primary_key == public_key_type()) return false;
auto sps = ctrl.my_signature_providers();
auto sp_itr = sps.find(primary_key);
return sp_itr != sps.end();
}
void pbft_database::prune_pbft_index() {
view_state_index.clear();
ctrl.reset_pbft_my_prepare();
}
pbft_new_view pbft_database::send_pbft_new_view(
const pbft_view_changed_certificate &vcc,
pbft_view_type current_view) {
auto primary_key = get_new_view_primary_key(current_view);
if (!is_new_primary(current_view) || vcc.empty()) return pbft_new_view();
//`sp_itr` is not possible to be the end iterator, since it's already been checked in `is_new_primary`.
auto my_sps = ctrl.my_signature_providers();
auto sp_itr = my_sps.find(primary_key);
auto highest_ppc = pbft_prepared_certificate();
auto highest_pcc = vector<pbft_committed_certificate>{};
auto highest_sc = pbft_stable_checkpoint();
for (auto const &vc: vcc.view_changes) {
if (vc.prepared_cert.block_info.block_num() > highest_ppc.block_info.block_num()
&& is_valid_prepared_certificate(vc.prepared_cert)) {
highest_ppc = vc.prepared_cert;
}
for (auto const &cc: vc.committed_cert) {
if (is_valid_committed_certificate(cc)) {
auto p_itr = find_if(highest_pcc.begin(), highest_pcc.end(),
[&](const pbft_committed_certificate &ext) { return ext.block_info.block_id == cc.block_info.block_id; });
if (p_itr == highest_pcc.end()) highest_pcc.emplace_back(cc);
}
}
if (vc.stable_checkpoint.block_info.block_num() > highest_sc.block_info.block_num() &&
is_valid_stable_checkpoint(vc.stable_checkpoint)) {
highest_sc = vc.stable_checkpoint;
}
}
auto uuid = boost::uuids::to_string(uuid_generator());
pbft_new_view nv;
nv.common.uuid=uuid; nv.new_view=current_view; nv.prepared_cert=highest_ppc; nv.committed_cert=highest_pcc; nv.stable_checkpoint=highest_sc, nv.view_changed_cert=vcc, nv.common.sender=sp_itr->first; nv.common.chain_id=chain_id;
nv.sender_signature = sp_itr->second(nv.digest());
emit(pbft_outgoing_new_view, nv);
return nv;
}
pbft_prepared_certificate pbft_database::generate_prepared_certificate() {
auto const &by_prepare_and_num_index = pbft_state_index.get<by_prepare_and_num>();
auto itr = by_prepare_and_num_index.begin();
if (itr == by_prepare_and_num_index.end()) return pbft_prepared_certificate();
pbft_state_ptr psp = *itr;
auto prepared_block_state = ctrl.fetch_block_state_by_id(psp->block_id);
if (!prepared_block_state) return pbft_prepared_certificate();
auto as = prepared_block_state->active_schedule.producers;
if (psp->is_prepared && psp->block_num > ctrl.last_irreversible_block_num()) {
auto prepares = psp->prepares;
auto valid_prepares = vector<pbft_prepare>{};
flat_map<pbft_view_type, uint32_t> prepare_count;
flat_map<pbft_view_type, vector<pbft_prepare>> prepare_msg;
for (auto const &pre: prepares) {
if (prepare_count.find(pre.view) == prepare_count.end()) prepare_count[pre.view] = 0;
prepare_msg[pre.view].emplace_back(pre);
}
for (auto const &sp: as) {
for (auto const &pp: prepares) {
if (sp.block_signing_key == pp.common.sender) prepare_count[pp.view] += 1;
}
}
auto bp_threshold = as.size() * 2 / 3 + 1;
for (auto const &e: prepare_count) {
if (e.second >= bp_threshold) {
valid_prepares = prepare_msg[e.first];
}
}
if (valid_prepares.empty()) return pbft_prepared_certificate();
pbft_prepared_certificate pc;
pc.block_info={psp->block_id}; pc.prepares=valid_prepares; pc.pre_prepares.emplace(psp->block_id);
for (auto const &p: valid_prepares) {
auto bid = p.block_info.block_id;
while (bid != psp->block_id) {
pc.pre_prepares.emplace(bid);
bid = ctrl.fetch_block_state_by_id(bid)->prev();
}
}
return pc;
} else return pbft_prepared_certificate();
}
vector<pbft_committed_certificate> pbft_database::generate_committed_certificate() {
auto const &by_commit_and_num_index = pbft_state_index.get<by_commit_and_num>();
auto itr = by_commit_and_num_index.begin();
if (itr == by_commit_and_num_index.end()) return vector<pbft_committed_certificate>{};
pbft_state_ptr psp = *itr;
if (!psp->is_committed) return vector<pbft_committed_certificate>{};
auto highest_committed_block_num = psp->block_num;
vector<block_num_type> ccb;
//adding my highest committed cert.
auto lscb_num = ctrl.last_stable_checkpoint_block_num();
if ( highest_committed_block_num > lscb_num ) {
ccb.emplace_back(highest_committed_block_num);
}
auto watermarks = get_updated_watermarks();
for (auto& watermark : watermarks) {
//adding committed cert on every water mark.
if (watermark < highest_committed_block_num && watermark > lscb_num) {
ccb.emplace_back(watermark);
}
}
auto const &by_id_index = pbft_state_index.get<by_block_id>();
auto pcc = vector<pbft_committed_certificate>{};
pcc.reserve(ccb.size());
for (auto const &committed_block_num: ccb) {
auto cbs = ctrl.fetch_block_state_by_number(committed_block_num);
if (!cbs) return vector<pbft_committed_certificate>{};
auto it = by_id_index.find(cbs->id);
if (it == by_id_index.end() || !(*it)->is_committed) {
return vector<pbft_committed_certificate>{};
}
auto as = cbs->active_schedule.producers;
auto commits = (*it)->commits;
auto valid_commits = vector<pbft_commit>{};
flat_map<pbft_view_type, uint32_t> commit_count;
flat_map<pbft_view_type, vector<pbft_commit>> commit_msg;
for (auto const &com: commits) {
if (commit_count.find(com.view) == commit_count.end()) commit_count[com.view] = 0;
commit_msg[com.view].emplace_back(com);
}
for (auto const &sp: as) {
for (auto const &cc: commits) {
if (sp.block_signing_key == cc.common.sender) commit_count[cc.view] += 1;
}
}
auto bp_threshold = as.size() * 2 / 3 + 1;
for (auto const &e: commit_count) {
if (e.second >= bp_threshold) {
valid_commits = commit_msg[e.first];
}
}
if (valid_commits.empty()) return vector<pbft_committed_certificate>{};
pbft_committed_certificate cc;
cc.block_info={cbs->id}; cc.commits=valid_commits;
pcc.emplace_back(cc);
}
return pcc;
}
pbft_view_changed_certificate pbft_database::generate_view_changed_certificate(pbft_view_type target_view) {
auto &by_view_index = view_state_index.get<by_view>();
auto itr = by_view_index.find(target_view);
if (itr == by_view_index.end()) return pbft_view_changed_certificate();
auto pvs = *itr;
if (pvs->is_view_changed) {
auto pvcc = pbft_view_changed_certificate();
pvcc.target_view=pvs->view; pvcc.view_changes=pvs->view_changes;
return pvcc;
} else return pbft_view_changed_certificate();
}
bool pbft_database::is_valid_prepared_certificate(const pbft_prepared_certificate &certificate) {
// an empty certificate is valid since it acts as a null digest in pbft.
if (certificate.empty()) return true;
// a certificate under lscb (no longer in fork_db) is also treated as null.
if (certificate.block_info.block_num() <= ctrl.last_stable_checkpoint_block_num()) return true;
auto valid = true;
for (auto const &p : certificate.prepares) {
valid = valid && is_valid_prepare(p);
if (!valid) return false;
}
auto cert_id = certificate.block_info.block_id;
auto cert_bs = ctrl.fetch_block_state_by_id(cert_id);
auto producer_schedule = lscb_active_producers();
if (certificate.block_info.block_num() > 0 && cert_bs) {
producer_schedule = cert_bs->active_schedule;
}
auto bp_threshold = producer_schedule.producers.size() * 2 / 3 + 1;
auto prepares = certificate.prepares;
flat_map<pbft_view_type, uint32_t> prepare_count;
for (auto const &pre: prepares) {
if (prepare_count.find(pre.view) == prepare_count.end()) prepare_count[pre.view] = 0;
}
for (auto const &sp: producer_schedule.producers) {
for (auto const &pp: prepares) {
if (sp.block_signing_key == pp.common.sender) prepare_count[pp.view] += 1;
}
}
auto should_prepared = false;
for (auto const &e: prepare_count) {
if (e.second >= bp_threshold) {
should_prepared = true;
}
}
if (!should_prepared) return false;
//validate prepare
auto lscb = ctrl.last_stable_checkpoint_block_num();
auto non_fork_bp_count = 0;
vector<block_info_type> prepare_infos;
prepare_infos.reserve(certificate.prepares.size());
for (auto const &p : certificate.prepares) {
//only search in fork db
if (p.block_info.block_num() <= lscb) {
++non_fork_bp_count;
} else {
prepare_infos.emplace_back(p.block_info);
}
}
return is_valid_longest_fork(certificate.block_info, prepare_infos, bp_threshold, non_fork_bp_count);
}
bool pbft_database::is_valid_committed_certificate(const pbft_committed_certificate &certificate) {
// an empty certificate is valid since it acts as a null digest in pbft.
if (certificate.empty()) return true;
// a certificate under lscb (no longer in fork_db) is also treated as null.
if (certificate.block_info.block_num() <= ctrl.last_stable_checkpoint_block_num()) return true;
auto valid = true;
for (auto const &c : certificate.commits) {
valid = valid && is_valid_commit(c);
if (!valid) return false;
}
auto cert_id = certificate.block_info.block_id;
auto cert_bs = ctrl.fetch_block_state_by_id(cert_id);
auto producer_schedule = lscb_active_producers();
if (certificate.block_info.block_num() > 0 && cert_bs) {
producer_schedule = cert_bs->active_schedule;
}
auto bp_threshold = producer_schedule.producers.size() * 2 / 3 + 1;
auto commits = certificate.commits;
flat_map<pbft_view_type, uint32_t> commit_count;
for (auto const &pre: commits) {
if (commit_count.find(pre.view) == commit_count.end()) commit_count[pre.view] = 0;
}
for (auto const &sp: producer_schedule.producers) {
for (auto const &pp: commits) {
if (sp.block_signing_key == pp.common.sender) commit_count[pp.view] += 1;
}
}
auto should_committed = false;
for (auto const &e: commit_count) {
if (e.second >= bp_threshold) {
should_committed = true;
}
}
if (!should_committed) return false;
//validate commit
auto lscb = ctrl.last_stable_checkpoint_block_num();
auto non_fork_bp_count = 0;
vector<block_info_type> commit_infos;
commit_infos.reserve(certificate.commits.size());
for (auto const &c : certificate.commits) {
//only search in fork db
if (c.block_info.block_num() <= lscb) {
++non_fork_bp_count;
} else {
commit_infos.emplace_back(c.block_info);
}
}
return is_valid_longest_fork(certificate.block_info, commit_infos, bp_threshold, non_fork_bp_count);
}
bool pbft_database::is_valid_view_change(const pbft_view_change &vc) {
if (vc.common.chain_id != chain_id) return false;
return vc.is_signature_valid()
&& should_recv_pbft_msg(vc.common.sender);
// No need to check prepared cert and stable checkpoint, until generate or validate a new view msg
}
bool pbft_database::is_valid_new_view(const pbft_new_view &nv) {
//all signatures should be valid
EOS_ASSERT(nv.common.chain_id == chain_id, pbft_exception, "wrong chain.");
EOS_ASSERT(nv.is_signature_valid(), pbft_exception, "bad new view signature");
EOS_ASSERT(nv.common.sender == get_new_view_primary_key(nv.new_view), pbft_exception, "new view is not signed with expected key");
EOS_ASSERT(is_valid_prepared_certificate(nv.prepared_cert), pbft_exception,
"bad prepared certificate: ${pc}", ("pc", nv.prepared_cert));
EOS_ASSERT(is_valid_stable_checkpoint(nv.stable_checkpoint), pbft_exception,
"bad stable checkpoint: ${scp}", ("scp", nv.stable_checkpoint));
for (auto const &c: nv.committed_cert) {
EOS_ASSERT(is_valid_committed_certificate(c), pbft_exception, "bad committed certificate: ${cc}", ("cc", c));
}
EOS_ASSERT(nv.is_signature_valid(), pbft_exception, "bad new view signature");
EOS_ASSERT(nv.view_changed_cert.target_view == nv.new_view, pbft_exception, "target view not match");
vector<public_key_type> lscb_producers;
lscb_producers.reserve(lscb_active_producers().producers.size());
for (auto const& pk: lscb_active_producers().producers) {
lscb_producers.emplace_back(pk.block_signing_key);
}
auto schedule_threshold = lscb_producers.size() * 2 / 3 + 1;
vector<public_key_type> view_change_producers;
view_change_producers.reserve(nv.view_changed_cert.view_changes.size());
for (auto vc: nv.view_changed_cert.view_changes) {
if (is_valid_view_change(vc)) {
add_pbft_view_change(vc);
view_change_producers.emplace_back(vc.common.sender);
}
}
vector<public_key_type> intersection;
std::sort(lscb_producers.begin(),lscb_producers.end());
std::sort(view_change_producers.begin(),view_change_producers.end());
std::set_intersection(lscb_producers.begin(),lscb_producers.end(),
view_change_producers.begin(),view_change_producers.end(),
back_inserter(intersection));
EOS_ASSERT(intersection.size() >= schedule_threshold, pbft_exception, "view changes count not enough");
EOS_ASSERT(should_new_view(nv.new_view), pbft_exception, "should not enter new view: ${nv}", ("nv", nv.new_view));
auto highest_ppc = pbft_prepared_certificate();
auto highest_pcc = vector<pbft_committed_certificate>{};
auto highest_scp = pbft_stable_checkpoint();
for (auto const &vc: nv.view_changed_cert.view_changes) {
if (vc.prepared_cert.block_info.block_num() > highest_ppc.block_info.block_num()
&& is_valid_prepared_certificate(vc.prepared_cert)) {
highest_ppc = vc.prepared_cert;
}
for (auto const &cc: vc.committed_cert) {
if (is_valid_committed_certificate(cc)) {
auto p_itr = find_if(highest_pcc.begin(), highest_pcc.end(),
[&](const pbft_committed_certificate &ext) { return ext.block_info.block_id == cc.block_info.block_id; });
if (p_itr == highest_pcc.end()) highest_pcc.emplace_back(cc);
}
}
if (vc.stable_checkpoint.block_info.block_num() > highest_scp.block_info.block_num()
&& is_valid_stable_checkpoint(vc.stable_checkpoint)) {
highest_scp = vc.stable_checkpoint;
}
}
EOS_ASSERT(highest_ppc.block_info == nv.prepared_cert.block_info, pbft_exception,
"prepared certificate does not match, should be ${hppc} but ${pc} given",
("hppc",highest_ppc)("pc", nv.prepared_cert));
std::sort(highest_pcc.begin(), highest_pcc.end());
auto committed_certs = nv.committed_cert;
std::sort(committed_certs.begin(), committed_certs.end());
EOS_ASSERT(highest_pcc.size() == committed_certs.size(), pbft_exception, "wrong committed certificates size");
for (auto i = 0; i < committed_certs.size(); ++i) {
EOS_ASSERT(highest_pcc[i].block_info == committed_certs[i].block_info, pbft_exception,
"committed certificate does not match, should be ${hpcc} but ${cc} given",
("hpcc",highest_pcc[i])("cc", committed_certs[i]));
}
EOS_ASSERT(highest_scp.block_info == nv.stable_checkpoint.block_info, pbft_exception,
"stable checkpoint does not match, should be ${hscp} but ${scp} given",
("hpcc",highest_scp)("pc", nv.stable_checkpoint));
return true;
}
bool pbft_database::should_stop_view_change(const pbft_view_change &vc) {
auto lscb_num = ctrl.last_stable_checkpoint_block_num();
auto vc_lscb = vc.stable_checkpoint.block_info.block_num();
return vc_lscb > 0 && lscb_num > vc_lscb;
}
vector<vector<block_info_type>> pbft_database::fetch_fork_from(vector<block_info_type> &block_infos) {
vector<vector<block_info_type>> result;
if (block_infos.empty()) {
return result;
}
if (block_infos.size() == 1) {
result.emplace_back(initializer_list<block_info_type>{block_infos.front()});
return result;
}
sort(block_infos.begin(), block_infos.end(),
[](const block_info_type &a, const block_info_type &b) -> bool { return a.block_num() > b.block_num(); });
while (!block_infos.empty()) {
auto fork = fetch_first_fork_from(block_infos);
if (!fork.empty()) {
result.emplace_back(fork);
}
}
return result;