summaryrefslogtreecommitdiff
path: root/agreement/events.go
blob: afcfa3052d64cd4960502624eecb7a7592b22193 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
// Copyright (C) 2019-2023 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand.  If not, see <https://www.gnu.org/licenses/>.

package agreement

import (
	"fmt"
	"time"

	"github.com/algorand/go-algorand/logging"
	"github.com/algorand/go-algorand/protocol"
)

// An event represents the communication of an event to a state machine.
//
// The eventType of the event corresponds to its semantics.  Metadata associated
// with an event is returned in the struct that implements the event interface.
type event interface {
	// t returns the eventType associated with the event.
	t() eventType

	// String returns a string description of an event.
	String() string

	// ComparableStr returns a comparable string description of an event
	// for testing purposes.
	ComparableStr() string
}

// A ConsensusVersionView is a view of the consensus version as read from a
// LedgerReader, associated with some round.
type ConsensusVersionView struct {
	_struct struct{} `codec:","`

	Err     *serializableError
	Version protocol.ConsensusVersion
}

// An externalEvent represents an event delivered to the top-level state machine.
//
// External events are associated with a round and a view of consensus version
// on that round.
type externalEvent interface {
	event

	// ConsensusRound is the round related to this event.
	ConsensusRound() round

	// AttachConsensusVersion returns a copy of this externalEvent with a
	// ConsensusVersion attached.
	AttachConsensusVersion(v ConsensusVersionView) externalEvent
}

// An eventType identifies the particular type of event emitted.
//
// The eventType is distinct from the Go event struct which implements the event
// interface.  The semantics of an event depends on the eventType and not on the
// type of the implementing struct.
//
//go:generate stringer -type=eventType
type eventType uint8

const (
	// none is returned by state machines which have no event to return
	// otherwise.
	none eventType = iota

	// Some events originate from input sources to the agreement service.
	// These events are serialized via the demultiplexer.

	// votePresent, payloadPresent, and bundlePresent are emitted by the
	// network as input to the player state machine as messages are
	// received by the network.
	//
	// These events contain the unverfied version of the message object
	// itself as well as the MessageHandle tag.
	votePresent
	payloadPresent
	bundlePresent

	// voteVerified, payloadVerified, and bundleVerified are emitted by the
	// cryptoVerifier as input to the player state machine as cryptographic
	// verification completes for messages.
	//
	// These events contain the original unverified version of the message
	// object and the MessageHandle tag associated with the message when
	// first received.
	//
	// If verification has succeeded, these events also contain the verified
	// version of the message object, and their Err field is set to nil.  If
	// verification has failed, these events instead set the Err field with
	// the reason that verification failed.
	voteVerified
	payloadVerified
	bundleVerified

	// roundInterruption is emitted by the Ledger as input to the player
	// state machine when an external source observes that the player's
	// current round has completed concurrent with the player's operation.
	// roundInterruption is also emitted (internally, by the player itself) after
	// calling ensureBlock.
	roundInterruption

	// timeout is emitted by the Clock as input to the player state machine
	// as the system observes that a timeout has been reached.
	//
	// The duration of the timeout is the one specified in player.Deadline.
	// This duration is expressed as an offset from the start of the current
	// period.
	//
	// fastTimeout is like timeout but for fast partition recovery.
	timeout
	fastTimeout

	// Other events are delivered from one state machine to another to
	// communicate some message or as a reply to some message.  These events
	// are internally dispatched via the router.

	// softThreshold, certThreshold, and nextThreshold are emitted by vote
	// state machines as they observe that a threshold of votes have been
	// met for a given step.
	//
	// These events may tell the player state machine to change their round,
	// their period, or possibly to send a cert vote.  These events are also
	// delivered to the proposal state machines to ensure that the correct
	// block is staged and relayed.
	softThreshold
	certThreshold
	nextThreshold

	// proposalCommittable is returned by the proposal state machines when a
	// proposal-value is observed to be committable (e.g., it is possible
	// that a certificate has formed for that proposal-value.
	proposalCommittable

	// proposalAccepted is returned by the proposal state machines when a
	// proposal-value is accepted.
	proposalAccepted

	// voteFiltered and voteMalformed are returned by the voteMachine and
	// the proposalMachine when a vote is invalid because it is corrupt
	// (voteMalformed) or irrelevant (voteFiltered).
	voteFiltered
	voteMalformed

	// bundleFiltered and bundleMalformed are returned by the voteMachine
	// when a bundle is invalid because it is corrupt (bundleMalformed) or
	// irrelevant (bundleFiltered).
	bundleFiltered
	bundleMalformed

	// payloadRejected and payloadMalformed are returned by the
	// proposalMachine when a proposal payload is invalid because it is
	// corrupt (payloadMalformed) or irrelevant (payloadRejected).
	payloadRejected
	payloadMalformed

	// payloadPipelined and payloadAccepted are returned by a proposal state
	// machine when either an unauthenticated (payloadPipelined) or an
	// authenticated (payloadAccepted) proposal payload is accepted and
	// stored.
	payloadPipelined
	payloadAccepted

	// proposalFrozen is sent between the player and proposal state machines
	// to specify that the proposal-vote with the lowest credential should
	// be fixed.
	proposalFrozen

	// voteAccepted is delivered from the voteMachine to its children after
	// a relevant vote has been validated.
	voteAccepted

	// newRound and newPeriod are delivered from the proposalMachine to
	// their children when a new round or period is observed.
	newRound
	newPeriod

	// readStaging is sent to the proposalPeriodMachine to read the staging
	// value for that period, if it exists.  It is returned by this machine
	// with the response.
	readStaging

	// readPinned is sent to the proposalStore to read the pinned value, if it exists.
	readPinned

	// readLowestVote is sent to the proposalPeriodMachine to read the
	// proposal-vote with the lowest credential.
	readLowestVote

	/*
	 * The following are event types that replace queries, and may warrant
	 * a revision to make them more state-machine-esque.
	 */

	// voteFilterRequest is an internal event emitted by vote aggregator and
	// the proposal manager to the vote step machines and the proposal period
	// machines respectively to check for duplicate votes. They enable the emission
	// of voteFilteredStep events.
	voteFilterRequest
	voteFilteredStep

	// nextThresholdStatusRequest is an internal event handled by voteMachinePeriod
	// that generates a corresponding nextThresholdStatus tracking whether the period
	// has seen none, a bot threshold, a value threshold, or both thresholds.
	nextThresholdStatusRequest
	nextThresholdStatus

	// freshestBundleRequest is an internal event handled by voteMachineRound that
	// generates a corresponding freshestBundle event.
	freshestBundleRequest
	freshestBundle

	// dumpVotesRequest is an internal event handled by voteTracker that generates
	// a corresponding dumpVotes event.
	dumpVotesRequest
	dumpVotes

	// For testing purposes only
	wrappedAction

	// checkpointReached indicates that we've completly persisted the agreement state to disk.
	// it's invoked by the end of the persistence loop on either success or failuire.
	checkpointReached
)

type emptyEvent struct{}

func (e emptyEvent) t() eventType {
	return none
}

func (e emptyEvent) String() string {
	return e.t().String()
}

func (e emptyEvent) ComparableStr() string {
	return e.String()
}

func (e emptyEvent) ConsensusRound() round {
	return 0
}

func (e emptyEvent) AttachConsensusVersion(v ConsensusVersionView) externalEvent {
	return e
}

type messageEvent struct {
	_struct struct{} `codec:","`
	// {vote,bundle,payload}{Present,Verified}
	T eventType

	// Input represents the message itself.
	Input message

	// Err is set if cryptographic verification was attempted and failed for
	// Input.
	Err *serializableError
	// TaskIndex is optionally set to track a message as it is processed
	// through cryptographic verification.
	TaskIndex uint64

	// Tail is an optionally-set field which specifies an unauthenticated
	// proposal which should be processed after Input is processed.  Tail is
	// used to schedule processing proposal payloads after a matching
	// proposal-vote.
	Tail *messageEvent
	// Tail *unauthenticatedProposal

	// whether the corresponding request was cancelled
	Cancelled bool

	Proto ConsensusVersionView
}

func (e messageEvent) t() eventType {
	return e.T
}

func (e messageEvent) String() string {
	return fmt.Sprintf("{T:%s Err:%v}", e.t().String(), e.Err)
}

func (e messageEvent) ComparableStr() string {
	return fmt.Sprintf("{T:%s %d Err:%v}", e.t().String(), e.ConsensusRound(), e.Err)
}

func (e messageEvent) ConsensusRound() round {
	switch e.T {
	case votePresent, voteVerified:
		return e.Input.UnauthenticatedVote.R.Round
	case payloadPresent, payloadVerified:
		return e.Input.UnauthenticatedProposal.Round()
	case bundlePresent, bundleVerified:
		return e.Input.UnauthenticatedBundle.Round
	default:
		return 0
	}
}

func (e messageEvent) AttachConsensusVersion(v ConsensusVersionView) externalEvent {
	e.Proto = v
	return e
}

// freshnessData is bundled with filterableMessageEvent
// to allow for delegated freshness computation
type freshnessData struct {
	_struct struct{} `codec:","`

	PlayerRound          round
	PlayerPeriod         period
	PlayerStep           step
	PlayerLastConcluding step
}

//msgp:ignore filterableMessageEvent
type filterableMessageEvent struct {
	messageEvent

	// bundle-in player data for freshness computation
	// we may want to rethink the SM structure here to avoid passing around state
	FreshnessData freshnessData
}

type roundInterruptionEvent struct {
	// Round holds the round the state machine should enter after processing
	// this event.
	Round round

	Proto ConsensusVersionView
}

func (e roundInterruptionEvent) t() eventType {
	return roundInterruption
}

func (e roundInterruptionEvent) String() string {
	return e.t().String()
}

func (e roundInterruptionEvent) ComparableStr() string {
	return e.String()
}

func (e roundInterruptionEvent) ConsensusRound() round {
	return e.Round
}

func (e roundInterruptionEvent) AttachConsensusVersion(v ConsensusVersionView) externalEvent {
	e.Proto = v
	return e
}

type timeoutEvent struct {
	// {timeout,fastTimeout}
	T eventType

	RandomEntropy uint64

	Round round
	Proto ConsensusVersionView
}

func (e timeoutEvent) t() eventType {
	return e.T
}

func (e timeoutEvent) String() string {
	return e.t().String()
}

func (e timeoutEvent) ComparableStr() string {
	return e.t().String()
}

func (e timeoutEvent) ConsensusRound() round {
	return e.Round
}

func (e timeoutEvent) AttachConsensusVersion(v ConsensusVersionView) externalEvent {
	e.Proto = v
	return e
}

type newRoundEvent struct{}

func (e newRoundEvent) t() eventType {
	return newRound
}

func (e newRoundEvent) String() string {
	return e.t().String()
}

func (e newRoundEvent) ComparableStr() string {
	return e.String()
}

type readLowestEvent struct {
	// T currently only supports readLowestVote
	T eventType

	// Round and Period are the round and period for which to query the
	// lowest-credential vote, value or payload.  This type of event is only
	// sent for reading the lowest period 0 credential, but the Period is here
	// anyway to route to the appropriate proposalMachinePeriod.
	Round  round
	Period period

	// Vote holds the lowest-credential vote.
	Vote vote
	// LowestIncludingLate holds the lowest-credential vote that was received, including
	// after Vote has been frozen.
	LowestIncludingLate vote

	// Filled and HasLowestIncludingLate indicates whether the Vote or LowestIncludingLate
	// fields are filled, respectively.
	Filled                 bool
	HasLowestIncludingLate bool
}

func (e readLowestEvent) t() eventType {
	return e.T
}

func (e readLowestEvent) String() string {
	return fmt.Sprintf("%s: %d %d", e.t().String(), e.Round, e.Period)
}

func (e readLowestEvent) ComparableStr() string {
	return e.String()
}

type newPeriodEvent struct {
	// Period holds the latest period relevant to the proposalRoundMachine.
	Period period
	// Proposal holds the proposal-value that the new period may want to
	// agree on.  It is used to update the pinned value.
	Proposal proposalValue
}

func (e newPeriodEvent) t() eventType {
	return newPeriod
}

func (e newPeriodEvent) String() string {
	return e.t().String()
}

func (e newPeriodEvent) ComparableStr() string {
	return fmt.Sprintf("%s: %d\t%.5s", e.t().String(), e.Period, e.Proposal.BlockDigest.String())
}

type voteAcceptedEvent struct {
	// Vote holds the vote accepted by the voteMachine.
	Vote vote

	// Proto is the consensus version corresponding to Vote.R.Round
	Proto protocol.ConsensusVersion
}

func (e voteAcceptedEvent) t() eventType {
	return voteAccepted
}

func (e voteAcceptedEvent) String() string {
	return fmt.Sprintf("%s: %d\t%.10s\t%.5s", e.t().String(), e.Vote.R.Step, e.Vote.R.Sender.String(), e.Vote.R.Proposal.BlockDigest.String())
}

func (e voteAcceptedEvent) ComparableStr() string {
	return e.String()
}

type proposalAcceptedEvent struct {
	// Round and Period are the round in which the proposal was accepted.
	Round  round
	Period period

	// Proposal is the proposal-value which was accepted.
	Proposal proposalValue

	// PayloadOk is true if a proposal payload which corresponds to the
	// proposal-value has already been received.  Payload holds the proposal
	// payload if this is the case.
	Payload   proposal
	PayloadOk bool
}

func (e proposalAcceptedEvent) t() eventType {
	return proposalAccepted
}

func (e proposalAcceptedEvent) String() string {
	return fmt.Sprintf("%v: %.5v", e.t().String(), e.Proposal.BlockDigest.String())
}

func (e proposalAcceptedEvent) ComparableStr() string {
	return e.String()
}

type proposalFrozenEvent struct {
	// Proposal is set to be the proposal-value which was frozen.
	Proposal proposalValue
}

func (e proposalFrozenEvent) t() eventType {
	return proposalFrozen
}

func (e proposalFrozenEvent) String() string {
	return e.t().String()
}

func (e proposalFrozenEvent) ComparableStr() string {
	return e.String()
}

type committableEvent struct {
	// Proposal is set to be the proposal-value which is committable.
	Proposal proposalValue

	// the proposal-vote that authenticated the payload (if one exists)
	Vote vote
}

func (e committableEvent) t() eventType {
	return proposalCommittable
}

func (e committableEvent) String() string {
	return e.t().String()
}

func (e committableEvent) ComparableStr() string {
	return e.String()
}

type payloadProcessedEvent struct {
	// payload{Rejected,Pipelined,Accepted}
	T eventType

	// Round is the round for which a payload has been pipelined or
	// accepted.
	Round round
	// Period is the period that is interested in this payload.
	// For reproposed payloads this may be different from the
	// original period in which the block was proposed.
	Period period
	// Pinned is set if this is a pinned payload.  If Pinned is set,
	// Period will be 0.
	Pinned bool

	// Proposal is the proposal-value that corresponds to the payload.
	Proposal proposalValue

	// UnauthenticatedPayload is the proposal payload which was pipelined by
	// proposal machine.
	UnauthenticatedPayload unauthenticatedProposal

	// Vote holds some proposal-vote that authenticated the payload, if one
	// exists.
	Vote vote

	// Err is set to be the reason the proposal payload was rejected in
	// payloadRejected.
	Err *serializableError
}

func (e payloadProcessedEvent) t() eventType {
	return e.T
}

func (e payloadProcessedEvent) String() string {
	if e.t() == payloadRejected {
		return fmt.Sprintf("%v: %v; %.5v", e.t().String(), e.Err, e.Proposal.BlockDigest.String())
	}
	return fmt.Sprintf("%v: %.5v", e.t().String(), e.Proposal.BlockDigest.String())
}

func (e payloadProcessedEvent) ComparableStr() string {
	return fmt.Sprintf("%v: %.5v", e.t().String(), e.Proposal.BlockDigest.String())
}

// LateCredentialTrackingEffect indicates the impact of a vote that was filtered (due to age)
// on the credential tracking system (in credentialArrivalHistory), for the purpose of tracking
// the time it took the best credential to arrive, even if it was late.
type LateCredentialTrackingEffect uint8

const (
	// NoLateCredentialTrackingImpact indicates the filtered event would have no impact on
	// the credential tracking mechanism.
	NoLateCredentialTrackingImpact LateCredentialTrackingEffect = iota

	// UnverifiedLateCredentialForTracking indicates the filtered event could impact
	// the credential tracking mechanism and more processing (validation) may be required.
	// It may be set by proposalManager when handling votePresent events.
	UnverifiedLateCredentialForTracking

	// VerifiedBetterLateCredentialForTracking indicates that the filtered event provides a new best
	// credential for its round.
	// It may be set by proposalManager when handling voteVerified events.
	VerifiedBetterLateCredentialForTracking
)

type filteredEvent struct {
	// {proposal,vote,bundle}{Filtered,Malformed}
	T eventType

	// LateCredentialTrackingNote indicates the impact of the filtered event on the
	// credential tracking machinery used for dynamically setting the filter
	// timeout.
	LateCredentialTrackingNote LateCredentialTrackingEffect

	// Err is the reason cryptographic verification failed and is set for
	// events {proposal,vote,bundle}Malformed.
	Err *serializableError
}

func (e filteredEvent) t() eventType {
	return e.T
}

func (e filteredEvent) String() string {
	return fmt.Sprintf("%v: %v", e.t().String(), e.Err)
}

func (e filteredEvent) ComparableStr() string {
	return e.t().String()
}

type stagingValueEvent struct {
	// Round and Period are the round and period of the staging value.
	Round  round
	Period period

	// Proposal holds the staging value itself.
	Proposal proposalValue
	// Payload holds the payload, if one exists (which is the case if Committable is set).
	Payload proposal
	// Committable is set if and only if the staging value is committable.
	Committable bool
}

func (e stagingValueEvent) t() eventType {
	return readStaging
}

func (e stagingValueEvent) String() string {
	return fmt.Sprintf("%v: %.5v", e.t().String(), e.Proposal.BlockDigest.String())
}

func (e stagingValueEvent) ComparableStr() string {
	return e.String()
}

type pinnedValueEvent struct {
	// Round is the round for which to query the current pinned value
	Round round

	// Proposal holds the pinned value itself.
	Proposal proposalValue
	// Payload holds the payload, if one exists (which is the case if PayloadOK is set).
	Payload proposal
	// PayloadOK is set if and only if a payload was received for the pinned value.
	PayloadOK bool
}

func (e pinnedValueEvent) t() eventType {
	return readPinned
}

func (e pinnedValueEvent) String() string {
	return fmt.Sprintf("%v: %.5v", e.t().String(), e.Proposal.BlockDigest.String())
}

func (e pinnedValueEvent) ComparableStr() string {
	return e.String()
}

type thresholdEvent struct {
	_struct struct{} `codec:","`
	// {{soft,cert,next}Threshold, none}
	T eventType

	// Round, Period, and Step describe the round, period, and step where
	// the threshold was reached.
	Round  round
	Period period
	Step   step

	// Proposal is the proposal-value for which the threshold was reached.
	Proposal proposalValue

	// Bundle holds a quorum of votes which form the threshold.
	Bundle unauthenticatedBundle

	Proto protocol.ConsensusVersion
}

func (e thresholdEvent) t() eventType {
	return e.T
}

func (e thresholdEvent) String() string {
	switch e.t() {
	case none:
		return e.t().String()
	default:
		return fmt.Sprintf("%v: %.5s", e.t().String(), e.Proposal.BlockDigest.String())
	}
}

func (e thresholdEvent) ComparableStr() string {
	return e.String()
}

// fresherThan produces a partial ordering on threshold events from the same
// round.
//
// The ordering is given as follows:
//
//   - certThreshold events are fresher than all other non-certThreshold events.
//   - Events from a later period are fresher than events from an older period.
//   - nextThreshold events are fresher than softThreshold events from the same
//     period.
//   - nextThreshold events for the bottom proposal-value are fresher than
//     nextThreshold events for some other value.
//
// Precondition: e.Round == o.Round if e.T != none and o.T != none
func (e thresholdEvent) fresherThan(o thresholdEvent) bool {
	if e.T == none && o.T == none {
		return true
	}

	if e.T == none {
		return false
	}

	if o.T == none {
		return true
	}

	if e.Round != o.Round {
		logging.Base().Panicf("round mismatch: %v != %v", e.Round, o.Round)
	}

	switch o.T {
	case softThreshold:
	case certThreshold:
	case nextThreshold:
	default:
		logging.Base().Panicf("bad event: %v", e.T)
	}
	switch e.T {
	case softThreshold:
	case certThreshold:
	case nextThreshold:
	default:
		logging.Base().Panicf("bad event: %v", e.T)
	}

	if o.T == certThreshold {
		return false
	}
	switch e.T {
	case softThreshold:
		return e.Period > o.Period
	case certThreshold:
		return true
	case nextThreshold:
		if e.Period > o.Period {
			return true
		}
		if e.Period < o.Period {
			return false
		}

		if o.T == softThreshold {
			return true
		}

		return e.Proposal == bottom && o.Proposal != bottom
	}
	logging.Base().Panicf("bad case: %v", e.T)
	return false
}

// zeroEvent creates a zeroed event of a given type
func zeroEvent(t eventType) event {
	switch t {
	case none:
		return emptyEvent{}
	case votePresent, voteVerified, payloadPresent, payloadVerified, bundlePresent, bundleVerified:
		return messageEvent{}
	case roundInterruption:
		return roundInterruptionEvent{}
	case timeout, fastTimeout:
		return timeoutEvent{}
	case newRound:
		return newRoundEvent{}
	case newPeriod:
		return newPeriodEvent{}
	case voteAccepted:
		return voteAcceptedEvent{}
	case proposalAccepted:
		return proposalAcceptedEvent{}
	case proposalFrozen:
		return proposalFrozenEvent{}
	case proposalCommittable:
		return committableEvent{}
	case payloadRejected, payloadPipelined, payloadAccepted:
		return payloadProcessedEvent{}
	case voteFiltered, bundleFiltered:
		return filteredEvent{}
	case softThreshold, certThreshold, nextThreshold:
		return thresholdEvent{}
	case checkpointReached:
		return checkpointEvent{}
	default:
		err := fmt.Errorf("bad event type: %v", t)
		panic(err)
	}
}

/* Former Query Events */

type voteFilterRequestEvent struct {
	RawVote rawVote
}

func (e voteFilterRequestEvent) t() eventType {
	return voteFilterRequest
}

func (e voteFilterRequestEvent) String() string {
	return fmt.Sprintf("%s: %d\t%.10s\t%.5s", e.t().String(), e.RawVote.Step, e.RawVote.Sender.String(), e.RawVote.Proposal.BlockDigest.String())
}

func (e voteFilterRequestEvent) ComparableStr() string {
	return e.String()
}

type filteredStepEvent struct {
	// voteFilteredStep
	T eventType
}

func (e filteredStepEvent) t() eventType {
	return e.T
}

func (e filteredStepEvent) String() string {
	return e.T.String()
}

func (e filteredStepEvent) ComparableStr() string {
	return e.String()
}

type nextThresholdStatusRequestEvent struct {
	// should be dispatched to the round, period in question, so no need to store that
}

func (e nextThresholdStatusRequestEvent) t() eventType {
	return nextThresholdStatusRequest
}

func (e nextThresholdStatusRequestEvent) String() string {
	return e.t().String()
}

func (e nextThresholdStatusRequestEvent) ComparableStr() string {
	return e.String()
}

type nextThresholdStatusEvent struct {
	_struct struct{} `codec:","`
	// the result of a nextThresholdStatusRequest. Contains two bits of information,
	// capturing four cases:
	// Bottom = false, Proposal = unset/bottom --> received no next value thresholds
	// Bottom = true, Proposal = unset/bottom --> received only a next-vote bottom threshold
	// Bottom = false, Proposal = val --> received a next value threshold
	// Bottom = true, Proposal = val --> received both thresholds.
	// In particular, the first case could occur despite already been in the subsequent period
	// IF we fast forwarded from a soft-vote bundle from the subsequent period.

	Bottom   bool          // true if saw a threshold for bottom
	Proposal proposalValue // set to not bottom if saw threshold for some proposal
}

func (e nextThresholdStatusEvent) t() eventType {
	return nextThresholdStatus
}

func (e nextThresholdStatusEvent) String() string {
	return e.t().String()
}

func (e nextThresholdStatusEvent) ComparableStr() string {
	return e.String()
}

type freshestBundleRequestEvent struct{}

func (e freshestBundleRequestEvent) t() eventType {
	return freshestBundleRequest
}

func (e freshestBundleRequestEvent) String() string {
	return e.t().String()
}

func (e freshestBundleRequestEvent) ComparableStr() string {
	return e.String()
}

type freshestBundleEvent struct {
	// Ok is set if any thresholdEvent was seen
	Ok bool
	// Event holds the freshest thresholdEvent seen by a round machine
	Event thresholdEvent
}

func (e freshestBundleEvent) t() eventType {
	return freshestBundle
}

func (e freshestBundleEvent) String() string {
	return fmt.Sprintf("%s: (%s)", e.t().String(), e.Event.String())
}

func (e freshestBundleEvent) ComparableStr() string {
	return e.String()
}

type dumpVotesRequestEvent struct{}

func (e dumpVotesRequestEvent) t() eventType {
	return dumpVotesRequest
}

func (e dumpVotesRequestEvent) String() string {
	return e.t().String()
}

func (e dumpVotesRequestEvent) ComparableStr() string {
	return e.String()
}

type dumpVotesEvent struct {
	Votes []unauthenticatedVote
}

func (e dumpVotesEvent) t() eventType {
	return dumpVotes
}

func (e dumpVotesEvent) String() string {
	return e.t().String()
}

func (e dumpVotesEvent) ComparableStr() string {
	return e.String()
}

type checkpointEvent struct {
	Round  round
	Period period
	Step   step
	Err    *serializableError // the error that was generated while storing the state to disk; nil on success.
	done   chan error         // an output channel to let the pseudonode that we're done processing. We don't want to serialize that, since it's not needed in recovery/autopsy.
}

func (e checkpointEvent) t() eventType {
	return checkpointReached
}

func (e checkpointEvent) String() string {
	return e.t().String()
}

func (e checkpointEvent) ComparableStr() string {
	return e.String()
}

func (e checkpointEvent) ConsensusRound() round {
	return 0
}

func (e checkpointEvent) AttachConsensusVersion(v ConsensusVersionView) externalEvent {
	return e
}

// This timestamp is assigned to messages that arrive for round R+1 while the current player
// is still waiting for quorum on R.
const pipelinedMessageTimestamp = time.Nanosecond

//msgp:ignore constantRoundStartTimer
type constantRoundStartTimer time.Duration

func (c constantRoundStartTimer) Since() time.Duration { return time.Duration(c) }

// clockForRound retrieves the roundStartTimer used for AttachValidatedAt and AttachReceivedAt.
func clockForRound(currentRound round, currentClock roundStartTimer, historicalClocks map[round]roundStartTimer) func(round) roundStartTimer {
	return func(eventRound round) roundStartTimer {
		if eventRound > currentRound {
			return constantRoundStartTimer(pipelinedMessageTimestamp)
		}
		if eventRound == currentRound {
			return currentClock
		}
		if clock, ok := historicalClocks[eventRound]; ok {
			return clock
		}
		return constantRoundStartTimer(0)
	}
}

// AttachValidatedAt looks for a validated proposal or vote inside a
// payloadVerified or voteVerified messageEvent, and attaches the given time to
// the proposal's validatedAt field.
func (e messageEvent) AttachValidatedAt(getClock func(eventRound round) roundStartTimer) messageEvent {
	switch e.T {
	case payloadVerified:
		e.Input.Proposal.validatedAt = getClock(e.Input.Proposal.Round()).Since()
	case voteVerified:
		e.Input.Vote.validatedAt = getClock(e.Input.Vote.R.Round).Since()
	}
	return e
}

// AttachReceivedAt looks for an unauthenticatedProposal inside a
// payloadPresent or votePresent messageEvent, and attaches the given
// time to the proposal's receivedAt field.
func (e messageEvent) AttachReceivedAt(getClock func(eventRound round) roundStartTimer) messageEvent {
	switch e.T {
	case payloadPresent:
		e.Input.UnauthenticatedProposal.receivedAt = getClock(e.Input.UnauthenticatedProposal.Round()).Since()
	case votePresent:
		// Check for non-nil Tail, indicating this votePresent event
		// contains a synthetic payloadPresent event that was attached
		// to it by setupCompoundMessage.
		if e.Tail != nil && e.Tail.T == payloadPresent {
			// The tail event is payloadPresent, serialized together
			// with the proposal vote as a single CompoundMessage
			// using a protocol.ProposalPayloadTag network message.
			e.Tail.Input.UnauthenticatedProposal.receivedAt = getClock(e.Tail.Input.UnauthenticatedProposal.Round()).Since()
		}
	}
	return e
}