-
Notifications
You must be signed in to change notification settings - Fork 1
/
PBFT.cpp
1451 lines (1240 loc) · 47.4 KB
/
PBFT.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
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file: PBFT.cpp
* @author: fisco-dev
*
* @date: 2017
*/
#include <boost/filesystem.hpp>
#include <libethcore/ChainOperationParams.h>
#include <libethcore/CommonJS.h>
#include <libethereum/Interface.h>
#include <libethereum/BlockChain.h>
#include <libethereum/EthereumHost.h>
#include <libethereum/NodeConnParamsManagerApi.h>
#include <libdevcrypto/Common.h>
#include "PBFT.h"
#include <libdevcore/easylog.h>
#include <libdevcore/LogGuard.h>
#include <libethereum/StatLog.h>
#include <libethereum/ConsensusControl.h>
using namespace std;
using namespace dev;
using namespace eth;
const unsigned PBFT::kCollectInterval = 60;
void PBFT::init()
{
ETH_REGISTER_SEAL_ENGINE(PBFT);
}
PBFT::PBFT()
{
}
PBFT::~PBFT() {
if (m_backup_db) {
delete m_backup_db;
}
stopWorking();
}
void PBFT::initEnv(std::weak_ptr<PBFTHost> _host, BlockChain* _bc, OverlayDB* _db, BlockQueue *bq, KeyPair const& _key_pair, unsigned _view_timeout)
{
Guard l(m_mutex);
m_host = _host;
m_bc.reset(_bc);
m_stateDB.reset(_db);
m_bq.reset(bq);
m_bc->setSignChecker([this](BlockHeader const & _header, std::vector<std::pair<u256, Signature>> _sign_list) {
return checkBlockSign(_header, _sign_list);
});
m_key_pair = _key_pair;
resetConfig();
m_view_timeout = _view_timeout;
m_consensus_block_number = 0;
m_last_consensus_time = utcTime();
m_change_cycle = 0;
m_to_view = 0;
m_leader_failed = false;
m_last_sign_time = 0;
m_last_collect_time = std::chrono::system_clock::now();
m_future_prepare_cache = std::make_pair(Invalid256, PrepareReq());
m_last_exec_finish_time = utcTime();
initBackupDB();
LOG(INFO) << "PBFT initEnv success";
}
void PBFT::initBackupDB() {
ldb::Options o;
o.max_open_files = 256;
o.create_if_missing = true;
std::string path = m_bc->chainParams().dataDir + "/pbftMsgBackup";
ldb::Status status = ldb::DB::Open(o, path, &m_backup_db);
if (!status.ok() || !m_backup_db)
{
if (boost::filesystem::space(path).available < 1024)
{
LOG(ERROR) << "Not enough available space found on hard drive. Please free some up and then re-run. Bailing.";
BOOST_THROW_EXCEPTION(NotEnoughAvailableSpace());
}
else
{
LOG(ERROR) << status.ToString();
LOG(ERROR) << "Database " << path << "already open. You appear to have another instance of ethereum running. Bailing.";
BOOST_THROW_EXCEPTION(DatabaseAlreadyOpen());
}
}
// reload msg from db
reloadMsg(backup_key_committed, &m_committed_prepare_cache);
}
void PBFT::resetConfig() {
if (!NodeConnManagerSingleton::GetInstance().getAccountType(m_key_pair.pub(), m_account_type)) {
LOG(ERROR) << "resetConfig Fail: can't find myself id, stop sealing";
m_cfg_err = true;
return;
}
auto node_num = NodeConnManagerSingleton::GetInstance().getMinerNum();
if (node_num == 0) {
LOG(ERROR) << "resetConfig Fail: miner_num = 0, stop sealing";
m_cfg_err = true;
return;
}
u256 node_idx;
if (!NodeConnManagerSingleton::GetInstance().getIdx(m_key_pair.pub(), node_idx)) {
//BOOST_THROW_EXCEPTION(PbftInitFailed() << errinfo_comment("NodeID not in cfg"));
LOG(INFO) << "resetConfig Fail: can't find myself id, stop sealing";
m_cfg_err = true;
return;
}
if (node_num != m_node_num || node_idx != m_node_idx) {
m_node_num = node_num;
m_node_idx = node_idx;
m_f = (m_node_num - 1 ) / 3;
m_prepare_cache.clear();
m_sign_cache.clear();
m_recv_view_change_req.clear();
ConsensusControl::instance().clearAllCache();
m_commitMap.clear();
if (!getMinerList(-1, m_miner_list)) {
LOG(ERROR) << "resetConfig Fail: getMinerList return false";
m_cfg_err = true;
return;
}
if (m_miner_list.size() != m_node_num) {
LOG(ERROR) << "resetConfig Fail: m_miner_list.size=" << m_miner_list.size() << ",m_node_num=" << m_node_num;
m_cfg_err = true;
return;
}
LOG(INFO) << "resetConfig Sucess: m_node_idx=" << m_node_idx << ", m_node_num=" << m_node_num;
}
// consensuscontrol init cache
ConsensusControl::instance().resetNodeCache();
m_cfg_err = false;
}
StringHashMap PBFT::jsInfo(BlockHeader const& _bi) const
{
return { { "number", toJS(_bi.number()) }, { "timestamp", toJS(_bi.timestamp()) } };
}
bool PBFT::generateSeal(BlockHeader const& _bi, bytes const& _block_data, u256 &_view)
{
Timer t;
Guard l(m_mutex);
_view = m_view;
if (!broadcastPrepareReq(_bi, _block_data)) {
LOG(ERROR) << "broadcastPrepareReq failed, " << _bi.number() << _bi.hash(WithoutSeal);
return false;
}
LOG(DEBUG) << "generateSeal, blk=" << _bi.number() << ", timecost=" << 1000 * t.elapsed();
return true;
}
bool PBFT::generateCommit(BlockHeader const& _bi, bytes const& _block_data, u256 const& _view)
{
Guard l(m_mutex);
if (_view != m_view) {
LOG(INFO) << "view has changed, generateCommit failed, _view=" << _view << ", m_view=" << m_view;
return false;
}
PrepareReq req;
req.height = _bi.number();
req.view = _view;
req.idx = m_node_idx;
req.timestamp = u256(utcTime());
req.block_hash = _bi.hash(WithoutSeal);
req.sig = signHash(req.block_hash);
req.sig2 = signHash(req.fieldsWithoutBlock());
req.block = _block_data;
if (addPrepareReq(req) && broadcastSignReq(req)) {
checkAndCommit(); // support for issuing block in single node mode (支持单节点可出块)
}
return true;
}
bool PBFT::shouldSeal(Interface*)
{
Guard l(m_mutex);
if (m_cfg_err || m_account_type != EN_ACCOUNT_TYPE_MINER) { // do not issue the block if not find myself in systemcontract config or this node is no a miner (配置中找不到自己或非记账节点就不出块)
return false;
}
std::pair<bool, u256> ret = getLeader();
if (!ret.first) {
return false;
}
if (ret.second != m_node_idx) {
if (auto h = m_host.lock()) {
h512 node_id = h512(0);
if (NodeConnManagerSingleton::GetInstance().getPublicKey(ret.second, node_id) && !h->isConnected(node_id)) {
LOG(ERROR) << "getLeader ret:<" << ret.first << "," << ret.second << ">" << ", need viewchange for disconnected";
m_last_consensus_time = 0;
m_last_sign_time = 0; // set m_last_consensus_time and m_last_sign_time to zero can guarantee "fastviewchange" to work (两个都设置为0,才能保证快速切换)
m_signalled.notify_all();
}
}
return false;
}
// deside whether to replay the committed_prepare package, would usually happen when the 3rd phases(commit phases) not finish (判断是否要把committed_prepare拿出来重放)
if (m_consensus_block_number == m_committed_prepare_cache.height) {
if (m_consensus_block_number != m_raw_prepare_cache.height) {
reHandlePrepareReq(m_committed_prepare_cache);
}
return false;
}
return true;
}
void PBFT::reHandlePrepareReq(PrepareReq const& _req) {
LOG(INFO) << "shouldSeal: found an committed but not saved block, post out again. hash=" << m_committed_prepare_cache.block_hash.abridged();
clearMask(); // to make sure msg will be delivered
PrepareReq req;
req.height = _req.height;
req.view = m_view;
req.idx = m_node_idx;
req.timestamp = u256(utcTime());
req.block_hash = _req.block_hash;
req.sig = signHash(req.block_hash);
req.sig2 = signHash(req.fieldsWithoutBlock());
req.block = _req.block;
LOG(INFO) << "BLOCK_TIMESTAMP_STAT:[" << toString(req.block_hash) << "][" << req.height << "][" << utcTime() << "][" << "broadcastPrepareReq" << "]";
RLPStream ts;
req.streamRLPFields(ts);
broadcastMsg(req.block_hash.hex(), PrepareReqPacket, ts.out());
handlePrepareMsg(m_node_idx, req, true); // 指明是来自自己的Req
}
std::pair<bool, u256> PBFT::getLeader() const {
if (m_cfg_err || m_leader_failed || m_highest_block.number() == Invalid256) {
return std::make_pair(false, Invalid256);
}
return std::make_pair(true, (m_view + m_highest_block.number()) % m_node_num);
}
void PBFT::reportBlock(BlockHeader const & _b, u256 const &) {
Guard l(m_mutex);
auto old_height = m_highest_block.number();
auto old_view = m_view;
m_highest_block = _b;
if (m_highest_block.number() >= m_consensus_block_number) {
m_view = m_to_view = m_change_cycle = 0;
m_leader_failed = false;
m_last_consensus_time = utcTime();
m_consensus_block_number = m_highest_block.number() + 1;
//m_recv_view_change_req.clear();
delViewChange(); // if is's the newest block's viewchange, we can't discard it (如果是最新块的viewchange,不能丢弃)
}
resetConfig();
delCache(m_highest_block.hash(WithoutSeal));
LOG(INFO) << "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Report: blk=" << m_highest_block.number() << ",hash=" << _b.hash(WithoutSeal).abridged() << ",idx=" << m_highest_block.genIndex() << ", Next: blk=" << m_consensus_block_number;
// onchain log
stringstream ss;
ss << "blk:" << m_highest_block.number().convert_to<string>()
<< " hash:" << _b.hash(WithoutSeal).abridged() << " idx:" << m_highest_block.genIndex().convert_to<string>()
<< " next:" << m_consensus_block_number.convert_to<string>();
PBFTFlowLog(old_height + old_view, ss.str());
}
void PBFT::onPBFTMsg(unsigned _id, std::shared_ptr<p2p::Capability> _peer, RLP const & _r) {
if (_id <= ViewChangeReqPacket) {
NodeID nodeid;
auto session = _peer->session();
if (session && (nodeid = session->id()))
{
u256 idx = u256(0);
if (!NodeConnManagerSingleton::GetInstance().getIdx(nodeid, idx)) {
LOG(ERROR) << "Recv an pbft msg from unknown peer id=" << _id;
return;
}
//handleMsg(_id, idx, _peer->session()->id(), _r[0]);
m_msg_queue.push(PBFTMsgPacket(idx, nodeid, _id, _r[0].data()));
}
} else {
LOG(ERROR) << "Recv an illegal msg, id=" << _id;
}
}
void PBFT::workLoop() {
while (isWorking()) {
try
{
std::pair<bool, PBFTMsgPacket> ret = m_msg_queue.tryPop(5);
if (ret.first) {
handleMsg(ret.second.packet_id, ret.second.node_idx, ret.second.node_id, RLP(ret.second.data));
} else {
std::unique_lock<std::mutex> l(x_signalled);
m_signalled.wait_for(l, chrono::milliseconds(5));
}
checkTimeout();
handleFutureBlock();
collectGarbage();
} catch (Exception &_e) {
LOG(ERROR) << _e.what();
}
}
}
void PBFT::handleMsg(unsigned _id, u256 const& _from, h512 const& _node, RLP const& _r) {
Guard l(m_mutex);
auto now_time = utcTime();
std::string key;
PBFTMsg pbft_msg;
switch (_id) {
case PrepareReqPacket: {
PrepareReq req;
req.populate(_r);
handlePrepareMsg(_from, req);
key = req.block_hash.hex();
pbft_msg = req;
break;
}
case SignReqPacket: {
SignReq req;
req.populate(_r);
handleSignMsg(_from, req);
key = req.sig.hex();
pbft_msg = req;
break;
}
case CommitReqPacket: {
CommitReq req;
req.populate(_r);
handleCommitMsg(_from, req);
key = req.sig.hex();
pbft_msg = req;
break;
}
case ViewChangeReqPacket: {
ViewChangeReq req;
req.populate(_r);
handleViewChangeMsg(_from, req);
key = req.sig.hex() + toJS(req.view);
pbft_msg = req;
break;
}
default: {
LOG(ERROR) << "Recv error msg, id=" << _id;
return;
}
}
bool time_flag = (pbft_msg.timestamp >= now_time) || (now_time - pbft_msg.timestamp < m_view_timeout);
bool height_flag = (pbft_msg.height > m_highest_block.number()) || (m_highest_block.number() - pbft_msg.height < 10);
//LOG(TRACE) << "key=" << key << ",time_flag=" << time_flag << ",height_flag=" << height_flag;
if (key.size() > 0 && time_flag && height_flag) {
std::unordered_set<h512> filter;
filter.insert(_node);
h512 gen_node_id = h512(0);
if (NodeConnManagerSingleton::GetInstance().getPublicKey(pbft_msg.idx, gen_node_id)) {
filter.insert(gen_node_id);
}
broadcastMsg(key, _id, _r.toBytes(), filter);
}
}
void PBFT::changeViewForEmptyBlockWithoutLock(u256 const& _from) {
LOG(INFO) << "changeViewForEmptyBlockWithoutLock m_to_view=" << m_to_view << ", from=" << _from << ", node=" << m_node_idx;
m_last_consensus_time = 0;
m_last_sign_time = 0;
m_change_cycle = 0;
m_empty_block_flag = true;
m_signalled.notify_all();
}
void PBFT::changeViewForEmptyBlockWithLock() {
Guard l(m_mutex);
LOG(INFO) << "changeViewForEmptyBlockWithLock m_to_view=" << m_to_view << ", node=" << m_node_idx;
m_last_consensus_time = 0;
m_last_sign_time = 0;
m_change_cycle = 0;
m_empty_block_flag = true;
m_leader_failed = true; // m_leader_failed would set in checkTimeout, however we set in this place is aim to let the empty block leader not issue a empty block at once (在checkTimeout的时候会设置,但是这里加上的目的是为了让出空块者不会立即再出空块)
m_signalled.notify_all();
}
void PBFT::checkTimeout() {
Timer t;
bool flag = false;
{
Guard l(m_mutex);
auto now_time = utcTime();
auto last_time = std::max(m_last_consensus_time, m_last_sign_time);
auto interval = (uint64_t)(m_view_timeout * std::pow(1.5, m_change_cycle));
if (now_time - last_time >= interval) {
m_leader_failed = true;
m_to_view += 1;
m_change_cycle = std::min(m_change_cycle + 1, (unsigned)kMaxChangeCycle); // prevent overflow (防止溢出)
m_last_consensus_time = now_time;
flag = true;
// remove not used viewchange(not match block number and hash) info in cache (曾经收到的viewchange消息中跟我当前要的不一致就清空)
for (auto iter = m_recv_view_change_req[m_to_view].begin(); iter != m_recv_view_change_req[m_to_view].end();) {
if (iter->second.height < m_highest_block.number()) {
iter = m_recv_view_change_req[m_to_view].erase(iter);
} else if (iter->second.height == m_highest_block.number() && iter->second.block_hash != m_highest_block.hash(WithoutSeal)) { // prevent evil info (防作恶)
iter = m_recv_view_change_req[m_to_view].erase(iter);
} else {
++iter;
}
}
// start viewchange log
if (m_view + 1 == m_to_view)
{
PBFTFlowViewChangeLog(m_highest_block.number() + m_view, " view:" + m_view.convert_to<string>());
}
else
{
STAT_ERROR_MSG_LOGGUARD(STAT_PBFT_VIEWCHANGE_TAG) << "Timeout and ViewChanged!"
<< " m_view=" << m_view << ", m_to_view=" << m_to_view << ", m_change_cycle=" << m_change_cycle;
}
if (!broadcastViewChangeReq()) {
LOG(ERROR) << "broadcastViewChangeReq failed";
return;
}
checkAndChangeView();
LOG(DEBUG) << "checkTimeout timecost=" << t.elapsed() << ", m_view=" << m_view << ",m_to_view=" << m_to_view;
}
}
if (flag && m_onViewChange) {
m_onViewChange();
}
}
void PBFT::handleFutureBlock() {
Guard l(m_mutex);
if (m_future_prepare_cache.second.height == m_consensus_block_number && m_future_prepare_cache.second.view == m_view) {
LOG(INFO) << "handleFurtureBlock, blk=" << m_future_prepare_cache.second.height;
handlePrepareMsg(m_future_prepare_cache.first, m_future_prepare_cache.second);
m_future_prepare_cache = std::make_pair(Invalid256, PrepareReq());
}
}
void PBFT::recvFutureBlock(u256 const& _from, PrepareReq const& _req) {
if (m_future_prepare_cache.second.block_hash != _req.block_hash) {
m_future_prepare_cache = std::make_pair(_from, _req);
LOG(INFO) << "recvFutureBlock, blk=" << _req.height << ",hash=" << _req.block_hash << ",idx=" << _req.idx;
}
}
Signature PBFT::signHash(h256 const & _hash) const {
return dev::sign(m_key_pair.sec(), _hash);
}
bool PBFT::checkSign(u256 const & _idx, h256 const & _hash, Signature const & _sig) const {
Public pub_id;
if (!NodeConnManagerSingleton::GetInstance().getPublicKey(_idx, pub_id)) {
LOG(ERROR) << "Can't find node, idx=" << _idx;
return false;
}
return dev::verify(pub_id, _sig, _hash);
}
bool PBFT::checkSign(PBFTMsg const& _req) const {
Public pub_id;
if (!NodeConnManagerSingleton::GetInstance().getPublicKey(_req.idx, pub_id)) {
LOG(ERROR) << "Can't find node, idx=" << _req.idx;
return false;
}
return dev::verify(pub_id, _req.sig, _req.block_hash) && dev::verify(pub_id, _req.sig2, _req.fieldsWithoutBlock());
}
bool PBFT::broadcastViewChangeReq() {
LOG(INFO) << "Ready to broadcastViewChangeReq, blk=" << m_highest_block.number() << ",view=" << m_view << ",to_view=" << m_to_view << ",m_change_cycle=" << m_change_cycle;
if (m_account_type != EN_ACCOUNT_TYPE_MINER) {
LOG(INFO) << "broadcastViewChangeReq give up for not miner";
return true;
}
ViewChangeReq req;
req.height = m_highest_block.number();
req.view = m_to_view;
req.idx = m_node_idx;
req.timestamp = u256(utcTime());
req.block_hash = m_highest_block.hash(WithoutSeal);
req.sig = signHash(req.block_hash);
req.sig2 = signHash(req.fieldsWithoutBlock());
if (!m_empty_block_flag) {
LOGCOMWARNING << WarningMap.at(ChangeViewWarning) << "|blockNumber:" << req.height << " ChangeView:" << req.view;
m_empty_block_flag = false;
}
RLPStream ts;
req.streamRLPFields(ts);
bool ret = broadcastMsg(req.sig.hex() + toJS(req.view), ViewChangeReqPacket, ts.out());
return ret;
}
bool PBFT::broadcastSignReq(PrepareReq const & _req) {
SignReq sign_req;
sign_req.height = _req.height;
sign_req.view = _req.view;
sign_req.idx = m_node_idx;
sign_req.timestamp = u256(utcTime());
sign_req.block_hash = _req.block_hash;
sign_req.sig = signHash(sign_req.block_hash);
sign_req.sig2 = signHash(sign_req.fieldsWithoutBlock());
RLPStream ts;
sign_req.streamRLPFields(ts);
if (broadcastMsg(sign_req.sig.hex(), SignReqPacket, ts.out())) {
addSignReq(sign_req);
return true;
}
return false;
}
bool PBFT::broadcastCommitReq(PrepareReq const & _req) {
CommitReq commit_req;
commit_req.height = _req.height;
commit_req.view = _req.view;
commit_req.idx = m_node_idx;
commit_req.timestamp = u256(utcTime());
commit_req.block_hash = _req.block_hash;
commit_req.sig = signHash(commit_req.block_hash);
commit_req.sig2 = signHash(commit_req.fieldsWithoutBlock());
RLPStream ts;
commit_req.streamRLPFields(ts);
if (broadcastMsg(commit_req.sig.hex(), CommitReqPacket, ts.out())) {
addCommitReq(commit_req);
return true;
}
return false;
}
bool PBFT::broadcastPrepareReq(BlockHeader const & _bi, bytes const & _block_data) {
PrepareReq req;
req.height = _bi.number();
req.view = m_view;
req.idx = m_node_idx;
req.timestamp = u256(utcTime());
req.block_hash = _bi.hash(WithoutSeal);
req.sig = signHash(req.block_hash);
req.sig2 = signHash(req.fieldsWithoutBlock());
req.block = _block_data;
RLPStream ts;
req.streamRLPFields(ts);
if (broadcastMsg(req.block_hash.hex(), PrepareReqPacket, ts.out())) {
addRawPrepare(req);
return true;
}
return false;
}
bool PBFT::broadcastMsg(std::string const & _key, unsigned _id, bytes const & _data, std::unordered_set<h512> const & _filter) {
if (auto h = m_host.lock()) {
h->foreachPeer([&](shared_ptr<PBFTPeer> _p)
{
NodeID nodeid;
auto session = _p->session();
if (session && (nodeid = session->id()))
{
unsigned account_type = 0;
if ( !NodeConnManagerSingleton::GetInstance().getAccountType(nodeid, account_type)) {
LOG(INFO) << "Cannot get account type for peer" << nodeid;
return true;
}
if ( _id != ViewChangeReqPacket && account_type != EN_ACCOUNT_TYPE_MINER && !m_bc->chainParams().broadcastToNormalNode) {
return true;
}
if (_filter.count(nodeid)) { // forward the broadcast to other node (转发广播)
this->broadcastMark(_key, _id, _p);
return true;
}
if (this->broadcastFilter(_key, _id, _p)) {
return true;
}
RLPStream ts;
_p->prep(ts, _id, 1).append(_data);
_p->sealAndSend(ts);
this->broadcastMark(_key, _id, _p);
}
return true;
});
return true;
}
return false;
}
bool PBFT::broadcastFilter(std::string const & _key, unsigned _id, shared_ptr<PBFTPeer> _p) {
if (_id == PrepareReqPacket) {
DEV_GUARDED(_p->x_knownPrepare)
return _p->m_knownPrepare.exist(_key);
} else if (_id == SignReqPacket) {
DEV_GUARDED(_p->x_knownSign)
return _p->m_knownSign.exist(_key);
} else if (_id == ViewChangeReqPacket) {
DEV_GUARDED(_p->x_knownViewChange)
return _p->m_knownViewChange.exist(_key);
} else if (_id == CommitReqPacket) {
DEV_GUARDED(_p->x_knownCommit)
return _p->m_knownCommit.exist(_key);
} else {
return true;
}
return true;
}
void PBFT::broadcastMark(std::string const & _key, unsigned _id, shared_ptr<PBFTPeer> _p) {
if (_id == PrepareReqPacket) {
DEV_GUARDED(_p->x_knownPrepare)
{
if (_p->m_knownPrepare.size() > kKnownPrepare) {
_p->m_knownPrepare.pop();
}
_p->m_knownPrepare.push(_key);
}
} else if (_id == SignReqPacket) {
DEV_GUARDED(_p->x_knownSign)
{
if (_p->m_knownSign.size() > kKnownSign) {
_p->m_knownSign.pop();
}
_p->m_knownSign.push(_key);
}
} else if (_id == ViewChangeReqPacket) {
DEV_GUARDED(_p->x_knownViewChange)
{
if (_p->m_knownViewChange.size() > kKnownViewChange) {
_p->m_knownViewChange.pop();
}
_p->m_knownViewChange.push(_key);
}
} else if (_id == CommitReqPacket) {
DEV_GUARDED(_p->x_knownCommit)
{
if (_p->m_knownCommit.size() > kKnownCommit) {
_p->m_knownCommit.pop();
}
_p->m_knownCommit.push(_key);
}
} else {
// do nothing
}
}
void PBFT::clearMask() {
if (auto h = m_host.lock()) {
h->foreachPeer([&](shared_ptr<PBFTPeer> _p)
{
DEV_GUARDED(_p->x_knownPrepare)
_p->m_knownPrepare.clear();
DEV_GUARDED(_p->x_knownSign)
_p->m_knownSign.clear();
DEV_GUARDED(_p->x_knownCommit)
_p->m_knownCommit.clear();
DEV_GUARDED(_p->x_knownViewChange)
_p->m_knownViewChange.clear();
return true;
});
}
}
bool PBFT::isExistPrepare(PrepareReq const & _req) {
return m_raw_prepare_cache.block_hash == _req.block_hash;
}
bool PBFT::isExistSign(SignReq const & _req) {
auto iter = m_sign_cache.find(_req.block_hash);
if (iter == m_sign_cache.end()) {
return false;
}
return iter->second.find(_req.sig.hex()) != iter->second.end();
}
bool PBFT::isExistCommit(CommitReq const & _req) {
auto iter = m_commit_cache.find(_req.block_hash);
if (iter == m_commit_cache.end()) {
return false;
}
return iter->second.find(_req.sig.hex()) != iter->second.end();
}
bool PBFT::isExistViewChange(ViewChangeReq const & _req) {
auto iter = m_recv_view_change_req.find(_req.view);
if (iter == m_recv_view_change_req.end()) {
return false;
}
return iter->second.find(_req.idx) != iter->second.end();
}
void PBFT::handlePrepareMsg(u256 const & _from, PrepareReq const & _req, bool _self) {
Timer t;
ostringstream oss;
oss << "handlePrepareMsg: idx=" << _req.idx << ",view=" << _req.view << ",blk=" << _req.height << ",hash=" << _req.block_hash.abridged() << ",from=" << _from;
VLOG(10) << oss.str() << ", net-time=" << u256(utcTime()) - _req.timestamp;
if (isExistPrepare(_req)) {
VLOG(10) << oss.str() << "Discard an illegal prepare, duplicated";
return;
}
if (!_self && _req.idx == m_node_idx) {
LOG(ERROR) << oss.str() << "Discard an illegal prepare, your own req";
return;
}
if (_req.height < m_consensus_block_number || _req.view < m_view) {
VLOG(10) << oss.str() << "Discard an illegal prepare, lower than your needed blk";
return;
}
if (_req.height > m_consensus_block_number || _req.view > m_view) {
LOG(INFO) << oss.str() << "Recv a future block, wait to be handled later";
recvFutureBlock(_from, _req);
return;
}
auto leader = getLeader();
if (!leader.first || _req.idx != leader.second) {
LOG(ERROR) << oss.str() << "Recv an illegal prepare, err leader";
return;
}
if (_req.height == m_committed_prepare_cache.height && _req.block_hash != m_committed_prepare_cache.block_hash) {
LOG(INFO) << oss.str() << "Discard an illegal prepare req, commited but not saved hash=" << m_committed_prepare_cache.block_hash.abridged();
return;
}
if (!checkSign(_req)) {
LOG(ERROR) << oss.str() << "CheckSign failed";
return;
}
// addRawPrepare 需要放在 _req.block_hash != m_committed_prepare_cache.block_hash 之后,因为 addRawPrepare 会重置 prepare 的信息
// 若节点已到 commit 阶段,那么在上面就会退出,如果在 sign 阶段,则相当于使用这个新的prepare重新开始sign流程
// addRawPrepare shoud put after '_req.block_hash != m_committed_prepare_cache.block_hash', for the reason that the addRawPrepare would reset the prepare cache
// if this node is execting to commit phase, then when receive a new prepare package, it would exit at '_req.block_hash != m_committed_prepare_cache.block_hash',
// while this node is execting sign phase, it equals to use this new prepare package to restart a new PBFT flow
addRawPrepare(_req); // must after recvFutureBlock (必须在recvFutureBlock之后)
LOG(TRACE) << "start exec tx, blk=" << _req.height << ",hash=" << _req.block_hash << ",idx=" << _req.idx << ", time=" << utcTime();
Block outBlock(*m_bc, *m_stateDB);
try {
m_bc->checkBlockValid(_req.block_hash, _req.block, outBlock);
if (outBlock.info().hash(WithoutSeal) != _req.block_hash) { // check whether the block data has been changed (检验块数据是否被更改)
LOG(ERROR) << oss.str() << ", block_hash is not equal to block";
return;
}
m_last_exec_finish_time = utcTime();
}
catch (std::exception &ex) {
LOG(ERROR) << oss.str() << "CheckBlockValid failed" << ex.what();
return;
}
// change leader for empty block (空块切换)
if (outBlock.pending().size() == 0 && m_omit_empty_block) {
changeViewForEmptyBlockWithoutLock(_from);
// for empty block
stringstream ss;
ss << "#empty blk hash:" << _req.block_hash.abridged() << " height:" << _req.height;
PBFTFlowLog(m_highest_block.number() + m_view, ss.str(), 1);
return;
}
// regenerate block data (重新生成block数据)
outBlock.commitToSeal(*m_bc, outBlock.info().extraData());
m_bc->addBlockCache(outBlock, outBlock.info().difficulty());
RLPStream ts;
outBlock.info().streamRLP(ts, WithoutSeal);
if (!outBlock.sealBlock(ts.out())) {
LOG(ERROR) << oss.str() << "Error: sealBlock failed 3";
return;
}
LOG(DEBUG) << "finish exec tx, blk=" << _req.height << ", time=" << utcTime();
// execed log
stringstream ss;
// TODO FLAG2 hash means real hash!
// ss << "hash:" << _req.block_hash.abridged() << " realhash:" << outBlock.info().hash(WithoutSeal).abridged()
// << " height:" << _req.height << " txnum:" << outBlock.pending().size();
ss << "hash:" << outBlock.info().hash(WithoutSeal) << " unexected_hash:" << _req.block_hash.abridged()
<< " height:" << _req.height << " txnum:" << outBlock.pending().size();
PBFTFlowLog(m_highest_block.number() + m_view, ss.str());
// regenerate Prepare package (重新生成Prepare)
PrepareReq req;
req.height = _req.height;
req.view = _req.view;
req.idx = _req.idx;
req.timestamp = u256(utcTime());
req.block_hash = outBlock.info().hash(WithoutSeal);
req.sig = signHash(req.block_hash);
req.sig2 = signHash(req.fieldsWithoutBlock());
req.block = outBlock.blockData();
if (!addPrepareReq(req)) {
LOG(ERROR) << oss.str() << "addPrepare failed";
return;
}
if (m_account_type == EN_ACCOUNT_TYPE_MINER && !broadcastSignReq(req)) {
LOG(ERROR) << oss.str() << "broadcastSignReq failed";
//return;
}
LOG(INFO) << oss.str() << ",real_block_hash=" << outBlock.info().hash(WithoutSeal).abridged() << " success";
checkAndCommit();
LOG(DEBUG) << "handlePrepareMsg, timecost=" << 1000 * t.elapsed();
return;
}
void PBFT::handleSignMsg(u256 const & _from, SignReq const & _req) {
Timer t;
ostringstream oss;
oss << "handleSignMsg: idx=" << _req.idx << ",view=" << _req.view << ",blk=" << _req.height << ",hash=" << _req.block_hash.abridged() << ", from=" << _from;
VLOG(10) << oss.str() << ", net-time=" << u256(utcTime()) - _req.timestamp;
if (isExistSign(_req)) {
VLOG(10) << oss.str() << "Discard an illegal sign, duplicated";
return;
}
if (_req.idx == m_node_idx) {
LOG(ERROR) << oss.str() << "Discard an illegal sign, your own req";
return;
}
if (m_prepare_cache.block_hash != _req.block_hash) {
VLOG(10) << oss.str() << "Recv a sign_req for block which not in prepareCache, preq=" << m_prepare_cache.block_hash.abridged();
bool future_msg = _req.height >= m_consensus_block_number || _req.view > m_view;
if (future_msg && checkSign(_req)) {
addSignReq(_req);
LOG(INFO) << oss.str() << "Cache this sign_req";
}
return;
}
if (m_prepare_cache.view != _req.view) {
LOG(INFO) << oss.str() << "Discard a sign_req which view is not equal, preq.v=" << m_prepare_cache.view;
return;
}
if (!checkSign(_req)) {
LOG(ERROR) << oss.str() << "CheckSign failed";
return;
}
LOG(INFO) << oss.str() << ", success";
addSignReq(_req);
checkAndCommit();
LOG(DEBUG) << "handleSignMsg, timecost=" << 1000 * t.elapsed();
return;
}
void PBFT::handleCommitMsg(u256 const &_from, CommitReq const &_req) {
Timer t;
ostringstream oss;
oss << "handleCommitMsg: idx=" << _req.idx << ",view=" << _req.view << ",blk=" << _req.height << ",hash=" << _req.block_hash.abridged() << ", from=" << _from;
VLOG(10) << oss.str() << ", net-time=" << u256(utcTime()) - _req.timestamp;
if (isExistCommit(_req)) {
VLOG(10) << oss.str() << " Discard an illegal commit, duplicated";
return;
}
if (_req.idx == m_node_idx) {
LOG(ERROR) << oss.str() << " Discard an illegal commit, your own req";
return;
}
if (m_prepare_cache.block_hash != _req.block_hash) {
VLOG(10) << oss.str() << "Recv a commit_req for block which not in prepareCache, preq=" << m_prepare_cache.block_hash.abridged();
bool future_msg = _req.height >= m_consensus_block_number || _req.view > m_view;
if (future_msg && checkSign(_req)) {
addCommitReq(_req);
LOG(INFO) << oss.str() << "Cache this commit_req";
}
return;
}
if (m_prepare_cache.view != _req.view) {
LOG(INFO) << oss.str() << " Discard an illegal commit, view is not equal prepare " << m_prepare_cache.view;
return;
}
if (!checkSign(_req)) {
LOG(ERROR) << oss.str() << "CheckSign failed";
return;
}
LOG(INFO) << oss.str() << ", success";
addCommitReq(_req);
checkAndSave();
LOG(DEBUG) << "handleCommitMsg, timecost=" << 1000 * t.elapsed();
return;
}
void PBFT::handleViewChangeMsg(u256 const & _from, ViewChangeReq const & _req) {
Timer t;
ostringstream oss;
oss << "handleViewChangeMsg: idx=" << _req.idx << ",view=" << _req.view << ",blk=" << _req.height << ",hash=" << _req.block_hash.abridged() << ",from=" << _from;
VLOG(10) << oss.str() << ", net-time=" << u256(utcTime()) - _req.timestamp;
if (isExistViewChange(_req)) {
VLOG(10) << oss.str() << "Discard an illegal viewchange, duplicated";
return;
}
if (_req.idx == m_node_idx) {
LOG(ERROR) << oss.str() << "Discard an illegal viewchange, your own req";
return;
}
// +1 是为了防止触碰到刚好view正在切换的边界条件。因为view落后的节点的view必定是低于(>2)其他整成节点的view
// this is for motivating viewchange, for the envs that if one node crash and other node's view has increased to a large number, than the node restart, it should broadcast a viewchange to other node
// other node receive the low view viewchange, would trigger follow code to motivate the node. +1 is to prevent the case that the view just change, for the reason
// which the new started node' view must fall behind(>2) the excited node
if (_req.view + 1 < m_to_view) {
LOG(INFO) << oss.str() << " send response to node=" << _from << " for motivating viewchange";
broadcastViewChangeReq();
}
if (_req.height < m_highest_block.number() || _req.view <= m_view) {
VLOG(10) << oss.str() << "Discard an illegal viewchange, m_highest_block=" << m_highest_block.number() << ",m_view=" << m_view;
return;
}
if (_req.height == m_highest_block.number() && _req.block_hash != m_highest_block.hash(WithoutSeal) && m_bc->block(_req.block_hash).size() == 0) {
LOG(INFO) << oss.str() << "Discard an illegal viewchange, same height but not hash, chain has been forked, my=" << m_highest_block.hash(WithoutSeal) << ",req=" << _req.block_hash;
return;
}
if (!checkSign(_req)) {
LOG(ERROR) << oss.str() << "CheckSign failed";