/
stateConsensus.go
2841 lines (2427 loc) · 92.9 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"
"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) {
_, 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()
}
}
// 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
}
}
switch msg.Type() {
case constants.DBSTATE_MSG, constants.DATA_RESPONSE, constants.MISSING_MSG, constants.MISSING_DATA, constants.MISSING_ENTRY_BLOCKS, constants.DBSTATE_MISSING_MSG, constants.ENTRY_BLOCK_RESPONSE:
// Allow these thru as they do not have Ack's (they don't change processlists)
default:
// Make sure we don't put in an old ack'd message (outside our repeat filter range)
tlim := int64(Range * 60 * 2 * 1000000000) // Filter hold two hours of messages, one in the past one in the future
filterTime := s.GetMessageFilterTimestamp().GetTime().UnixNano() // this is the start of the filter
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+tlim) {
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 + tlim) {
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
}
}
defer func() {
if validToExec == 1 && s.LLeaderHeight > 1 && s.Acks[msg.GetHash().Fixed()] == nil {
switch msg.Type() {
case constants.REVEAL_ENTRY_MSG, constants.COMMIT_ENTRY_MSG, constants.COMMIT_CHAIN_MSG, constants.FACTOID_TRANSACTION_MSG:
pl := s.ProcessLists.Get(s.LLeaderHeight)
if pl.VMs[msg.GetVMIndex()].Synced {
validToExec = 0
}
}
}
}()
// 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 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_REPLAY", 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) {
switch msg.Type() {
case constants.COMMIT_ENTRY_MSG, constants.COMMIT_CHAIN_MSG, constants.REVEAL_ENTRY_MSG,
constants.EOM_MSG, constants.DIRECTORY_BLOCK_SIGNATURE_MSG, constants.FACTOID_TRANSACTION_MSG:
// 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.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("badMsgs", "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, constants.COMMIT_ENTRY_MSG, constants.COMMIT_CHAIN_MSG:
if !s.NoEntryYet(msg.GetHash(), nil) {
//delete(s.Holding, msg.GetHash().Fixed())
s.DeleteFromHolding(msg.GetMsgHash().Fixed(), msg, "AlreadyCommitted") // delete commit
s.DeleteFromHolding(msg.GetHash().Fixed(), msg, "AlreadyCommitted") // delete reveal
s.Commits.Delete(msg.GetHash().Fixed())
s.LogMessage("executeMsg", "drop, already committed", msg)
return true
}
s.AddToHolding(msg.GetMsgHash().Fixed(), msg) // add valid commit/reveal to holding in case it fails to get added
//s.Holding[msg.GetMsgHash().Fixed()] = msg
}
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
!vms && // 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", "LeaderExecute", msg)
msg.LeaderExecute(s)
}
} else {
s.LogMessage("executeMsg", "FollowerExecute", msg)
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.AddToHolding(msg.GetMsgHash().Fixed(), msg) // Add message where validToExecute==0
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 {
s.LogPrintf("dbstateprocess", "Trying to process DBStatesReceived %d", s.DBStatesReceivedBase+ix)
s.executeMsg(msg)
}
// if we can not process a DBStatesReceived then go process some messages
if hsb == s.GetHighestSavedBlk() {
break
}
}
}
// Process inbound messages
preEmptyLoopTime := time.Now()
if ValidationDebug {
s.LogPrintf("executeMsg", "start messageSort")
}
emptyLoop:
for {
select {
case msg := <-s.msgQueue:
s.LogMessage("msgQueue", "Execute", msg)
progress = s.executeMsg(msg) || progress
default:
break emptyLoop
}
}
emptyLoopTime := time.Since(preEmptyLoopTime)
TotalEmptyLoopTime.Add(float64(emptyLoopTime.Nanoseconds()))
preAckLoopTime := time.Now()
// Process acknowledgements if we have some.
ackLoop:
for {
select {
case ack := <-s.ackQueue:
_, validToExecute := s.Validate(ack)
switch validToExecute {
case -1:
s.LogMessage("ackQueue", "drop Invalid", ack)
continue
case 0:
s.LogMessage("ackQueue", "Hold", ack)
// toss the ack into holding and we will try again in a bit...
TotalHoldingQueueInputs.Inc()
//s.Holding[ack.GetMsgHash().Fixed()] = ack
s.AddToHolding(ack.GetMsgHash().Fixed(), ack) // Add ack where valid==0
continue
}
s.LogMessage("ackQueue", "Execute2", ack)
progress = s.executeMsg(ack) || progress
default:
break ackLoop
}
}
ackLoopTime := time.Since(preAckLoopTime)
TotalAckLoopTime.Add(float64(ackLoopTime.Nanoseconds()))
preProcessXReviewTime := time.Now()
// Reprocess any stalled messages, but not so much compared inbound messages
// Process last first
if ValidationDebug {
s.LogPrintf("executeMsg", "start reviewHolding")
}
if s.RunLeader {
s.ReviewHolding()
for {
for _, msg := range s.XReview {
if msg == nil {
continue
}
// copy the messages we are responsible for and all ACKs to process to be executed
if msg.GetVMIndex() == s.LeaderVMIndex || msg.Type() == constants.ACK_MSG {
process = append(process, msg)
}
}
// toss everything else
s.XReview = s.XReview[:0]
break
} // skip review
}
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
//***************************************************************
// 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))
}
s.Commits.Cleanup(s)
s.DB.Trim()
// Set the resend time at the END of the function. This prevents the time it takes to execute this function
// from reducing the time we allow before another review
defer func() {
s.ResendHolding = now
}()
// 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
}
for _, a := range s.Acks {
if s.Holding[a.GetHash().Fixed()] != nil {
a.FollowerExecute(s)
}
}
// Set this flag, so it acts as a constant. We will set s.LeaderNewMin to false
// after processing the Holding Queue. Ensures we only do this one per minute.
// processMinute := s.LeaderNewMin // Have we processed this minute
s.LeaderNewMin++ // Either way, don't do it again until the ProcessEOM resets LeaderNewMin
for k, v := range s.Holding {
if (time.Now().Add(-2 * time.Second)).After(preReviewHoldingTime) {
break
}
if int(highest)-int(saved) > 1000 {
TotalHoldingQueueOutputs.Inc()
//delete(s.Holding, k)
s.DeleteFromHolding(k, v, "HKB-HSB>1000")
continue // No point in executing if we think we can't hold this.
}
if v.Expire(s) {
s.LogMessage("executeMsg", "expire from holding", v)
s.ExpireCnt++
TotalHoldingQueueOutputs.Inc()
//delete(s.Holding, k)
s.DeleteFromHolding(k, 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.DeleteFromHolding(k, v, "old EOM")
continue
}
if !eom.IsLocal() && eom.DBHeight > saved {
s.HighestKnown = eom.DBHeight
}
}
dbsigmsg, ok := v.(*messages.DirectoryBlockSignature)
if ok {
if dbsigmsg.DBHeight < s.LLeaderHeight || (s.CurrentMinute > 0 && dbsigmsg.DBHeight == s.LLeaderHeight) {
TotalHoldingQueueOutputs.Inc()
//delete(s.Holding, k)
s.DeleteFromHolding(k, v, "Old DBSig")
continue
}
if !dbsigmsg.IsLocal() && dbsigmsg.DBHeight > saved {
s.HighestKnown = dbsigmsg.DBHeight
}
}
dbsmsg, ok := v.(*messages.DBStateMsg)
if ok && dbsmsg.DirectoryBlock.GetHeader().GetDBHeight() <= saved && saved > 0 {
TotalHoldingQueueOutputs.Inc()
//delete(s.Holding, k)
s.DeleteFromHolding(k, v, "old DBState")
continue
}
// 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 {
TotalHoldingQueueOutputs.Inc()
//delete(s.Holding, k) // Drop commits with the same entry hash from holding because they are blocked by a previous entry
s.DeleteFromHolding(k, v, "already committed")
continue
}
}
// 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 {
TotalHoldingQueueOutputs.Inc()
//delete(s.Holding, k) // Drop commits with the same entry hash from holding because they are blocked by a previous entry
s.DeleteFromHolding(k, v, "already committed")
continue
}
}
validToSend, validToExecute := s.Validate(v)
if validToSend > 0 {
v.SendOut(s, v)
}
switch validToExecute {
case -1:
s.LogMessage("executeMsg", "invalid from holding", v)
TotalHoldingQueueOutputs.Inc()
//delete(s.Holding, k)
s.DeleteFromHolding(k, v, "invalid from holding")
continue
case 0:
continue
}
// 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
}
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.GetHash().Fixed(), re, "already committed reveal")
s.Commits.Delete(re.GetHash().Fixed())
continue
}
// Needs to be our VMIndex as well, or ignore.
if re.GetVMIndex() != s.LeaderVMIndex || !s.Leader {
continue // 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()
if len(s.XReview) > 200 {
break
}
}
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 s.DBSigDone == true {
// s.LogPrintf("executeMsg", "reset s.DBSigDone in MoveStateToHeight for block change")
//}
//
//s.DBSigDone = false // movestatetoheight (new block)
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)
if s.Leader && !s.LeaderPL.DBSigAlreadySent {
s.SendDBSig(s.LLeaderHeight, s.LeaderVMIndex) // MoveStateToHeight()
}
s.DBStates.UpdateState() // go process the DBSigs
} else if s.CurrentMinute != newMinute { // And minute
if newMinute == 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
}
s.CurrentMinute = newMinute // Update just the minute
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)
// 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()
}
{ // 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)
}
}
// force sync state to a ration 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
// leave s.DBSigDone alone unless it's a block change
//for _, vm := range s.LeaderPL.VMs {
// vm.Synced = false // movestatetoheight
//}
// 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)
}
// 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!")
}
if ht > s.LLeaderHeight {
s.LogPrintf("dbstateprocess", "unexpected: ht > s.LLeaderHeight at %d added %d", s.LLeaderHeight, ht)
//fmt.Println(fmt.Sprintf("SigType PROCESS: %10s Add DBState: s.SigType(%v)", s.FactomNodeName, s.SigType))
s.MoveStateToHeight(ht, 0) // AddDBState()
s.StartDelay = s.GetTimestamp().GetTimeMilli()
s.RunLeader = false
LeaderPL := s.ProcessLists.Get(s.LLeaderHeight)
if s.LLeaderHeight != 0 && s.LeaderPL != LeaderPL {
s.LogPrintf("ExecuteMsg", "AddDBState: Unexpected change in LeaderPL")
s.LeaderPL = LeaderPL
}
s.SetLeaderTimestamp(dbState.DirectoryBlock.GetTimestamp()) // move the leader timestamp to the start of the block
{
// Okay, we have just loaded a new DBState. The temp balances are no longer valid, if they exist. Nuke them.
s.LeaderPL.FactoidBalancesTMutex.Lock()
s.LeaderPL.FactoidBalancesT = map[[32]byte]int64{}
s.LeaderPL.FactoidBalancesTMutex.Unlock()
s.LeaderPL.ECBalancesTMutex.Lock()
s.LeaderPL.ECBalancesT = map[[32]byte]int64{}
s.LeaderPL.ECBalancesTMutex.Unlock()
}
Leader, LeaderVMIndex := s.LeaderPL.GetVirtualServers(s.CurrentMinute, s.IdentityChainID) // AddDBState()
{ // debug
if s.Leader != Leader {
s.LogPrintf("executeMsg", "State.AddDBState() unexpectedly setting s.Leader to %v", Leader)
s.Leader = Leader
}
if s.LeaderVMIndex != LeaderVMIndex {
s.LogPrintf("executeMsg", "State.AddDBState() unexpectedly setting s.LeaderVMIndex to %v", LeaderVMIndex)
s.LeaderVMIndex = LeaderVMIndex
}
}
for s.ProcessLists.UpdateState(s.LLeaderHeight) {
}
}
if ht == 0 && s.LLeaderHeight == 0 {
s.MoveStateToHeight(1, 0)
}
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)
}
}
// exeute 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 {