-
Notifications
You must be signed in to change notification settings - Fork 370
/
ordering_service.py
2491 lines (2130 loc) · 107 KB
/
ordering_service.py
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
import itertools
import logging
import time
from _sha256 import sha256
from collections import defaultdict, OrderedDict, deque
from functools import partial
from typing import Tuple, List, Set, Optional, Dict, Iterable, Callable
from orderedset._orderedset import OrderedSet
from sortedcontainers import SortedList
from common.exceptions import PlenumValueError, LogicError
from common.serializers.serialization import state_roots_serializer, invalid_index_serializer, serialize_msg_for_signing
from crypto.bls.bls_bft_replica import BlsBftReplica
from plenum.common.config_util import getConfig
from plenum.common.constants import POOL_LEDGER_ID, SEQ_NO_DB_LABEL, AUDIT_LEDGER_ID, TXN_TYPE, \
LAST_SENT_PP_STORE_LABEL, AUDIT_TXN_PP_SEQ_NO, AUDIT_TXN_VIEW_NO, AUDIT_TXN_PRIMARIES, AUDIT_TXN_DIGEST, \
PREPREPARE, PREPARE, COMMIT, DOMAIN_LEDGER_ID, TS_LABEL, AUDIT_TXN_NODE_REG, CONFIG_LEDGER_ID
from plenum.common.event_bus import InternalBus, ExternalBus
from plenum.common.exceptions import SuspiciousNode, InvalidClientMessageException, SuspiciousPrePrepare, \
UnknownIdentifier
from plenum.common.ledger import Ledger
from plenum.common.messages.internal_messages import RequestPropagates, BackupSetupLastOrdered, \
RaisedSuspicion, ViewChangeStarted, NewViewCheckpointsApplied, MissingMessage, CheckpointStabilized, \
ReAppliedInNewView, NewViewAccepted, CatchupCheckpointsApplied, MasterReorderedAfterVC
from plenum.common.messages.node_messages import PrePrepare, Prepare, Commit, Reject, ThreePhaseKey, Ordered, \
OldViewPrePrepareRequest, OldViewPrePrepareReply
from plenum.common.metrics_collector import MetricsName, MetricsCollector, NullMetricsCollector
from plenum.common.request import Request
from plenum.common.router import Subscription
from plenum.common.stashing_router import PROCESS
from plenum.common.timer import TimerService, RepeatingTimer
from plenum.common.txn_util import get_payload_digest, get_payload_data, get_seq_no, get_txn_time
from plenum.common.types import f
from plenum.common.util import compare_3PC_keys, updateNamedTuple, SortedDict, getMaxFailures, mostCommonElement, \
get_utc_epoch, max_3PC_key, reasonForClientFromException
from plenum.server.batch_handlers.three_pc_batch import ThreePcBatch
from plenum.server.consensus.consensus_shared_data import ConsensusSharedData
from plenum.server.consensus.batch_id import BatchID
from plenum.server.consensus.metrics_decorator import measure_consensus_time
from plenum.server.consensus.ordering_service_msg_validator import OrderingServiceMsgValidator
from plenum.server.consensus.primary_selector import PrimariesSelector
from plenum.server.consensus.utils import replica_name_to_node_name, get_original_viewno, preprepare_to_batch_id
from plenum.server.replica_helper import PP_APPLY_REJECT_WRONG, PP_APPLY_WRONG_DIGEST, PP_APPLY_WRONG_STATE, \
PP_APPLY_ROOT_HASH_MISMATCH, PP_APPLY_HOOK_ERROR, PP_SUB_SEQ_NO_WRONG, PP_NOT_FINAL, PP_APPLY_AUDIT_HASH_MISMATCH, \
PP_REQUEST_ALREADY_ORDERED, PP_CHECK_NOT_FROM_PRIMARY, PP_CHECK_TO_PRIMARY, PP_CHECK_DUPLICATE, \
PP_CHECK_INCORRECT_POOL_STATE_ROOT, PP_CHECK_OLD, PP_CHECK_REQUEST_NOT_FINALIZED, PP_CHECK_NOT_NEXT, \
PP_CHECK_WRONG_TIME, Stats, OrderedTracker, TPCStat, generateName, PP_WRONG_PRIMARIES
from plenum.server.replica_freshness_checker import FreshnessChecker
from plenum.server.replica_helper import replica_batch_digest
from plenum.server.replica_validator_enums import STASH_VIEW_3PC, STASH_CATCH_UP, STASH_WAITING_FIRST_BATCH_IN_VIEW
from plenum.server.request_handlers.ledgers_freeze.ledger_freeze_helper import StaticLedgersFreezeHelper
from plenum.server.request_managers.write_request_manager import WriteRequestManager
from plenum.server.suspicion_codes import Suspicions
from stp_core.common.log import getlogger
logger = getlogger()
class OrderingService:
def __init__(self,
data: ConsensusSharedData,
timer: TimerService,
bus: InternalBus,
network: ExternalBus,
write_manager: WriteRequestManager,
bls_bft_replica: BlsBftReplica,
freshness_checker: FreshnessChecker,
stasher=None,
get_current_time: Optional[Callable[[], float]] = None,
get_time_for_3pc_batch: Optional[Callable[[], int]] = None,
metrics: MetricsCollector = NullMetricsCollector()):
self.metrics = metrics
self._data = data
self._requests = self._data.requests
self._timer = timer
self._bus = bus
self._network = network
self._write_manager = write_manager
self._name = self._data.name
# TODO: We shouldn't use get_utc_epoch here, time needs to be under full control through TimerService
self.get_time_for_3pc_batch = get_time_for_3pc_batch or get_utc_epoch
# Flag which node set, when it have set new primaries and need to send batch
self.primaries_batch_needed = False
self._config = getConfig()
# TODO: Change just to self._stasher = stasher
self._stasher = stasher
self._subscription = Subscription()
self._validator = OrderingServiceMsgValidator(self._data)
self.get_current_time = get_current_time or self._timer.get_current_time
self._out_of_order_repeater = RepeatingTimer(self._timer,
self._config.PROCESS_STASHED_OUT_OF_ORDER_COMMITS_INTERVAL,
self._process_stashed_out_of_order_commits,
active=False)
"""
Maps from legacy replica code
"""
self._state_root_serializer = state_roots_serializer
# Keeps a map of PRE-PREPAREs which did not satisfy timestamp
# criteria, they can be accepted if >f PREPAREs are encountered.
# This is emptied on view change. With each PRE-PREPARE, a flag is
# stored which indicates whether there are sufficient acceptable
# PREPAREs or not
self.pre_prepares_stashed_for_incorrect_time = {}
# Time of the last PRE-PREPARE which satisfied all validation rules
# (time, digest, roots were all correct). This time is not to be
# reverted even if the PRE-PREPAREs are not ordered. This implies that
# the next primary would have seen all accepted PRE-PREPAREs or another
# view change will happen
self.last_accepted_pre_prepare_time = None
# PRE-PREPAREs timestamps stored by non primary replica to check
# obsolescence of incoming PrePrepares. Pre-prepares with the same
# 3PC key are not merged since we need to keep incoming timestamps
# for each new PP from every nodes separately.
# Dictionary:
# key: Tuple[pp.viewNo, pp.seqNo]
# value: Dict[Tuple[PrePrepare, sender], timestamp]
self.pre_prepare_tss = defaultdict(dict)
# PRE-PREPAREs that are waiting to be processed but do not have the
# corresponding request finalised. Happens when replica has not been
# forwarded the request by the node but is getting 3 phase messages.
# The value is a list since a malicious entry might send PRE-PREPARE
# with a different digest and since we dont have the request finalised
# yet, we store all PRE-PPREPAREs
# type: List[Tuple[PrePrepare, str, Set[Tuple[str, int]]]]
self.prePreparesPendingFinReqs = []
# PrePrepares waiting for previous PrePrepares, key being tuple of view
# number and pre-prepare sequence numbers and value being tuple of
# PrePrepare and sender
# TODO: Since pp_seq_no will start from 1 in each view, the comparator
# of SortedDict needs to change
self.prePreparesPendingPrevPP = SortedDict(lambda k: (k[0], k[1]))
# PREPAREs that are stored by non primary replica for which it has not
# got any PRE-PREPARE. Dictionary that stores a tuple of view no and
# prepare sequence number as key and a deque of PREPAREs as value.
# This deque is attempted to be flushed on receiving every
# PRE-PREPARE request.
self.preparesWaitingForPrePrepare = {}
# Defines if there was a batch after last catchup
self.first_batch_after_catchup = False
self._lastPrePrepareSeqNo = self._data.low_watermark # type: int
# COMMITs that are stored for which there are no PRE-PREPARE or PREPARE
# received
self.commitsWaitingForPrepare = {}
# type: Dict[Tuple[int, int], deque]
# Dictionary of received PRE-PREPAREs. Key of dictionary is a 2
# element tuple with elements viewNo, pre-prepare seqNo and value
# is the received PRE-PREPARE
self.prePrepares = SortedDict(lambda k: (k[0], k[1]))
# type: Dict[Tuple[int, int], PrePrepare]
# Dictionary to keep track of the which replica was primary during each
# view. Key is the view no and value is the name of the primary
# replica during that view
self.primary_names = OrderedDict() # type: OrderedDict[int, str]
# Did we log a message about getting request while absence of primary
self.warned_no_primary = False
self.requestQueues = {} # type: Dict[int, OrderedSet]
self.stats = Stats(TPCStat)
self.batches = OrderedDict() # type: OrderedDict[Tuple[int, int]]
self.l_bls_bft_replica = bls_bft_replica
# Set of tuples to keep track of ordered requests. Each tuple is
# (viewNo, ppSeqNo).
self.ordered = OrderedTracker()
self.lastBatchCreated = self.get_current_time()
# Commits which are not being ordered since commits with lower
# sequence numbers have not been ordered yet. Key is the
# viewNo and value a map of pre-prepare sequence number to commit
# type: Dict[int,Dict[int,Commit]]
self.stashed_out_of_order_commits = {}
self._freshness_checker = freshness_checker
self._skip_send_3pc_ts = None
self._subscription.subscribe(self._stasher, PrePrepare, self.process_preprepare)
self._subscription.subscribe(self._stasher, Prepare, self.process_prepare)
self._subscription.subscribe(self._stasher, Commit, self.process_commit)
self._subscription.subscribe(self._stasher, NewViewCheckpointsApplied, self.process_new_view_checkpoints_applied)
self._subscription.subscribe(self._stasher, OldViewPrePrepareRequest, self.process_old_view_preprepare_request)
self._subscription.subscribe(self._stasher, OldViewPrePrepareReply, self.process_old_view_preprepare_reply)
self._subscription.subscribe(self._bus, ViewChangeStarted, self.process_view_change_started)
self._subscription.subscribe(self._bus, CheckpointStabilized, self.process_checkpoint_stabilized)
self._subscription.subscribe(self._bus, NewViewAccepted, self.process_new_view_accepted)
self._subscription.subscribe(self._bus, CatchupCheckpointsApplied, self.process_catchup_checkpoints_applied)
# Dict to keep PrePrepares from old view to be re-ordered in the new view
# key is (viewNo, ppSeqNo, ppDigest) tuple, and value is PrePrepare
self.old_view_preprepares = {}
# TODO: find a better place for calling this setter
if self.is_master:
self._write_manager.node_reg_handler.set_internal_bus(self._bus)
def cleanup(self):
self._subscription.unsubscribe_all()
def __repr__(self):
return self.name
@measure_consensus_time(MetricsName.PROCESS_PREPARE_TIME,
MetricsName.BACKUP_PROCESS_PREPARE_TIME)
def process_prepare(self, prepare: Prepare, sender: str):
"""
Validate and process the PREPARE specified.
If validation is successful, create a COMMIT and broadcast it.
:param prepare: a PREPARE msg
:param sender: name of the node that sent the PREPARE
"""
result, reason = self._validate(prepare)
if result != PROCESS:
return result, reason
key = (prepare.viewNo, prepare.ppSeqNo)
logger.debug("{} received PREPARE{} from {}".format(self, key, sender))
# TODO move this try/except up higher
try:
if self._validate_prepare(prepare, sender):
self._add_to_prepares(prepare, sender)
self.stats.inc(TPCStat.PrepareRcvd)
logger.debug("{} processed incoming PREPARE {}".format(
self, (prepare.viewNo, prepare.ppSeqNo)))
else:
# TODO let's have isValidPrepare throw an exception that gets
# handled and possibly logged higher
logger.trace("{} cannot process incoming PREPARE".format(self))
except SuspiciousNode as ex:
self.report_suspicious_node(ex)
return None, None
def _validate_prepare(self, prepare: Prepare, sender: str) -> bool:
"""
Return whether the PREPARE specified is valid.
:param prepare: the PREPARE to validate
:param sender: the name of the node that sent the PREPARE
:return: True if PREPARE is valid, False otherwise
"""
key = (prepare.viewNo, prepare.ppSeqNo)
primaryStatus = self._is_primary_for_msg(prepare)
ppReq = self.get_preprepare(*key)
# If a non primary replica and receiving a PREPARE request before a
# PRE-PREPARE request, then proceed
# PREPARE should not be sent from primary
if self._is_msg_from_primary(prepare, sender):
self.report_suspicious_node(SuspiciousNode(sender, Suspicions.PR_FRM_PRIMARY, prepare))
return False
# If non primary replica
if primaryStatus is False:
if self.prepares.hasPrepareFrom(prepare, sender):
self.report_suspicious_node(SuspiciousNode(
sender, Suspicions.DUPLICATE_PR_SENT, prepare))
return False
# If PRE-PREPARE not received for the PREPARE, might be slow
# network
if not ppReq:
self._enqueue_prepare(prepare, sender)
self.l_setup_last_ordered_for_non_master()
return False
# If primary replica
if primaryStatus is True:
if self.prepares.hasPrepareFrom(prepare, sender):
self.report_suspicious_node(SuspiciousNode(
sender, Suspicions.DUPLICATE_PR_SENT, prepare))
return False
# If PRE-PREPARE was not sent for this PREPARE, certainly
# malicious behavior unless this is re-ordering after view change where a new Primary may not have a
# PrePrepare from old view
elif not ppReq:
if prepare.ppSeqNo <= self._data.prev_view_prepare_cert:
self._enqueue_prepare(prepare, sender)
else:
self.report_suspicious_node(SuspiciousNode(
sender, Suspicions.UNKNOWN_PR_SENT, prepare))
return False
if primaryStatus is None and not ppReq:
self._enqueue_prepare(prepare, sender)
self.l_setup_last_ordered_for_non_master()
return False
if prepare.digest != ppReq.digest:
self.report_suspicious_node(SuspiciousNode(sender, Suspicions.PR_DIGEST_WRONG, prepare))
return False
elif prepare.stateRootHash != ppReq.stateRootHash:
self.report_suspicious_node(SuspiciousNode(sender, Suspicions.PR_STATE_WRONG,
prepare))
return False
elif prepare.txnRootHash != ppReq.txnRootHash:
self.report_suspicious_node(SuspiciousNode(sender, Suspicions.PR_TXN_WRONG,
prepare))
return False
elif prepare.auditTxnRootHash != ppReq.auditTxnRootHash:
self.report_suspicious_node(SuspiciousNode(sender, Suspicions.PR_AUDIT_TXN_ROOT_HASH_WRONG,
prepare))
return False
# BLS multi-sig:
self.l_bls_bft_replica.validate_prepare(prepare, sender)
return True
"""Method from legacy code"""
def _enqueue_prepare(self, pMsg: Prepare, sender: str):
key = (pMsg.viewNo, pMsg.ppSeqNo)
logger.debug("{} queueing prepare due to unavailability of PRE-PREPARE. "
"Prepare {} for key {} from {}".format(self, pMsg, key, sender))
if key not in self.preparesWaitingForPrePrepare:
self.preparesWaitingForPrePrepare[key] = deque()
self.preparesWaitingForPrePrepare[key].append((pMsg, sender))
if key not in self.pre_prepares_stashed_for_incorrect_time:
if self.is_master or self.last_ordered_3pc[1] != 0:
self._request_pre_prepare_for_prepare(key)
else:
self._process_stashed_pre_prepare_for_time_if_possible(key)
def _process_stashed_pre_prepare_for_time_if_possible(
self, key: Tuple[int, int]):
"""
Check if any PRE-PREPAREs that were stashed since their time was not
acceptable, can now be accepted since enough PREPAREs are received
"""
logger.debug('{} going to process stashed PRE-PREPAREs with '
'incorrect times'.format(self))
q = self._data.quorums.f
if len(self.preparesWaitingForPrePrepare[key]) > q:
times = [pr.ppTime for (pr, _) in
self.preparesWaitingForPrePrepare[key]]
most_common_time, freq = mostCommonElement(times)
if self._data.quorums.timestamp.is_reached(freq):
logger.debug('{} found sufficient PREPAREs for the '
'PRE-PREPARE{}'.format(self, key))
stashed_pp = self.pre_prepares_stashed_for_incorrect_time
pp, sender, done = stashed_pp[key]
if done:
logger.debug('{} already processed PRE-PREPARE{}'.format(self, key))
return True
# True is set since that will indicate to `is_pre_prepare_time_acceptable`
# that sufficient PREPAREs are received
stashed_pp[key] = (pp, sender, True)
self._network.process_incoming(pp, sender)
return True
return False
def _request_pre_prepare_for_prepare(self, three_pc_key) -> bool:
"""
Check if has an acceptable PRE_PREPARE already stashed, if not then
check count of PREPAREs, make sure >f consistent PREPAREs are found,
store the acceptable PREPARE state (digest, roots) for verification of
the received PRE-PREPARE
"""
if three_pc_key in self.prePreparesPendingPrevPP:
logger.debug('{} not requesting a PRE-PREPARE since already found '
'stashed for {}'.format(self, three_pc_key))
return False
if len(
self.preparesWaitingForPrePrepare[three_pc_key]) < self._data.quorums.prepare.value:
logger.debug(
'{} not requesting a PRE-PREPARE because does not have'
' sufficient PREPAREs for {}'.format(
self, three_pc_key))
return False
digest, state_root, txn_root, _ = \
self._get_acceptable_stashed_prepare_state(three_pc_key)
# Choose a better data structure for `prePreparesPendingFinReqs`
pre_prepares = [pp for pp, _, _ in self.prePreparesPendingFinReqs
if (pp.viewNo, pp.ppSeqNo) == three_pc_key]
if pre_prepares:
if [pp for pp in pre_prepares if (pp.digest, pp.stateRootHash, pp.txnRootHash) == (digest, state_root, txn_root)]:
logger.debug('{} not requesting a PRE-PREPARE since already '
'found stashed for {}'.format(self, three_pc_key))
return False
self._request_pre_prepare(three_pc_key,
stash_data=(digest, state_root, txn_root))
return True
def _get_acceptable_stashed_prepare_state(self, three_pc_key):
prepares = {s: (m.digest, m.stateRootHash, m.txnRootHash) for m, s in
self.preparesWaitingForPrePrepare[three_pc_key]}
acceptable, freq = mostCommonElement(prepares.values())
return (*acceptable, {s for s, state in prepares.items()
if state == acceptable})
def _is_primary_for_msg(self, msg) -> Optional[bool]:
"""
Return whether this replica is primary if the request's view number is
equal this replica's view number and primary has been selected for
the current view.
Return None otherwise.
:param msg: message
"""
return self._data.is_primary if self._is_msg_for_current_view(msg) \
else self._is_primary_in_view(msg.viewNo)
def _is_primary_in_view(self, viewNo: int) -> Optional[bool]:
"""
Return whether this replica was primary in the given view
"""
if viewNo not in self.primary_names:
return False
return self.primary_names[viewNo] == self.name
@measure_consensus_time(MetricsName.PROCESS_COMMIT_TIME,
MetricsName.BACKUP_PROCESS_COMMIT_TIME)
def process_commit(self, commit: Commit, sender: str):
"""
Validate and process the COMMIT specified.
If validation is successful, return the message to the node.
:param commit: an incoming COMMIT message
:param sender: name of the node that sent the COMMIT
"""
result, reason = self._validate(commit)
if result != PROCESS:
return result, reason
logger.debug("{} received COMMIT{} from {}".format(self, (commit.viewNo, commit.ppSeqNo), sender))
if self._validate_commit(commit, sender):
self.stats.inc(TPCStat.CommitRcvd)
self._add_to_commits(commit, sender)
logger.debug("{} processed incoming COMMIT{}".format(
self, (commit.viewNo, commit.ppSeqNo)))
return result, reason
def _validate_commit(self, commit: Commit, sender: str) -> bool:
"""
Return whether the COMMIT specified is valid.
:param commit: the COMMIT to validate
:return: True if `request` is valid, False otherwise
"""
key = (commit.viewNo, commit.ppSeqNo)
if not self._has_prepared(key):
self._enqueue_commit(commit, sender)
return False
if self.commits.hasCommitFrom(commit, sender):
self.report_suspicious_node(SuspiciousNode(sender, Suspicions.DUPLICATE_CM_SENT, commit))
return False
# BLS multi-sig (call it for non-ordered only to avoid redundant validations):
why_not = None
if not self._validator.has_already_ordered(commit.viewNo, commit.ppSeqNo):
pre_prepare = self.get_preprepare(commit.viewNo, commit.ppSeqNo)
why_not = self.l_bls_bft_replica.validate_commit(commit, sender, pre_prepare)
if why_not == BlsBftReplica.CM_BLS_SIG_WRONG:
logger.warning("{} discard Commit message from {}:{}".format(self, sender, commit))
self.report_suspicious_node(SuspiciousNode(sender,
Suspicions.CM_BLS_SIG_WRONG,
commit))
return False
elif why_not is not None:
logger.warning("Unknown error code returned for bls commit "
"validation {}".format(why_not))
return True
def _enqueue_commit(self, request: Commit, sender: str):
key = (request.viewNo, request.ppSeqNo)
logger.debug("{} - Queueing commit due to unavailability of PREPARE. "
"Request {} with key {} from {}".format(self, request, key, sender))
if key not in self.commitsWaitingForPrepare:
self.commitsWaitingForPrepare[key] = deque()
self.commitsWaitingForPrepare[key].append((request, sender))
@measure_consensus_time(MetricsName.PROCESS_PREPREPARE_TIME,
MetricsName.BACKUP_PROCESS_PREPREPARE_TIME)
def process_preprepare(self, pre_prepare: PrePrepare, sender: str):
"""
Validate and process provided PRE-PREPARE, create and
broadcast PREPARE for it.
:param pre_prepare: message
:param sender: name of the node that sent this message
"""
pp_key = (pre_prepare.viewNo, pre_prepare.ppSeqNo)
# the same PrePrepare might come here multiple times
if (pp_key and (pre_prepare.auditTxnRootHash, sender) not in self.pre_prepare_tss[pp_key]):
# TODO more clean solution would be to set timestamps
# earlier (e.g. in zstack)
self.pre_prepare_tss[pp_key][pre_prepare.auditTxnRootHash, sender] = self.get_time_for_3pc_batch()
result, reason = self._validate(pre_prepare)
if result != PROCESS:
return result, reason
key = (pre_prepare.viewNo, pre_prepare.ppSeqNo)
logger.debug("{} received PRE-PREPARE{} from {}".format(self, key, sender))
# TODO: should we still do it?
# Converting each req_idrs from list to tuple
req_idrs = {f.REQ_IDR.nm: [key for key in pre_prepare.reqIdr]}
pre_prepare = updateNamedTuple(pre_prepare, **req_idrs)
def report_suspicious(reason):
ex = SuspiciousNode(sender, reason, pre_prepare)
self.report_suspicious_node(ex)
why_not = self._can_process_pre_prepare(pre_prepare, sender)
if why_not is None:
why_not_applied = \
self._process_valid_preprepare(pre_prepare, sender)
if why_not_applied is not None:
if why_not_applied == PP_APPLY_REJECT_WRONG:
report_suspicious(Suspicions.PPR_REJECT_WRONG)
elif why_not_applied == PP_APPLY_WRONG_STATE:
report_suspicious(Suspicions.PPR_STATE_WRONG)
elif why_not_applied == PP_APPLY_ROOT_HASH_MISMATCH:
report_suspicious(Suspicions.PPR_TXN_WRONG)
elif why_not_applied == PP_APPLY_HOOK_ERROR:
report_suspicious(Suspicions.PPR_PLUGIN_EXCEPTION)
elif why_not_applied == PP_SUB_SEQ_NO_WRONG:
report_suspicious(Suspicions.PPR_SUB_SEQ_NO_WRONG)
elif why_not_applied == PP_NOT_FINAL:
# this is fine, just wait for another
return None, None
elif why_not_applied == PP_APPLY_AUDIT_HASH_MISMATCH:
report_suspicious(Suspicions.PPR_AUDIT_TXN_ROOT_HASH_WRONG)
elif why_not_applied == PP_REQUEST_ALREADY_ORDERED:
report_suspicious(Suspicions.PPR_WITH_ORDERED_REQUEST)
elif why_not_applied == PP_WRONG_PRIMARIES:
report_suspicious(Suspicions.PPR_WITH_WRONG_PRIMARIES)
elif why_not == PP_APPLY_WRONG_DIGEST:
report_suspicious(Suspicions.PPR_DIGEST_WRONG)
elif why_not == PP_CHECK_NOT_FROM_PRIMARY:
report_suspicious(Suspicions.PPR_FRM_NON_PRIMARY)
elif why_not == PP_CHECK_TO_PRIMARY:
report_suspicious(Suspicions.PPR_TO_PRIMARY)
elif why_not == PP_CHECK_DUPLICATE:
report_suspicious(Suspicions.DUPLICATE_PPR_SENT)
elif why_not == PP_CHECK_INCORRECT_POOL_STATE_ROOT:
report_suspicious(Suspicions.PPR_POOL_STATE_ROOT_HASH_WRONG)
elif why_not == PP_CHECK_OLD:
logger.info("PRE-PREPARE {} has ppSeqNo lower "
"then the latest one - ignoring it".format(key))
elif why_not == PP_CHECK_REQUEST_NOT_FINALIZED:
absents = set()
non_fin = set()
non_fin_payload = set()
for key in pre_prepare.reqIdr:
req = self._requests.get(key)
if req is None:
absents.add(key)
elif not req.finalised:
non_fin.add(key)
non_fin_payload.add(req.request.payload_digest)
absent_str = ', '.join(str(key) for key in absents)
non_fin_str = ', '.join(
'{} ({} : {})'.format(str(key),
str(len(self._requests[key].propagates)),
', '.join(self._requests[key].propagates.keys())) for key in non_fin)
logger.warning(
"{} found requests in the incoming pp, of {} ledger, that are not finalized. "
"{} of them don't have propagates: [{}]. "
"{} of them don't have enough propagates: [{}].".format(self, pre_prepare.ledgerId,
len(absents), absent_str,
len(non_fin), non_fin_str))
def signal_suspicious(req):
logger.info("Request digest {} already ordered. Discard {} "
"from {}".format(req, pre_prepare, sender))
report_suspicious(Suspicions.PPR_WITH_ORDERED_REQUEST)
# checking for payload digest is more effective
for payload_key in non_fin_payload:
if self.db_manager.get_store(SEQ_NO_DB_LABEL).get_by_payload_digest(payload_key) != (None, None):
signal_suspicious(payload_key)
return None, None
# for absents we can only check full digest
for full_key in absents:
if self.db_manager.get_store(SEQ_NO_DB_LABEL).get_by_full_digest(full_key) is not None:
signal_suspicious(full_key)
return None, None
bad_reqs = absents | non_fin
self._enqueue_pre_prepare(pre_prepare, sender, bad_reqs)
# TODO: An optimisation might be to not request PROPAGATEs
# if some PROPAGATEs are present or a client request is
# present and sufficient PREPAREs and PRE-PREPARE are present,
# then the digest can be compared but this is expensive as the
# PREPARE and PRE-PREPARE contain a combined digest
if self._config.PROPAGATE_REQUEST_ENABLED:
self._schedule(partial(self._request_propagates_if_needed, bad_reqs, pre_prepare),
self._config.PROPAGATE_REQUEST_DELAY)
elif why_not == PP_CHECK_NOT_NEXT:
pp_view_no = pre_prepare.viewNo
pp_seq_no = pre_prepare.ppSeqNo
_, last_pp_seq_no = self.__last_pp_3pc
if self.is_master or self.last_ordered_3pc[1] != 0:
seq_frm = last_pp_seq_no + 1
seq_to = pp_seq_no - 1
if seq_to >= seq_frm >= pp_seq_no - self._config.CHK_FREQ + 1:
logger.warning(
"{} missing PRE-PREPAREs from {} to {}, "
"going to request".format(self, seq_frm, seq_to))
self._request_missing_three_phase_messages(
pp_view_no, seq_frm, seq_to)
self._enqueue_pre_prepare(pre_prepare, sender)
self.l_setup_last_ordered_for_non_master()
elif why_not == PP_CHECK_WRONG_TIME:
key = (pre_prepare.viewNo, pre_prepare.ppSeqNo)
item = (pre_prepare, sender, False)
self.pre_prepares_stashed_for_incorrect_time[key] = item
report_suspicious(Suspicions.PPR_TIME_WRONG)
elif why_not == BlsBftReplica.PPR_BLS_MULTISIG_WRONG:
report_suspicious(Suspicions.PPR_BLS_MULTISIG_WRONG)
else:
logger.warning("Unknown PRE-PREPARE check status: {}".format(why_not))
return None, None
@property
def view_no(self):
return self._data.view_no
@property
def sent_preprepares(self):
return self._data.sent_preprepares
@property
def prepares(self):
return self._data.prepares
@property
def commits(self):
return self._data.commits
@property
def requested_pre_prepares(self):
return self._data.requested_pre_prepares
@property
def last_ordered_3pc(self):
return self._data.last_ordered_3pc
@last_ordered_3pc.setter
def last_ordered_3pc(self, lo_tuple):
self._data.last_ordered_3pc = lo_tuple
pp_seq_no = lo_tuple[1]
if pp_seq_no > self.lastPrePrepareSeqNo:
self.lastPrePrepareSeqNo = pp_seq_no
logger.info('{} set last ordered as {}'.format(self, lo_tuple))
@property
def last_preprepare(self):
last_3pc = (0, 0)
lastPp = None
if self.sent_preprepares:
(v, s), pp = self.sent_preprepares.peekitem(-1)
last_3pc = (v, s)
lastPp = pp
if self.prePrepares:
(v, s), pp = self.prePrepares.peekitem(-1)
if compare_3PC_keys(last_3pc, (v, s)) > 0:
lastPp = pp
return lastPp
@property
def __last_pp_3pc(self):
last_pp = self.last_preprepare
if not last_pp:
return self.last_ordered_3pc
last_3pc = (last_pp.viewNo, last_pp.ppSeqNo)
if compare_3PC_keys(self.last_ordered_3pc, last_3pc) > 0:
return last_3pc
return self.last_ordered_3pc
@property
def db_manager(self):
return self._write_manager.database_manager
@property
def is_master(self):
return self._data.is_master
@property
def primary_name(self):
"""
Name of the primary replica of this replica's instance
:return: Returns name if primary is known, None otherwise
"""
return self._data.primary_name
@property
def name(self):
return self._data.name
@name.setter
def name(self, n):
self._data._name = n
@property
def f(self):
return getMaxFailures(self._data.total_nodes)
def gc(self, till3PCKey):
logger.info("{} cleaning up till {}".format(self, till3PCKey))
tpcKeys = set()
reqKeys = set()
for key3PC, pp in itertools.chain(
self.sent_preprepares.items(),
self.prePrepares.items()
):
if compare_3PC_keys(till3PCKey, key3PC) <= 0:
tpcKeys.add(key3PC)
for reqKey in pp.reqIdr:
reqKeys.add(reqKey)
for key3PC, pp_dict in self.pre_prepare_tss.items():
if compare_3PC_keys(till3PCKey, key3PC) <= 0:
tpcKeys.add(key3PC)
# TODO INDY-1983: was found that it adds additional
# requests to clean, need to explore why
# for (pp, _) in pp_dict:
# for reqKey in pp.reqIdr:
# reqKeys.add(reqKey)
logger.trace("{} found {} 3-phase keys to clean".
format(self, len(tpcKeys)))
logger.trace("{} found {} request keys to clean".
format(self, len(reqKeys)))
self.old_view_preprepares = {k: v for k, v in self.old_view_preprepares.items()
if compare_3PC_keys(till3PCKey, (k[0], k[1])) > 0}
to_clean_up = (
self.pre_prepare_tss,
self.sent_preprepares,
self.prePrepares,
self.prepares,
self.commits,
self.batches,
self.pre_prepares_stashed_for_incorrect_time,
)
for request_key in tpcKeys:
pp = self.get_preprepare(*request_key)
if pp:
self._clear_batch(self.get_preprepare(*request_key))
for coll in to_clean_up:
coll.pop(request_key, None)
for request_key in reqKeys:
self._requests.ordered_by_replica(request_key)
self._requests.free(request_key)
for ledger_id, keys in self.requestQueues.items():
if request_key in keys:
self.discard_req_key(ledger_id, request_key)
logger.trace('{} freed request {} from previous checkpoints'.format(self, request_key))
# ToDo: do we need ordered messages there?
self.ordered.clear_below_view(self.view_no - 1)
# BLS multi-sig:
self.l_bls_bft_replica.gc(till3PCKey)
def discard_req_key(self, ledger_id, req_key):
self.requestQueues[ledger_id].discard(req_key)
def _clear_prev_view_pre_prepares(self):
to_remove = []
for idx, (pp, _, _) in enumerate(self.prePreparesPendingFinReqs):
if pp.viewNo < self.view_no:
to_remove.insert(0, idx)
for idx in to_remove:
self.prePreparesPendingFinReqs.pop(idx)
for (v, p) in list(self.prePreparesPendingPrevPP.keys()):
if v < self.view_no:
self.prePreparesPendingPrevPP.pop((v, p))
def report_suspicious_node(self, ex: SuspiciousNode):
logger.debug("{} raised suspicion on node {} for {}; suspicion code "
"is {}".format(self, ex.node, ex.reason, ex.code))
self._bus.send(RaisedSuspicion(inst_id=self._data.inst_id,
ex=ex))
def _validate(self, msg):
return self._validator.validate(msg)
def _can_process_pre_prepare(self, pre_prepare: PrePrepare, sender: str):
"""
Decide whether this replica is eligible to process a PRE-PREPARE.
:param pre_prepare: a PRE-PREPARE msg to process
:param sender: the name of the node that sent the PRE-PREPARE msg
"""
if self._validator.has_already_ordered(pre_prepare.viewNo, pre_prepare.ppSeqNo):
return None
digest = self.generate_pp_digest(pre_prepare.reqIdr,
get_original_viewno(pre_prepare),
pre_prepare.ppTime)
if digest != pre_prepare.digest:
return PP_APPLY_WRONG_DIGEST
# PRE-PREPARE should not be sent from non primary
if not self._is_msg_from_primary(pre_prepare, sender):
return PP_CHECK_NOT_FROM_PRIMARY
# Already has a PRE-PREPARE with same 3 phase key
if (pre_prepare.viewNo, pre_prepare.ppSeqNo) in self.prePrepares:
return PP_CHECK_DUPLICATE
if not self._is_pre_prepare_time_acceptable(pre_prepare, sender):
return PP_CHECK_WRONG_TIME
if compare_3PC_keys((pre_prepare.viewNo, pre_prepare.ppSeqNo),
self.__last_pp_3pc) > 0:
return PP_CHECK_OLD # ignore old pre-prepare
if self._non_finalised_reqs(pre_prepare.reqIdr):
return PP_CHECK_REQUEST_NOT_FINALIZED
if not self._is_next_pre_prepare(pre_prepare.viewNo,
pre_prepare.ppSeqNo):
return PP_CHECK_NOT_NEXT
if f.POOL_STATE_ROOT_HASH.nm in pre_prepare and \
pre_prepare.poolStateRootHash != self.get_state_root_hash(POOL_LEDGER_ID):
return PP_CHECK_INCORRECT_POOL_STATE_ROOT
# BLS multi-sig:
status = self.l_bls_bft_replica.validate_pre_prepare(pre_prepare,
sender)
if status is not None:
return status
return None
def _schedule(self, func, delay):
self._timer.schedule(delay, func)
def _process_valid_preprepare(self, pre_prepare: PrePrepare, sender: str):
why_not_applied = None
# apply and validate applied PrePrepare if it's not odered yet
if not self._validator.has_already_ordered(pre_prepare.viewNo, pre_prepare.ppSeqNo):
why_not_applied = self._apply_and_validate_applied_pre_prepare(pre_prepare, sender)
if why_not_applied is not None:
return why_not_applied
# add to PrePrepares
if self._data.is_primary:
self._add_to_sent_pre_prepares(pre_prepare)
else:
self._add_to_pre_prepares(pre_prepare)
# we may have stashed Prepares and Commits if this is PrePrepare from old view (re-ordering phase)
self._dequeue_prepares(pre_prepare.viewNo, pre_prepare.ppSeqNo)
self._dequeue_commits(pre_prepare.viewNo, pre_prepare.ppSeqNo)
return None
def _apply_and_validate_applied_pre_prepare(self, pre_prepare: PrePrepare, sender: str):
self.first_batch_after_catchup = False
old_state_root = self.get_state_root_hash(pre_prepare.ledgerId, to_str=False)
old_txn_root = self.get_txn_root_hash(pre_prepare.ledgerId)
if self.is_master:
logger.debug('{} state root before processing {} is {}, {}'.format(
self,
pre_prepare,
old_state_root,
old_txn_root))
# 1. APPLY
reqs, invalid_indices, rejects, suspicious = self._apply_pre_prepare(pre_prepare)
# 2. CHECK IF MORE CHUNKS NEED TO BE APPLIED FURTHER BEFORE VALIDATION
if pre_prepare.sub_seq_no != 0:
return PP_SUB_SEQ_NO_WRONG
if not pre_prepare.final:
return PP_NOT_FINAL
# 3. VALIDATE APPLIED
invalid_from_pp = invalid_index_serializer.deserialize(pre_prepare.discarded)
if suspicious:
why_not_applied = PP_REQUEST_ALREADY_ORDERED
else:
why_not_applied = self._validate_applied_pre_prepare(pre_prepare,
invalid_indices, invalid_from_pp)
# 4. IF NOT VALID AFTER APPLYING - REVERT
if why_not_applied is not None:
if self.is_master:
self._revert(pre_prepare.ledgerId,
old_state_root,
len(pre_prepare.reqIdr) - len(invalid_indices))
return why_not_applied
# 5. TRACK APPLIED
if rejects:
for reject in rejects:
self._network.send(reject)
if self.is_master:
# BLS multi-sig:
self.l_bls_bft_replica.process_pre_prepare(pre_prepare, sender)
logger.trace("{} saved shared multi signature for root".format(self, old_state_root))
if not self.is_master:
self.db_manager.get_store(LAST_SENT_PP_STORE_LABEL).store_last_sent_pp_seq_no(
self._data.inst_id, pre_prepare.ppSeqNo)
self._track_batches(pre_prepare, old_state_root)
key = (pre_prepare.viewNo, pre_prepare.ppSeqNo)
logger.debug("{} processed incoming PRE-PREPARE{}".format(self, key),
extra={"tags": ["processing"]})
return None
def _enqueue_pre_prepare(self, pre_prepare: PrePrepare, sender: str,
nonFinReqs: Set = None):
if nonFinReqs:
logger.info("{} - Queueing pre-prepares due to unavailability of finalised "
"requests. PrePrepare {} from {}".format(self, pre_prepare, sender))
self.prePreparesPendingFinReqs.append((pre_prepare, sender, nonFinReqs))
else:
# Possible exploit, an malicious party can send an invalid
# pre-prepare and over-write the correct one?
logger.info("Queueing pre-prepares due to unavailability of previous pre-prepares. {} from {}".
format(pre_prepare, sender))
self.prePreparesPendingPrevPP[pre_prepare.viewNo, pre_prepare.ppSeqNo] = (pre_prepare, sender)
def _request_propagates_if_needed(self, bad_reqs: list, pre_prepare: PrePrepare):
if any(pre_prepare is pended[0] for pended in self.prePreparesPendingFinReqs):
self._bus.send(RequestPropagates(bad_reqs))
def _request_missing_three_phase_messages(self, view_no: int, seq_frm: int, seq_to: int) -> None:
for pp_seq_no in range(seq_frm, seq_to + 1):
key = (view_no, pp_seq_no)
self._request_pre_prepare(key)
self._request_prepare(key)
self._request_commit(key)
def _request_three_phase_msg(self, three_pc_key: Tuple[int, int],
msg_type: str,
recipients: Optional[List[str]] = None,
stash_data: Optional[Tuple[str, str, str]] = None):
self._bus.send(MissingMessage(msg_type,
three_pc_key,
self._data.inst_id,
recipients,
stash_data))
def _request_pre_prepare(self, three_pc_key: Tuple[int, int],
stash_data: Optional[Tuple[str, str, str]] = None):
"""
Request preprepare
"""
if not self._config.PRE_PREPARE_REQUEST_ENABLED:
return
recipients = [replica_name_to_node_name(self.primary_name)]
self._request_three_phase_msg(three_pc_key,
PREPREPARE,
recipients,
stash_data)
def _request_prepare(self, three_pc_key: Tuple[int, int],
recipients: List[str] = None,
stash_data: Optional[Tuple[str, str, str]] = None):
"""
Request preprepare
"""