forked from FactomProject/factomd
-
Notifications
You must be signed in to change notification settings - Fork 1
/
stateConsensus.go
2777 lines (2394 loc) · 91.8 KB
/
stateConsensus.go
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
// Copyright 2017 Factom Foundation
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.
package state
import (
"errors"
"fmt"
"hash"
"os"
"reflect"
"sort"
"time"
"github.com/FactomProject/factomd/common/constants"
"github.com/FactomProject/factomd/common/entryBlock"
"github.com/FactomProject/factomd/common/entryCreditBlock"
"github.com/FactomProject/factomd/common/factoid"
"github.com/FactomProject/factomd/common/globals"
"github.com/FactomProject/factomd/common/interfaces"
"github.com/FactomProject/factomd/common/messages"
"github.com/FactomProject/factomd/common/primitives"
"github.com/FactomProject/factomd/util"
"github.com/FactomProject/factomd/util/atomic"
log "github.com/sirupsen/logrus"
)
// consenLogger is the general logger for all consensus related logs. You can add additional fields,
// or create more context loggers off of this
var consenLogger = packageLogger.WithFields(log.Fields{"subpack": "consensus"})
var _ = fmt.Print
var _ = (*hash.Hash32)(nil)
//***************************************************************
// Process Loop for Consensus
//
// Returns true if some message was processed.
//***************************************************************
func (s *State) CheckFileName(name string) bool {
return messages.CheckFileName(name)
}
func (s *State) DebugExec() (ret bool) {
return globals.Params.DebugLogRegEx != ""
}
func (s *State) LogMessage(logName string, comment string, msg interfaces.IMsg) {
if s.DebugExec() {
if s == nil {
messages.StateLogMessage("unknown", 0, 0, logName, comment, msg)
} else {
messages.StateLogMessage(s.FactomNodeName, int(s.LLeaderHeight), int(s.CurrentMinute), logName, comment, msg)
}
}
}
func (s *State) LogPrintf(logName string, format string, more ...interface{}) {
if s.DebugExec() {
if s == nil {
messages.StateLogPrintf("unknown", 0, 0, logName, format, more...)
} else {
messages.StateLogPrintf(s.FactomNodeName, int(s.LLeaderHeight), int(s.CurrentMinute), logName, format, more...)
}
}
}
func (s *State) AddToHolding(hash [32]byte, msg interfaces.IMsg) {
if !constants.NeedsAck(msg.Type()) {
s.LogMessage("holding", "add non-ack'd", msg)
}
_, ok := s.Holding[hash]
if !ok {
s.Holding[hash] = msg
s.LogMessage("holding", "add", msg)
TotalHoldingQueueInputs.Inc()
}
}
func (s *State) DeleteFromHolding(hash [32]byte, msg interfaces.IMsg, reason string) {
_, ok := s.Holding[hash]
if ok {
delete(s.Holding, hash)
s.LogMessage("holding", "delete "+reason, msg)
TotalHoldingQueueOutputs.Inc()
}
s.Hold.RemoveDependentMsg(hash, reason)
}
var FilterTimeLimit = int64(Range * 60 * 2 * 1000000000) // Filter hold two hours of messages, one in the past one in the future
// this is the common validation to all messages. they must not be a reply, they must not be out size the time window
// for the replay filter.
func (s *State) Validate(msg interfaces.IMsg) (validToSend int, validToExec int) {
// check the time frame of messages with ACKs and reject any that are before the message filter time (before boot
// or outside the replay filter time frame)
defer func() {
s.LogMessage("msgvalidation", fmt.Sprintf("send=%d execute=%d local=%v %s", *(&validToSend), *(&validToExec), msg.IsLocal(), atomic.WhereAmIString(1)), msg)
}()
// During boot ignore messages that are more than 15 minutes old...
if s.IgnoreMissing && msg.Type() != constants.DBSTATE_MSG {
now := s.GetTimestamp().GetTimeSeconds()
if now-msg.GetTimestamp().GetTimeSeconds() > 60*15 {
s.LogMessage("executeMsg", "ignoreMissing", msg)
return -1, -1
}
}
// Pokemon bug protection. Ignore any msg without a valid GetMsgHash()
if msg.GetMsgHash() == nil || msg.GetHash() == nil || msg.GetRepeatHash() == nil {
return -1, -1
}
if constants.NeedsAck(msg.Type()) {
// Make sure we don't put in an old ack'd message (outside our repeat filter range)
filterTime := s.GetMessageFilterTimestamp().GetTime().UnixNano()
if filterTime == 0 {
panic("got 0 time")
}
msgtime := msg.GetTimestamp().GetTime().UnixNano()
// Make sure we don't put in an old msg (outside our repeat range)
{ // debug
if msgtime < filterTime || msgtime > (filterTime+FilterTimeLimit) {
s.LogPrintf("executeMsg", "MsgFilter %s", s.GetMessageFilterTimestamp().GetTime().String())
s.LogPrintf("executeMsg", "Leader %s", s.GetLeaderTimestamp().GetTime().String())
s.LogPrintf("executeMsg", "Message %s", msg.GetTimestamp().GetTime().String())
}
}
// messages before message filter timestamp it's an old message
if msgtime < filterTime {
s.LogMessage("executeMsg", "drop message, more than an hour in the past", msg)
return -1, -1 // Old messages are bad.
} else if msgtime > (filterTime + FilterTimeLimit) {
s.LogMessage("executeMsg", "hold message from the future", msg)
return 0, 0 // Far Future (>1H) stuff I can hold for now. It might be good later?
}
}
switch msg.Type() {
case constants.REVEAL_ENTRY_MSG, constants.COMMIT_ENTRY_MSG, constants.COMMIT_CHAIN_MSG:
if !s.NoEntryYet(msg.GetHash(), nil) {
s.LogMessage("executeMsg", "drop, already committed", msg)
return -1, -1
}
}
// Valid to send is a bit different from valid to execute. Check for valid to send here.
validToSend = msg.Validate(s)
if validToSend == 0 { // if the msg says hold then we hold...
return 0, 0
}
if validToSend == -1 { // if the msg says drop then we drop...
return -1, -1
}
if validToSend == -2 { // if the msg says New hold then we don't execute...
return 0, -2
}
if validToSend != 1 { // if the msg says anything other than valid
s.LogMessage("badEvents", fmt.Sprintf("Invalid validity code %d", validToSend), msg)
panic("unexpected validity code")
}
// if it is valid to send then we check other stuff ...
_, ok := s.Replay.Valid(constants.INTERNAL_REPLAY, msg.GetRepeatHash().Fixed(), msg.GetTimestamp(), s.GetTimestamp())
if !ok {
consenLogger.WithFields(msg.LogFields()).Debug("executeMsg (Replay Invalid)")
s.LogMessage("executeMsg", "drop, INTERNAL_REPLAY2", msg)
return -1, -1
}
// if its local and valid to send, then execute it.
if msg.IsLocal() {
return 1, 1
}
// only valid to send messages past here
msg.ComputeVMIndex(s)
vmIndex := msg.GetVMIndex()
// If we are not the leader, or this isn't the VM we are responsible for ...
if !s.Leader || (s.LeaderVMIndex != vmIndex) {
if constants.NeedsAck(msg.Type()) {
// don't need to check for a matching ack for ACKs or local messages
// for messages that get ACK make sure we can expect to process them
ack, _ := s.Acks[msg.GetMsgHash().Fixed()].(*messages.Ack)
if ack == nil {
s.LogPrintf("executeMsg", "LeaderVm = %d, msg vm = %d M-%x", s.LeaderVMIndex, vmIndex, msg.GetMsgHash().Bytes()[:3])
s.LogMessage("executeMsg", "hold, no ack yet", msg)
return 1, 0
}
pl := s.ProcessLists.Get(ack.DBHeight)
if pl == nil {
s.LogMessage("executeMsg", "hold, no process list yet", msg)
return 1, 0
}
}
}
return 1, 1
}
func (s *State) executeMsg(msg interfaces.IMsg) (ret bool) {
// track how long we spend in executeMsg
preExecuteMsgTime := time.Now()
defer func() {
executeMsgTime := time.Since(preExecuteMsgTime)
TotalExecuteMsgTime.Add(float64(executeMsgTime.Nanoseconds()))
}()
if s.executeRecursionDetection == nil {
s.executeRecursionDetection = make(map[[32]byte]interfaces.IMsg, 10)
}
repeatHash := msg.GetRepeatHash().Fixed()
{
// detect if we recurse with the same message we are currently executing
_, ok := s.executeRecursionDetection[repeatHash]
if ok {
s.LogMessage("executeMsg", "recursion detected for ", msg)
panic("executeMsg() recursed")
}
s.executeRecursionDetection[repeatHash] = msg
defer delete(s.executeRecursionDetection, repeatHash)
}
if msg.GetHash() == nil || reflect.ValueOf(msg.GetHash()).IsNil() {
s.LogMessage("badEvents", "Nil hash in executeMsg", msg)
return false
}
s.SetString()
msg.ComputeVMIndex(s)
validToSend, validToExecute := s.Validate(msg)
if validToSend == 1 {
msg.SendOut(s, msg)
}
switch validToExecute {
case 1:
switch msg.Type() {
case constants.REVEAL_ENTRY_MSG:
if !s.NoEntryYet(msg.GetHash(), nil) {
s.DeleteFromHolding(msg.GetMsgHash().Fixed(), msg, "AlreadyCommitted1") // delete reveal
s.Commits.Delete(msg.GetHash().Fixed())
s.LogMessage("executeMsg", "drop_reveal, already committed", msg)
return true
}
s.AddToHolding(msg.GetMsgHash().Fixed(), msg) // add valid commit/reveal to holding in case it fails to get added
case constants.COMMIT_ENTRY_MSG, constants.COMMIT_CHAIN_MSG:
if !s.NoEntryYet(msg.GetHash(), nil) {
s.DeleteFromHolding(msg.GetMsgHash().Fixed(), msg, "AlreadyCommitted2") // delete commit
s.DeleteFromHolding(msg.GetHash().Fixed(), msg, "AlreadyCommitted3") // delete reveal
s.Commits.Delete(msg.GetHash().Fixed())
s.LogMessage("executeMsg", "drop_commit, already committed", msg)
return true
}
s.AddToHolding(msg.GetMsgHash().Fixed(), msg) // add valid commit/reveal to holding in case it fails to get added
}
var vm *VM = nil
if s.Leader && s.RunLeader {
vm = s.LeaderPL.VMs[s.LeaderVMIndex]
}
var vml int = 0
var vmh int = 0
var vms bool = false
if vm != nil {
vms = vm.Synced
vmh = int(vm.Height)
if vm.List != nil {
vml = len(vm.List)
}
}
local := msg.IsLocal()
vmi := msg.GetVMIndex()
hkb := s.GetHighestKnownBlock()
if s.RunLeader &&
s.Leader &&
!s.Saving && // if not between blocks
vm != nil && vmh == vml && // if we have processed to the end of the process list
(!s.Syncing || !vms) && // if not syncing or this VM is not yet synced
(local || vmi == s.LeaderVMIndex) && // if it's a local message or it a message for our VM
s.LeaderPL.DBHeight+1 >= hkb {
if vml == 0 { // if we have not generated a DBSig ...
s.SendDBSig(s.LLeaderHeight, s.LeaderVMIndex) // ExecuteMsg()
TotalXReviewQueueInputs.Inc()
s.XReview = append(s.XReview, msg)
s.LogMessage("executeMsg", "Missing DBSig use XReview", msg)
} else {
s.LogMessage("executeMsg", fmt.Sprintf("LeaderExecute[%d]", s.LeaderVMIndex), msg)
msg.LeaderExecute(s)
}
} else {
s.LogMessage("executeMsg", fmt.Sprintf("FollowerExecute[%d]", s.LeaderVMIndex), msg)
if s.Leader {
s.LogPrintf("executeMsg", "cause:"+
" s.RunLeader(%v) && s.Leader(%v) && !s.Saving(%v) && vm(%p) != nil && vmh(%v) == vml(%v) && "+
"(!s.Syncing(%v) || !vms(%v)) && (local(%v) || vmi(%v) == s.LeaderVMIndex(%v)) && "+
"s.LeaderPL.DBHeight(%v)+1 >= hkb(%v)",
s.RunLeader, s.Leader, s.Saving, vm, vmh, vml, s.Syncing, vms, local, vmi, s.LeaderVMIndex, s.LeaderPL.DBHeight, hkb)
}
msg.FollowerExecute(s)
}
return true
case 0:
// Sometimes messages we have already processed are in the msgQueue from holding when we execute them
// this check makes sure we don't put them back in holding after just deleting them
s.LogMessage("executeMsg", "hold executeMsg", msg)
s.AddToHolding(msg.GetMsgHash().Fixed(), msg) // Add message where validToExecute==0
return false
case -2:
s.LogMessage("executeMsg", "dependent_hold executeMsg", msg)
return false
default:
s.DeleteFromHolding(msg.GetMsgHash().Fixed(), msg, "InvalidMsg") // delete commit
if !msg.SentInvalid() {
msg.MarkSentInvalid(true)
s.networkInvalidMsgQueue <- msg
}
return true
}
}
func (s *State) Process() (progress bool) {
if ValidationDebug {
s.LogPrintf("executeMsg", "start State.Process() msgs=%d acks=%d in=%d in2=%d", len(s.msgQueue), len(s.ackQueue), s.inMsgQueue.Length(), s.inMsgQueue2.Length())
defer s.LogPrintf("executeMsg", "end State.Process() %v", *&progress)
}
s.StateProcessCnt++
if s.ResetRequest {
s.ResetRequest = false
s.DoReset()
return false
}
LeaderPL := s.ProcessLists.Get(s.LLeaderHeight)
if s.LeaderPL != LeaderPL {
s.LogPrintf("ExecuteMsg", "Process: Unexpected change in LeaderPL")
s.LeaderPL = LeaderPL
}
now := s.GetTimestamp().GetTimeMilli() // Timestamps are in milliseconds, so wait 20
// If we are not running the leader, then look to see if we have waited long enough to
// start running the leader. If we are, start the clock on Ignoring Missing Messages. This
// is so we don't conflict with past version of the network if we have to reboot the network.
var Leader bool
var LeaderVMIndex int
if s.CurrentMinute > 9 {
Leader, LeaderVMIndex = s.LeaderPL.GetVirtualServers(9, s.IdentityChainID)
} else {
Leader, LeaderVMIndex = s.LeaderPL.GetVirtualServers(s.CurrentMinute, s.IdentityChainID)
}
if s.LLeaderHeight != 0 { // debug
if s.Leader != Leader {
s.LogPrintf("executeMsg", "State.Process() unexpectedly setting s.Leader to %v", Leader)
}
if s.LeaderVMIndex != LeaderVMIndex {
s.LogPrintf("executeMsg", "State.Process() unexpectedly setting s.LeaderVMIndex to %v", LeaderVMIndex)
}
}
// gotta set them here for the first initialization, maybe ought to call movetoheight()? but not here...
s.Leader = Leader
s.LeaderVMIndex = LeaderVMIndex
if !s.RunLeader {
if now-s.StartDelay > s.StartDelayLimit {
if s.DBFinished == true {
s.RunLeader = true
if !s.IgnoreDone {
s.StartDelay = now // Reset StartDelay for Ignore Missing
s.IgnoreDone = true
}
}
}
} else if s.IgnoreMissing {
if now-s.StartDelay > s.StartDelayLimit {
s.IgnoreMissing = false
}
}
process := []interfaces.IMsg{}
hsb := s.GetHighestSavedBlk()
// trim any received DBStatesReceived messages that are fully processed
completed := s.GetHighestLockedSignedAndSavesBlk()
cut := int(completed) - s.DBStatesReceivedBase
if cut > 0 {
s.LogPrintf("dbstateprocess", "Cut %d (%d to %d) from DBStatesReceived", cut, s.DBStatesReceivedBase, s.DBStatesReceivedBase+cut-1)
if cut >= len(s.DBStatesReceived) {
s.DBStatesReceived = s.DBStatesReceived[:0]
s.DBStatesReceivedBase = int(hsb + 1)
} else {
s.DBStatesReceived = append(make([]*messages.DBStateMsg, 0), s.DBStatesReceived[cut:]...)
s.DBStatesReceivedBase += cut
}
}
/** Process all the DBStatesReceived that might be pending **/
if len(s.DBStatesReceived) > 0 {
for {
hsb := s.GetHighestSavedBlk()
// Get the index of the next DBState
ix := int(hsb) - s.DBStatesReceivedBase + 1
// Make sure we are in range
if ix < 0 || ix >= len(s.DBStatesReceived) {
break // We have nothing for the system, given its current height.
}
if msg := s.DBStatesReceived[ix]; msg != nil {
ret := s.executeMsg(msg)
s.LogPrintf("dbstateprocess", "Trying to process DBStatesReceived %d, %t", s.DBStatesReceivedBase+ix, ret)
}
// if we can not process a DBStatesReceived then go process some messages
if hsb == s.GetHighestSavedBlk() {
break
}
}
}
// Process inbound messages
preEmptyLoopTime := time.Now()
emptyLoop:
for i := 0; i < 100; i++ {
var msg interfaces.IMsg
select {
// We have prioritizedMsgQueue listed twice, meaning it has 2 chances to be
// randomly selected to unblock and execute.
case msg = <-s.prioritizedMsgQueue:
s.LogMessage("prioritizedMsgQueue", "Execute", msg)
case msg = <-s.prioritizedMsgQueue:
s.LogMessage("prioritizedMsgQueue", "Execute", msg)
case msg = <-s.msgQueue:
s.LogMessage("msgQueue", "Execute", msg)
case msg = <-s.ackQueue:
s.LogMessage("ackQueue", "Execute", msg)
case msg = <-s.ackQueue:
s.LogMessage("ackQueue", "Execute", msg)
case msg = <-s.ackQueue:
s.LogMessage("ackQueue", "Execute", msg)
default:
break emptyLoop
}
progress = s.executeMsg(msg) || progress
}
emptyLoopTime := time.Since(preEmptyLoopTime)
TotalEmptyLoopTime.Add(float64(emptyLoopTime.Nanoseconds()))
preProcessXReviewTime := time.Now()
// Reprocess any stalled messages, but not so much compared inbound messages
// Process last first
// Check for Ack'd items in holding
func() {
count := 0
if ValidationDebug {
s.LogPrintf("executeMsg", "Start reviewAcks")
defer s.LogPrintf("executeMsg", "end reviewAcks executed %d", count)
}
for _, a := range s.Acks {
if s.Holding[a.GetHash().Fixed()] != nil {
a.FollowerExecute(s)
count++
}
}
}()
// only review holding if I am a leader
if s.RunLeader && s.Leader {
s.ReviewHolding()
for _, msg := range s.XReview {
if msg == nil {
continue
}
// copy the messages we are responsible for and all msg that don't need ack
// messages that need ack will get processed when thier ack arrives
if msg.GetVMIndex() == s.LeaderVMIndex || !constants.NeedsAck(msg.Type()) {
process = append(process, msg)
}
}
// toss everything else
s.XReview = s.XReview[:0]
}
if ValidationDebug {
s.LogPrintf("executeMsg", "end reviewHolding %d", len(s.XReview))
}
processXReviewTime := time.Since(preProcessXReviewTime)
TotalProcessXReviewTime.Add(float64(processXReviewTime.Nanoseconds()))
if len(process) != 0 {
preProcessProcChanTime := time.Now()
if ValidationDebug {
s.LogPrintf("executeMsg", "Start processloop %d", len(process))
}
for _, msg := range process {
newProgress := s.executeMsg(msg)
if ValidationDebug && newProgress {
s.LogMessage("executeMsg", "progress set by ", msg)
}
progress = newProgress || progress //
s.LogMessage("executeMsg", "From process", msg)
s.UpdateState()
} // processLoop for{...}
if ValidationDebug {
s.LogPrintf("executeMsg", "end processloop")
}
processProcChanTime := time.Since(preProcessProcChanTime)
TotalProcessProcChanTime.Add(float64(processProcChanTime.Nanoseconds()))
}
return
}
//***************************************************************
// Checkpoint DBKeyMR
//***************************************************************
func CheckDBKeyMR(s *State, ht uint32, hash string) error {
if s.Network != "MAIN" && s.Network != "main" {
return nil
}
if val, ok := constants.CheckPoints[ht]; ok {
if val != hash {
return fmt.Errorf("%20s CheckPoints at %d DB height failed\n", s.FactomNodeName, ht)
}
}
return nil
}
//***************************************************************
// Consensus Methods
//***************************************************************
func (s *State) ExpireHolding() {
highest := s.GetHighestKnownBlock()
saved := s.GetHighestSavedBlk()
if saved > highest {
highest = saved + 1
}
for _, v := range s.Holding {
if v.Expire(s) {
s.ExpireCnt++
s.DeleteFromHolding(v.GetMsgHash().Fixed(), v, "expired")
continue // If the message has expired, don't hold or execute
}
eom, ok := v.(*messages.EOM)
if ok {
if int(eom.DBHeight)*10+int(eom.Minute) < int(s.LLeaderHeight)*10+s.CurrentMinute {
s.ExpireCnt++
s.DeleteFromHolding(v.GetMsgHash().Fixed(), v, "old EOM")
continue
}
if !eom.IsLocal() && eom.DBHeight > saved {
s.SetHighestKnownBlock(eom.DBHeight)
}
}
dbsigmsg, ok := v.(*messages.DirectoryBlockSignature)
if ok {
if dbsigmsg.DBHeight < s.LLeaderHeight || (s.CurrentMinute > 0 && dbsigmsg.DBHeight == s.LLeaderHeight) {
s.ExpireCnt++
s.DeleteFromHolding(v.GetMsgHash().Fixed(), v, "old DBSig")
continue
}
if !dbsigmsg.IsLocal() && dbsigmsg.DBHeight > saved {
s.SetHighestKnownBlock(dbsigmsg.DBHeight)
}
}
dbsmsg, ok := v.(*messages.DBStateMsg)
if ok && dbsmsg.DirectoryBlock.GetHeader().GetDBHeight() <= saved && saved > 0 {
s.ExpireCnt++
s.DeleteFromHolding(v.GetMsgHash().Fixed(), v, "old DBState")
continue
}
}
}
// Places the entries in the holding map back into the XReview list for
// review if this is a leader, and those messages are that leader's
// responsibility
func (s *State) ReviewHolding() {
preReviewHoldingTime := time.Now()
if len(s.XReview) > 0 {
return
}
now := s.GetTimestamp()
if s.ResendHolding == nil {
s.ResendHolding = now
}
if now.GetTimeMilli()-s.ResendHolding.GetTimeMilli() < 100 {
return
}
if len(s.Holding) == 0 {
return
}
if ValidationDebug {
s.LogPrintf("executeMsg", "Start reviewHolding")
defer s.LogPrintf("executeMsg", "end reviewHolding holding=%d, xreview=%d", len(s.Holding), len(s.XReview))
}
// moved to once per block in move state to height
//s.Commits.Cleanup(s)
//s.DB.Trim()
// Anything we are holding, we need to reprocess.
s.XReview = make([]interfaces.IMsg, 0)
highest := s.GetHighestKnownBlock()
saved := s.GetHighestSavedBlk()
if saved > highest {
highest = saved + 1
}
// if the sorted holding is empty or built for the wrong VM
if len(s.HoldingList) == 0 || s.HoldingVM != s.LeaderVMIndex {
s.HoldingVM = s.LeaderVMIndex // save the VM I used in making this sorted list
sorted := []interfaces.IMsg{}
for _, v := range s.Holding {
if v.GetVMIndex() == s.LeaderVMIndex || !constants.NeedsAck(v.Type()) {
sorted = append(sorted, v)
}
}
sort.Slice(sorted,
func(i, j int) bool {
a := sorted[i].GetTimestamp().GetTimeMilli()
b := sorted[j].GetTimestamp().GetTimeMilli()
return a < b
})
for k, v := range sorted {
if k >= cap(s.HoldingList) {
break
}
s.HoldingList <- v.GetMsgHash().Fixed()
}
}
cnt := 1
processholdinglist:
for {
if cnt&0x1F == 0 && s.GetTimestamp().GetTimeMilli()-now.GetTimeMilli() > 200 {
break processholdinglist
}
cnt++
var k [32]byte
var v interfaces.IMsg
var ok bool
select {
case k = <-s.HoldingList:
v, ok = s.Holding[k]
if !ok || v == nil {
continue processholdinglist
}
default:
break processholdinglist
}
if int(highest)-int(saved) > 1000 {
s.DeleteFromHolding(k, v, "HKB-HSB>1000")
continue processholdinglist // No point in executing if we think we can't hold this.
}
// If it is an entryCommit/ChainCommit/RevealEntry and it has a duplicate hash to an existing entry throw it away here
ce, ok := v.(*messages.CommitEntryMsg)
if ok {
x := s.NoEntryYet(ce.CommitEntry.EntryHash, ce.CommitEntry.GetTimestamp())
if !x {
s.DeleteFromHolding(k, v, "already committed")
continue processholdinglist
}
}
// If it is an chainCommit and it has a duplicate hash to an existing entry throw it away here
cc, ok := v.(*messages.CommitChainMsg)
if ok {
x := s.NoEntryYet(cc.CommitChain.EntryHash, cc.CommitChain.GetTimestamp())
if !x {
s.DeleteFromHolding(k, v, "already committed")
continue processholdinglist
}
}
validToSend, validToExecute := s.Validate(v)
if validToSend > 0 {
v.SendOut(s, v)
}
switch validToExecute {
case -1:
s.LogMessage("executeMsg", "invalid from holding", v)
s.DeleteFromHolding(k, v, "invalid from holding")
continue processholdinglist
case 0:
continue processholdinglist
}
// if it is a Factoid or entry credit transaction then check BLOCK_REPLAY
switch v.Type() {
case constants.FACTOID_TRANSACTION_MSG, constants.COMMIT_CHAIN_MSG, constants.COMMIT_ENTRY_MSG:
ok2 := s.FReplay.IsHashUnique(constants.BLOCK_REPLAY, v.GetRepeatHash().Fixed())
if !ok2 {
s.DeleteFromHolding(k, v, "BLOCK_REPLAY")
continue processholdinglist
}
default:
}
// If a Reveal Entry has a commit available, then process the Reveal Entry and send it out.
if re, ok := v.(*messages.RevealEntryMsg); ok {
if !s.NoEntryYet(re.GetHash(), s.GetLeaderTimestamp()) {
s.DeleteFromHolding(re.GetMsgHash().Fixed(), re, "already committed reveal")
s.Commits.Delete(re.GetHash().Fixed())
continue processholdinglist
}
// Needs to be our VMIndex as well, or ignore.
if re.GetVMIndex() != s.LeaderVMIndex || !s.Leader {
continue processholdinglist // If we are a leader, but it isn't ours, and it isn't a new minute, ignore.
}
}
TotalXReviewQueueInputs.Inc()
s.XReview = append(s.XReview, v)
TotalHoldingQueueOutputs.Inc()
}
s.ResendHolding = s.GetTimestamp()
reviewHoldingTime := time.Since(preReviewHoldingTime)
TotalReviewHoldingTime.Add(float64(reviewHoldingTime.Nanoseconds()))
}
func (s *State) MoveStateToHeight(dbheight uint32, newMinute int) {
// s.LogPrintf("dbstateprocess", "MoveStateToHeight(%d-:-%d) called from %s", dbheight, newMinute, atomic.WhereAmIString(1))
s.LogPrintf("dbstateprocess", "MoveStateToHeight(%d-:-%d)", dbheight, newMinute)
if (s.LLeaderHeight+1 == dbheight && newMinute == 0) || (s.LLeaderHeight == dbheight && s.CurrentMinute+1 == newMinute) {
// these are the allowed cases; move to nextblock-:-0 or move to next minute
} else {
s.LogPrintf("dbstateprocess", "State move between non-sequential heights from %d to %d", s.LLeaderHeight, dbheight)
if s.LLeaderHeight != dbheight {
fmt.Fprintf(os.Stderr, "State move between non-sequential heights from %d to %d\n", s.LLeaderHeight, dbheight)
}
//force sync state to a rational state for between minutes
s.Syncing = false // movestatetoheight
s.EOM = false // movestatetoheight
s.EOMDone = false // movestatetoheight
s.DBSig = false // movestatetoheight
s.EOMProcessed = 0 // movestatetoheight
s.DBSigProcessed = 0 // movestatetoheight
s.DBSigDone = false // movestatetoheight
if s.LeaderPL != nil {
for _, vm := range s.LeaderPL.VMs {
vm.Synced = false // movestatetoheight
}
}
}
// normally when loading by DBStates we jump from minute 0 to minute 0
// when following by minute we jump from minute 10 to minute 0
if s.LLeaderHeight != dbheight && s.CurrentMinute != 0 && s.CurrentMinute != 10 {
s.LogPrintf("dbstateprocess", "Jump in current minute from %d-:-%d to %d-:-%d", s.LLeaderHeight, s.CurrentMinute, dbheight, newMinute)
//fmt.Fprintf(os.Stderr, "Jump in current minute from %d-:-%d to %d-:-%d\n", s.LLeaderHeight, s.CurrentMinute, dbheight, newMinute)
}
//s.setCurrentMinute(newMinute) // MoveStateToHeight() move minute
//s.SetLLeaderHeight(int(dbheight)) // Update leader height in MoveStateToHeight
if s.LLeaderHeight != dbheight {
if newMinute != 0 {
panic(fmt.Sprintf("Can't jump to the middle of a block minute: %d", newMinute))
}
s.DBStates.UpdateState()
// update cached values that change with current minute
s.CurrentMinute = 0 // Update height and minute
s.LLeaderHeight = uint32(dbheight) // Update height and minute
// update cached values that change with height
s.LeaderPL = s.ProcessLists.Get(dbheight) // fix up cached values
if s.LLeaderHeight != s.LeaderPL.DBHeight {
panic("bad things are happening")
}
s.ProcessLists.Get(dbheight + 1) // Make sure next PL exists
// We are between blocks make sure we are setup to sync
// should already be true but if a DBSTATE got processed mid block
// there might be a circumstance where we get here in a weird state
// so make it the normal starting state
// update cached values that change with height
s.dbheights <- int(dbheight) // Notify MMR process we have moved on...
s.CurrentMinuteStartTime = time.Now().UnixNano()
s.CurrentBlockStartTime = s.CurrentMinuteStartTime
// If an we added or removed servers or elections tool place in minute 9, our lists will be unsorted. Fix that
s.LeaderPL.SortAuditServers()
s.LeaderPL.SortFedServers()
// check for identity change every time we start a new block before we look up our VM
s.CheckForIDChange()
s.Leader, s.LeaderVMIndex = s.LeaderPL.GetVirtualServers(s.CurrentMinute, s.IdentityChainID) // MoveStateToHeight block
s.LogPrintf("executeMsg", "MoveStateToHeight set leader=%v, vmIndex = %v", s.Leader, s.LeaderVMIndex)
// update the elections thread
authlistMsg := s.EFactory.NewAuthorityListInternal(s.LeaderPL.FedServers, s.LeaderPL.AuditServers, s.LLeaderHeight)
s.ElectionsQueue().Enqueue(authlistMsg)
// Do not send out dbsigs while loading from disk
if s.Leader && !s.LeaderPL.DBSigAlreadySent && s.LLeaderHeight > s.DBHeightAtBoot {
s.SendDBSig(s.LLeaderHeight, s.LeaderVMIndex) // MoveStateToHeight()
}
s.DBStates.UpdateState() // go process the DBSigs
// Expire old commits and stuff ...
s.Commits.Cleanup(s)
s.DB.Trim()
} else if s.CurrentMinute != newMinute { // And minute
switch newMinute {
case 1:
dbstate := s.GetDBState(dbheight - 1)
if dbstate != nil && !dbstate.Saved {
s.LogPrintf("dbstateprocess", "Set ReadyToSave %d", dbstate.DirectoryBlock.GetHeader().GetDBHeight())
dbstate.ReadyToSave = true
}
s.DBStates.UpdateState() // call to get the state signed now that the DBSigs have processed
case 2:
s.ExpireHolding() // expire anything in holding that is old.
}
s.CurrentMinute = newMinute // Update just the minute
// We are between blocks make sure we are setup to sync
// should already be true but if a DBSTATE got processed mid block
// there might be a circumstance where we get here in a weird state
// so make it the normal starting state
s.CurrentMinuteStartTime = time.Now().UnixNano()
// If an election took place, our lists will be unsorted. Fix that
s.LeaderPL.SortAuditServers()
s.LeaderPL.SortFedServers()
s.Leader, s.LeaderVMIndex = s.LeaderPL.GetVirtualServers(newMinute, s.IdentityChainID) // MoveStateToHeight minute
s.LogPrintf("executeMsg", "MoveStateToHeight new minute set leader=%v, vmIndex = %v", s.Leader, s.LeaderVMIndex)
}
{ // debug
vmSync := false
for _, vm := range s.LeaderPL.VMs {
if vm != nil {
vmSync = vmSync || vm.Synced
}
}
if s.Syncing || s.EOM || s.EOMDone || s.DBSig || (s.EOMProcessed != 0) || (s.DBSigProcessed != 0) || vmSync {
s.LogPrintf("executeMsg", "resetting syncstate in moveToHeight")
s.LogPrintf("executeMsg", "s.Syncing=%v s.EOM=%v s.EOMDone=%v s.DBSig=%v s.DBSigDone=%v s.EOMProcessed=%d s.DBSigProcessed=%v, vmSync = %v",
s.Syncing, s.EOM, s.EOMDone, s.DBSig, s.DBSigDone, s.EOMProcessed, s.DBSigProcessed, vmSync)
}
}
// set the limits because we might have added servers
s.EOMLimit = len(s.LeaderPL.FedServers) // We add or remove server only on block boundaries
s.DBSigLimit = s.EOMLimit // We add or remove server only on block boundaries
s.LogPrintf("dbstateprocess", "MoveStateToHeight(%d-:-%d) leader=%v leaderPL=%p, leaderVMIndex=%d", dbheight, newMinute, s.Leader, s.LeaderPL, s.LeaderVMIndex)
s.Hold.ExecuteForNewHeight(s.LLeaderHeight, s.CurrentMinute) // execute held messages
s.Hold.Review() // cleanup old messages
}
// Adds blocks that are either pulled locally from a database, or acquired from peers.
func (s *State) AddDBState(isNew bool,
directoryBlock interfaces.IDirectoryBlock,
adminBlock interfaces.IAdminBlock,
factoidBlock interfaces.IFBlock,
entryCreditBlock interfaces.IEntryCreditBlock,
eBlocks []interfaces.IEntryBlock,
entries []interfaces.IEBEntry) *DBState {
// This is expensive, so only do this once the database is loaded.
if s.DBFinished {
s.LogPrintf("dbstateprocess", "AddDBState(isNew %v, directoryBlock %d %x, adminBlock %x, factoidBlock %x, entryCreditBlock %X, eBlocks %d, entries %d)",
isNew, directoryBlock.GetHeader().GetDBHeight(), directoryBlock.GetHash().Bytes()[:4],
adminBlock.GetHash().Bytes()[:4], factoidBlock.GetHash().Bytes()[:4], entryCreditBlock.GetHash().Bytes()[:4], len(eBlocks), len(entries))
}
dbState := s.DBStates.NewDBState(isNew, directoryBlock, adminBlock, factoidBlock, entryCreditBlock, eBlocks, entries)
if dbState == nil {
//s.AddStatus(fmt.Sprintf("AddDBState(): Fail dbstate is nil at dbht: %d", directoryBlock.GetHeader().GetDBHeight()))
return nil
}
ht := dbState.DirectoryBlock.GetHeader().GetDBHeight()
DBKeyMR := dbState.DirectoryBlock.GetKeyMR().String()
err := CheckDBKeyMR(s, ht, DBKeyMR)
if err != nil {
panic(fmt.Errorf("Found block at height %d that didn't match a checkpoint. Got %s, expected %s", ht, DBKeyMR, constants.CheckPoints[ht])) //TODO make failing when given bad blocks fail more elegantly
}
if ht == s.LLeaderHeight-1 || (ht == s.LLeaderHeight) {
} else {
s.LogPrintf("dbstateprocess", "AddDBState out of order! at %d added %d", s.LLeaderHeight, ht)
fmt.Fprintf(os.Stderr, "AddDBState() out of order! at %d added %d\n", s.LLeaderHeight, ht)
//panic("AddDBState out of order!")
}
return dbState
}
// Messages that will go into the Process List must match an Acknowledgement.
// The code for this is the same for all such messages, so we put it here.
//
// Returns true if it finds a match, puts the message in holding, or invalidates the message
func (s *State) FollowerExecuteMsg(m interfaces.IMsg) {
FollowerExecutions.Inc()
// add it to the holding queue in case AddToProcessList may remove it
TotalHoldingQueueInputs.Inc()
//s.Holding[m.GetMsgHash().Fixed()] = m
s.AddToHolding(m.GetMsgHash().Fixed(), m) // FollowerExecuteMsg()
ack, _ := s.Acks[m.GetMsgHash().Fixed()].(*messages.Ack)
if ack != nil {
m.SetLeaderChainID(ack.GetLeaderChainID())
m.SetMinute(ack.Minute)
pl := s.ProcessLists.Get(ack.DBHeight)
pl.AddToProcessList(s, ack, m)
// Cross Boot Replay
s.CrossReplayAddSalt(ack.DBHeight, ack.Salt)
}
}
// execute a msg with an optional delay (in factom seconds)
func (s *State) repost(m interfaces.IMsg, delay int) {
//whereAmI := atomic.WhereAmIString(1)
go func() { // This is a trigger to issue the EOM, but we are still syncing. Wait to retry.
if delay > 0 {
time.Sleep(time.Duration(delay) * s.FactomSecond()) // delay in Factom seconds
}
//s.LogMessage("MsgQueue", fmt.Sprintf("enqueue_%s(%d)", whereAmI, len(s.msgQueue)), m)
s.LogMessage("MsgQueue", fmt.Sprintf("repost enqueue (%d)", len(s.msgQueue)), m)
s.msgQueue <- m // Goes in the "do this really fast" queue so we are prompt about EOM's while syncing
}()
}
// FactomSecond finds the time duration of 1 second relative to 10min blocks.
// Blktime EOMs Second
// 600s 60s 1s
// 300s 30s 0.5s
// 120s 12s 0.2s
// 60s 6s 0.1s
// 30s 3s 0.05s
func (s *State) FactomSecond() time.Duration {
// Convert to time.second, then divide by 600
factomsecond := time.Duration(s.DirectoryBlockInSeconds) * time.Second / 600
if factomsecond < time.Duration(250*time.Millisecond) {
factomsecond = time.Duration(250 * time.Millisecond) // for really fast block we lie ...
}
return factomsecond
}
// Messages that will go into the Process List must match an Acknowledgement.
// The code for this is the same for all such messages, so we put it here.
//
// Returns true if it finds a match, puts the message in holding, or invalidates the message
func (s *State) FollowerExecuteEOM(m interfaces.IMsg) {
if m.IsLocal() && !s.Leader {
return // This is an internal EOM message. We are not a leader so ignore.
} else if m.IsLocal() {