/
node.go
1789 lines (1563 loc) · 52.1 KB
/
node.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
package committee
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
beacon "github.com/oasisprotocol/oasis-core/go/beacon/api"
"github.com/oasisprotocol/oasis-core/go/common/crash"
"github.com/oasisprotocol/oasis-core/go/common/crypto/hash"
"github.com/oasisprotocol/oasis-core/go/common/logging"
"github.com/oasisprotocol/oasis-core/go/common/node"
"github.com/oasisprotocol/oasis-core/go/common/pubsub"
"github.com/oasisprotocol/oasis-core/go/common/version"
consensus "github.com/oasisprotocol/oasis-core/go/consensus/api"
roothash "github.com/oasisprotocol/oasis-core/go/roothash/api"
"github.com/oasisprotocol/oasis-core/go/roothash/api/block"
"github.com/oasisprotocol/oasis-core/go/roothash/api/commitment"
"github.com/oasisprotocol/oasis-core/go/runtime/host"
"github.com/oasisprotocol/oasis-core/go/runtime/host/protocol"
"github.com/oasisprotocol/oasis-core/go/runtime/transaction"
storage "github.com/oasisprotocol/oasis-core/go/storage/api"
commonWorker "github.com/oasisprotocol/oasis-core/go/worker/common"
"github.com/oasisprotocol/oasis-core/go/worker/common/committee"
"github.com/oasisprotocol/oasis-core/go/worker/common/p2p"
p2pError "github.com/oasisprotocol/oasis-core/go/worker/common/p2p/error"
"github.com/oasisprotocol/oasis-core/go/worker/common/p2p/txsync"
"github.com/oasisprotocol/oasis-core/go/worker/registration"
)
var (
errSeenNewerBlock = fmt.Errorf("executor: seen newer block")
errRuntimeAborted = fmt.Errorf("executor: runtime aborted batch processing")
errIncompatibleHeader = p2pError.Permanent(fmt.Errorf("executor: incompatible header"))
errBatchTooLarge = p2pError.Permanent(fmt.Errorf("executor: batch too large"))
errIncorrectRole = fmt.Errorf("executor: incorrect role")
errIncorrectState = fmt.Errorf("executor: incorrect state")
errMsgFromNonTxnSched = fmt.Errorf("executor: received txn scheduler dispatch msg from non-txn scheduler")
// Transaction scheduling errors.
errNoBlocks = fmt.Errorf("executor: no blocks")
errNotExecutor = fmt.Errorf("executor: not executor in this round")
// proposeTimeoutDelay is the duration to wait before submitting the propose timeout request.
proposeTimeoutDelay = 2 * time.Second
// abortTimeout is the duration to wait for the runtime to abort.
abortTimeout = 5 * time.Second
)
var (
discrepancyDetectedCount = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "oasis_worker_execution_discrepancy_detected_count",
Help: "Number of detected execute discrepancies.",
},
[]string{"runtime"},
)
abortedBatchCount = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "oasis_worker_aborted_batch_count",
Help: "Number of aborted batches.",
},
[]string{"runtime"},
)
storageCommitLatency = prometheus.NewSummaryVec(
prometheus.SummaryOpts{
Name: "oasis_worker_storage_commit_latency",
Help: "Latency of storage commit calls (state + outputs) (seconds).",
},
[]string{"runtime"},
)
batchProcessingTime = prometheus.NewSummaryVec(
prometheus.SummaryOpts{
Name: "oasis_worker_batch_processing_time",
Help: "Time it takes for a batch to finalize (seconds).",
},
[]string{"runtime"},
)
batchRuntimeProcessingTime = prometheus.NewSummaryVec(
prometheus.SummaryOpts{
Name: "oasis_worker_batch_runtime_processing_time",
Help: "Time it takes for a batch to be processed by the runtime (seconds).",
},
[]string{"runtime"},
)
batchSize = prometheus.NewSummaryVec(
prometheus.SummaryOpts{
Name: "oasis_worker_batch_size",
Help: "Number of transactions in a batch.",
},
[]string{"runtime"},
)
nodeCollectors = []prometheus.Collector{
discrepancyDetectedCount,
abortedBatchCount,
storageCommitLatency,
batchProcessingTime,
batchRuntimeProcessingTime,
batchSize,
}
metricsOnce sync.Once
)
// Node is a committee node.
type Node struct { // nolint: maligned
runtimeReady bool
runtimeVersion version.Version
runtimeCapabilityTEE *node.CapabilityTEE
runtimeTrustSynced bool
runtimeTrustSyncCncl context.CancelFunc
limitsLastUpdateLock sync.Mutex
// limitsLastUpdate is the round of the last update of the round weight limits.
limitsLastUpdate uint64
// Guarded by .commonNode.CrossNode.
proposingTimeout bool
commonNode *committee.Node
commonCfg commonWorker.Config
roleProvider registration.RoleProvider
ctx context.Context
cancelCtx context.CancelFunc
stopCh chan struct{}
stopOnce sync.Once
quitCh chan struct{}
initCh chan struct{}
// Mutable and shared with common node's worker.
// Guarded by .commonNode.CrossNode.
state NodeState
// Context valid until the next round.
// Guarded by .commonNode.CrossNode.
roundCtx context.Context
roundCancelCtx context.CancelFunc
storage storage.LocalBackend
txSync txsync.Client
stateTransitions *pubsub.Broker
// Bump this when we need to change what the worker selects over.
reselect chan struct{}
logger *logging.Logger
}
// Name returns the service name.
func (n *Node) Name() string {
return "executor committee node"
}
// Start starts the service.
func (n *Node) Start() error {
// Make sure we are running with a compatible storage backend.
lsb, ok := n.commonNode.Runtime.Storage().(storage.LocalBackend)
if !ok {
return fmt.Errorf("executor requires a local storage backend")
}
// Make sure to unwrap the local backend as we need the raw local backend here.
if wrapped, ok := lsb.(storage.WrappedLocalBackend); ok {
lsb = wrapped.Unwrap()
}
n.storage = lsb
go n.worker()
return nil
}
// Stop halts the service.
func (n *Node) Stop() {
n.stopOnce.Do(func() { close(n.stopCh) })
}
// Quit returns a channel that will be closed when the service terminates.
func (n *Node) Quit() <-chan struct{} {
return n.quitCh
}
// Cleanup performs the service specific post-termination cleanup.
func (n *Node) Cleanup() {
}
// Initialized returns a channel that will be closed when the node is
// initialized and ready to service requests.
func (n *Node) Initialized() <-chan struct{} {
return n.initCh
}
// WatchStateTransitions subscribes to the node's state transitions.
func (n *Node) WatchStateTransitions() (<-chan NodeState, *pubsub.Subscription) {
sub := n.stateTransitions.Subscribe()
ch := make(chan NodeState)
sub.Unwrap(ch)
return ch, sub
}
func (n *Node) getMetricLabels() prometheus.Labels {
return prometheus.Labels{
"runtime": n.commonNode.Runtime.ID().String(),
}
}
func (n *Node) queueBatchBlocking(ctx context.Context, proposal *commitment.Proposal) error {
rt, err := n.commonNode.Runtime.ActiveDescriptor(ctx)
if err != nil {
n.logger.Warn("failed to fetch active runtime descriptor",
"err", err,
)
return p2pError.Permanent(err)
}
// Do a quick check on the batch size.
if uint64(len(proposal.Batch)) > rt.TxnScheduler.MaxBatchSize {
n.logger.Warn("received proposed batch contained too many transactions",
"max_batch_size", rt.TxnScheduler.MaxBatchSize,
"batch_size", len(proposal.Batch),
)
return errBatchTooLarge
}
batch := &unresolvedBatch{
proposal: proposal,
maxBatchSizeBytes: rt.TxnScheduler.MaxBatchSizeBytes,
}
n.commonNode.CrossNode.Lock()
defer n.commonNode.CrossNode.Unlock()
return n.handleExternalBatchLocked(batch)
}
func (n *Node) bumpReselect() {
select {
case n.reselect <- struct{}{}:
default:
// If there's one already queued, we don't need to do anything.
}
}
// Guarded by n.commonNode.CrossNode.
func (n *Node) transitionLocked(state NodeState) {
n.logger.Info("state transition",
"current_state", n.state,
"new_state", state,
)
// Validate state transition.
dests := validStateTransitions[n.state.Name()]
var valid bool
for _, dest := range dests[:] {
if dest == state.Name() {
valid = true
break
}
}
if !valid {
panic(fmt.Sprintf("invalid state transition: %s -> %s", n.state, state))
}
n.state = state
n.stateTransitions.Broadcast(state)
// Restart our worker's select in case our state-specific channels have changed.
n.bumpReselect()
}
// HandleEpochTransitionLocked implements NodeHooks.
// Guarded by n.commonNode.CrossNode.
func (n *Node) HandleEpochTransitionLocked(epoch *committee.EpochSnapshot) {
switch {
case epoch.IsExecutorWorker(), epoch.IsExecutorBackupWorker():
n.transitionLocked(StateWaitingForBatch{})
default:
n.transitionLocked(StateNotReady{})
}
}
// HandleNewBlockEarlyLocked implements NodeHooks.
// Guarded by n.commonNode.CrossNode.
func (n *Node) HandleNewBlockEarlyLocked(blk *block.Block) {
crash.Here(crashPointRoothashReceiveAfter)
// If we have seen a new block while a batch was processing, we need to
// abort it no matter what as any processed state may be invalid.
n.abortBatchLocked(errSeenNewerBlock)
// Update our availability.
n.nudgeAvailability(false)
}
// HandleNewBlockLocked implements NodeHooks.
// Guarded by n.commonNode.CrossNode.
func (n *Node) HandleNewBlockLocked(blk *block.Block) {
header := blk.Header
// Cancel old round context, start a new one.
if n.roundCancelCtx != nil {
(n.roundCancelCtx)()
}
n.roundCtx, n.roundCancelCtx = context.WithCancel(n.ctx)
clearProposalQueue := true
// Perform actions based on current state.
switch state := n.state.(type) {
case StateWaitingForBlock:
// Check if this was the block we were waiting for.
currentHash := header.EncodedHash()
if currentHash.Equal(&state.batch.proposal.Header.PreviousHash) {
n.logger.Info("received block needed for batch processing")
clearProposalQueue = false
n.maybeStartProcessingBatchLocked(state.batch)
break
}
// Check if the new block is for the same or newer round than the
// one we are waiting for. In this case, we should abort as the
// block will never be seen.
curRound := header.Round
waitRound := state.batch.proposal.Header.Round - 1
if curRound >= waitRound {
n.logger.Warn("seen newer block while waiting for block")
n.transitionLocked(StateWaitingForBatch{})
break
}
// Continue waiting for block.
n.logger.Info("still waiting for block",
"current_round", curRound,
"wait_round", waitRound,
)
case StateWaitingForTxs:
// Stop waiting for transactions and start a new round.
n.logger.Warn("considering previous proposal invalid due to missing transactions")
n.transitionLocked(StateWaitingForBatch{})
case StateWaitingForEvent:
// Block finalized without the need for a backup worker.
n.logger.Info("considering the round finalized",
"round", header.Round,
"header_hash", header.EncodedHash(),
)
n.transitionLocked(StateWaitingForBatch{})
case StateWaitingForFinalize:
func() {
defer n.transitionLocked(StateWaitingForBatch{})
// A new block means the round has been finalized.
n.logger.Info("considering the round finalized",
"round", header.Round,
"header_hash", header.EncodedHash(),
"header_type", header.HeaderType,
)
if header.HeaderType != block.Normal {
return
}
if !header.IORoot.Equal(&state.proposedIORoot) {
n.logger.Error("proposed batch was not finalized",
"header_io_root", header.IORoot,
"proposed_io_root", state.proposedIORoot,
"header_type", header.HeaderType,
"batch_size", len(state.txHashes),
)
return
}
// Record time taken for successfully processing a batch.
batchProcessingTime.With(n.getMetricLabels()).Observe(time.Since(state.batchStartTime).Seconds())
n.logger.Debug("removing processed batch from queue",
"batch_size", len(state.txHashes),
"io_root", header.IORoot,
)
// Remove processed transactions from queue.
n.commonNode.TxPool.RemoveTxBatch(state.txHashes)
}()
}
// Clear proposal queue.
if clearProposalQueue {
n.commonNode.TxPool.ClearProposedBatch()
}
// Clear the potentially set "is proposing timeout" flag from the previous round.
n.proposingTimeout = false
if header.HeaderType != block.Normal {
// If last round was not successful, make sure we re-query the round weight limits
// before scheduling a batch as ExecuteTxResponse could have set invalid weights.
n.limitsLastUpdateLock.Lock()
n.limitsLastUpdate = header.Round - 1
n.limitsLastUpdateLock.Unlock()
}
// Check if we are a proposer and if so try to immediately schedule a new batch.
if n.commonNode.Group.GetEpochSnapshot().IsTransactionScheduler(blk.Header.Round) {
n.logger.Info("we are a transaction scheduler",
"round", blk.Header.Round,
)
n.commonNode.TxPool.WakeupScheduler()
}
}
func (n *Node) updateBatchWeightLimits(ctx context.Context, blk *block.Block, lb *consensus.LightBlock, epoch beacon.EpochTime) error {
n.limitsLastUpdateLock.Lock()
defer n.limitsLastUpdateLock.Unlock()
if n.limitsLastUpdate != 0 && n.limitsLastUpdate >= blk.Header.Round {
n.logger.Debug("skipping querying batch weight limits",
"last_update_round", n.limitsLastUpdate,
"round", blk.Header.Round,
)
// Already queried weights for this round.
return nil
}
rt := n.commonNode.GetHostedRuntime()
if rt == nil {
return fmt.Errorf("updating runtime weight limits while hosted runtime is not initialized")
}
// Query batch limits.
batchLimits, err := rt.QueryBatchLimits(ctx, blk, lb, epoch)
if err != nil {
return fmt.Errorf("querying batch round limits: %w", err)
}
if err := n.commonNode.TxPool.UpdateWeightLimits(batchLimits); err != nil {
return err
}
n.limitsLastUpdate = blk.Header.Round
return nil
}
func (n *Node) proposeTimeoutLocked(roundCtx context.Context) error {
// Do not propose a timeout if we are already proposing it.
// The flag will get cleared on the next round or if the propose timeout
// tx fails.
if n.proposingTimeout {
return nil
}
if n.commonNode.CurrentBlock == nil {
return fmt.Errorf("executor: propose timeout error, nil block")
}
rt, err := n.commonNode.Runtime.ActiveDescriptor(roundCtx)
if err != nil {
return err
}
proposerTimeout := rt.TxnScheduler.ProposerTimeout
currentBlockHeight := n.commonNode.CurrentBlockHeight
if n.commonNode.Height < currentBlockHeight+proposerTimeout {
n.logger.Debug("executor: proposer timeout not reached yet",
"height", n.commonNode.Height,
"current_block_height", currentBlockHeight,
"proposer_timeout", proposerTimeout,
)
return nil
}
n.logger.Debug("executor requesting proposer timeout",
"height", n.commonNode.Height,
"current_block_height", currentBlockHeight,
"proposer_timeout", proposerTimeout,
)
n.proposingTimeout = true
tx := roothash.NewRequestProposerTimeoutTx(0, nil, n.commonNode.Runtime.ID(), n.commonNode.CurrentBlock.Header.Round)
go func(round uint64) {
// Wait a bit before actually proposing a timeout, to give the current
// scheduler some time to propose a batch in case it just received it.
//
// This prevents triggering a timeout when there is a long period
// of no transactions, as without this artificial delay, the non
// scheduler nodes would be faster in proposing a timeout than the
// scheduler node proposing a batch.
select {
case <-time.After(proposeTimeoutDelay):
case <-roundCtx.Done():
n.logger.Info("not requesting proposer timeout, round context canceled")
return
}
// Make sure we are still in the right state/round.
n.commonNode.CrossNode.Lock()
// Make sure we are still in the right state.
var invalidState bool
switch n.state.(type) {
case StateWaitingForBatch, StateWaitingForTxs:
default:
invalidState = true
}
// Make sure we are still processing the right round.
if round != n.commonNode.CurrentBlock.Header.Round {
invalidState = true
}
if invalidState {
n.logger.Info("not requesting proposer timeout",
"height", n.commonNode.Height,
"current_block_round", n.commonNode.CurrentBlock.Header.Round,
"proposing_round", round,
"state", n.state,
)
n.commonNode.CrossNode.Unlock()
return
}
n.commonNode.CrossNode.Unlock()
err := consensus.SignAndSubmitTx(roundCtx, n.commonNode.Consensus, n.commonNode.Identity.NodeSigner, tx)
switch err {
case nil:
n.logger.Info("executor timeout request finalized",
"height", n.commonNode.Height,
"current_block_height", currentBlockHeight,
"proposer_timeout", proposerTimeout,
)
default:
n.logger.Error("failed to submit executor timeout request",
"height", n.commonNode.Height,
"current_block_height", currentBlockHeight,
"err", err,
)
n.commonNode.CrossNode.Lock()
n.proposingTimeout = false
n.commonNode.CrossNode.Unlock()
}
}(n.commonNode.CurrentBlock.Header.Round)
return nil
}
func (n *Node) getRtStateAndRoundResults(ctx context.Context, height int64) (*roothash.RuntimeState, *roothash.RoundResults, error) {
rq := &roothash.RuntimeRequest{
RuntimeID: n.commonNode.Runtime.ID(),
Height: height,
}
state, err := n.commonNode.Consensus.RootHash().GetRuntimeState(ctx, rq)
if err != nil {
n.logger.Error("failed to query runtime state",
"err", err,
"height", height,
)
return nil, nil, err
}
roundResults, err := n.commonNode.Consensus.RootHash().GetLastRoundResults(ctx, rq)
if err != nil {
n.logger.Error("failed to query round last normal round results",
"err", err,
"height", height,
)
return nil, nil, err
}
return state, roundResults, nil
}
func (n *Node) handleScheduleBatch(force bool) { //nolint: gocyclo
roundCtx, epoch, rtState, roundResults, blk, lb, err := func() (
context.Context,
*committee.EpochSnapshot,
*roothash.RuntimeState,
*roothash.RoundResults,
*block.Block,
*consensus.LightBlock,
error,
) {
n.commonNode.CrossNode.Lock()
defer n.commonNode.CrossNode.Unlock()
roundCtx := n.roundCtx
// Check if we are in a suitable state for scheduling a batch.
switch n.state.(type) {
case StateWaitingForBatch:
// We are waiting for a batch.
case StateWaitingForTxs:
// We are waiting for transactions. Note that this means we are not a transaction
// scheduler and so we won't actually be able to schedule anything. But we should still
// propose a timeout if the transaction scheduler proposed something that nobody has.
default:
return roundCtx, nil, nil, nil, nil, nil, errIncorrectState
}
if n.commonNode.CurrentBlock == nil {
return roundCtx, nil, nil, nil, nil, nil, errNoBlocks
}
epoch := n.commonNode.Group.GetEpochSnapshot()
// If we are not an executor worker in this epoch, we don't need to do anything.
if !epoch.IsExecutorWorker() {
return roundCtx, nil, nil, nil, nil, nil, errNotExecutor
}
rtState, roundResults, err := n.getRtStateAndRoundResults(roundCtx, n.commonNode.CurrentBlockHeight)
if err != nil {
return roundCtx, nil, nil, nil, nil, nil, err
}
return roundCtx, epoch, rtState, roundResults, n.commonNode.CurrentBlock, n.commonNode.CurrentConsensusBlock, nil
}()
if err != nil {
n.logger.Debug("not scheduling a batch",
"err", err,
)
return
}
// Update per round scheduler parameters if needed.
if err = n.updateBatchWeightLimits(roundCtx, blk, lb, epoch.GetEpochNumber()); err != nil {
n.logger.Error("failed updating batch weight limits",
"err", err,
)
}
// Fetch incoming message queue metadata to see if there's any queued messages.
inMsgMeta, err := n.commonNode.Consensus.RootHash().GetIncomingMessageQueueMeta(roundCtx, &roothash.RuntimeRequest{
RuntimeID: n.commonNode.Runtime.ID(),
// We make the check at the latest height even though we will later only look at the last
// height. This will make sure that any messages eventually get processed even if there are
// no other runtime transactions being sent. In the worst case this will result in an empty
// block being generated.
Height: consensus.HeightLatest,
})
if err != nil {
n.logger.Error("failed to fetch incoming runtime message queue metadata",
"err", err,
)
return
}
// Check what the runtime supports.
rt := n.commonNode.GetHostedRuntime()
if rt == nil {
n.logger.Debug("not scheduling a batch as the runtime is not yet ready")
return
}
rtInfo, err := rt.GetInfo(roundCtx)
if err != nil {
n.logger.Warn("not scheduling a batch as the runtime is broken",
"err", err,
)
return
}
var batch []*transaction.CheckedTransaction
switch {
case epoch.IsTransactionScheduler(blk.Header.Round) && rtInfo.Features.HasScheduleControl():
// The runtime supports schedule control and we are the scheduler in this round.
batch = n.commonNode.TxPool.GetPrioritizedBatch(nil, rtInfo.Features.ScheduleControl.InitialBatchSize)
default:
// Just ask the scheduler for a batch of transactions.
batch = n.commonNode.TxPool.GetScheduledBatch(force)
}
// Ask the scheduler to get a batch of transactions for us and see if we should be proposing
// a new batch to other nodes.
switch {
case len(batch) > 0:
// We have some transactions, schedule batch.
case force && len(roundResults.Messages) > 0:
// We have runtime message results (and batch timeout expired), schedule batch.
case force && inMsgMeta.Size > 0:
// We have queued incoming runtime messages (and batch timeout expired), schedule batch.
case rtState.LastNormalRound == rtState.GenesisBlock.Header.Round:
// This is the runtime genesis, schedule batch.
case force && rtState.LastNormalHeight < epoch.GetEpochHeight():
// No block in this epoch processed by runtime yet, schedule batch.
default:
// No need to schedule a batch.
return
}
// If we are an executor and not a scheduler try proposing a timeout.
if !epoch.IsTransactionScheduler(blk.Header.Round) {
n.logger.Debug("proposing a timeout",
"round", blk.Header.Round,
"batch_size", len(batch),
"round_results", roundResults,
)
err = func() error {
n.commonNode.CrossNode.Lock()
defer n.commonNode.CrossNode.Unlock()
// Make sure we are still in the right state.
switch n.state.(type) {
case StateWaitingForBatch:
case StateWaitingForTxs:
default:
return errIncorrectState
}
// Make sure we are still processing the right round.
if blk.Header.Round != n.commonNode.CurrentBlock.Header.Round {
return errIncorrectState
}
return n.proposeTimeoutLocked(roundCtx)
}()
switch err {
case nil:
case errIncorrectState:
return
default:
n.logger.Error("error proposing a timeout",
"err", err,
)
}
// If we are not a transaction scheduler, we can't really schedule.
n.logger.Debug("not scheduling a batch as we are not a transaction scheduler")
return
}
// If the runtime supports schedule control we ask the runtime to schedule the batch and then
// propose that.
if rtInfo.Features.HasScheduleControl() {
n.startRuntimeBatchSchedulingLocked(rtState, roundResults, rt, batch)
return
}
// Runtime does not support scheduling control, do our own scheduling.
n.logger.Debug("runtime does not support scheduling control, scheduling batch",
"batch_size", len(batch),
"round_results", roundResults,
)
// Scheduler node starts batch processing.
// Generate the initial I/O root containing only the inputs (outputs and
// tags will be added later by the executor nodes).
emptyRoot := storage.Root{
Namespace: blk.Header.Namespace,
Version: blk.Header.Round + 1,
Type: storage.RootTypeIO,
}
emptyRoot.Hash.Empty()
ioTree := transaction.NewTree(nil, emptyRoot)
defer ioTree.Close()
rawBatch := make(transaction.RawBatch, len(batch))
txHashes := make([]hash.Hash, len(batch))
for idx, tx := range batch {
if err = ioTree.AddTransaction(roundCtx, transaction.Transaction{Input: tx.Raw(), BatchOrder: uint32(idx)}, nil); err != nil {
n.logger.Error("failed to create I/O tree",
"err", err,
)
return
}
rawBatch[idx] = tx.Raw()
txHashes[idx] = tx.Hash()
}
// Mark any proposed transactions.
n.commonNode.TxPool.PromoteProposedBatch(txHashes)
ioWriteLog, ioRoot, err := ioTree.Commit(roundCtx)
if err != nil {
n.logger.Error("failed to create I/O tree",
"err", err,
)
return
}
// Commit I/O tree to local storage.
if err = n.schedulerStoreTransactions(roundCtx, blk, ioWriteLog, ioRoot); err != nil {
n.logger.Error("failed to commit I/O tree to storage",
"err", err,
)
return
}
n.commonNode.CrossNode.Lock()
defer n.commonNode.CrossNode.Unlock()
// Make sure we are still in the right state/round.
if _, ok := n.state.(StateWaitingForBatch); !ok || blk.Header.Round != n.commonNode.CurrentBlock.Header.Round {
n.logger.Error("new state or round since started the dispatch",
"state", n.state,
"expected_round", blk.Header.Round,
"round", n.commonNode.CurrentBlock.Header.Round,
)
return
}
proposal, err := n.schedulerCreateProposalLocked(roundCtx, ioRoot, txHashes)
if err != nil {
n.logger.Error("failed to create proposal",
"err", err,
)
return
}
// Also process the batch locally.
n.maybeStartProcessingBatchLocked(&unresolvedBatch{
proposal: proposal,
batch: rawBatch,
})
}
func (n *Node) schedulerStoreTransactions(ctx context.Context, blk *block.Block, inputWriteLog storage.WriteLog, inputRoot hash.Hash) error {
var emptyRoot hash.Hash
emptyRoot.Empty()
return n.storage.Apply(ctx, &storage.ApplyRequest{
Namespace: blk.Header.Namespace,
RootType: storage.RootTypeIO,
SrcRound: blk.Header.Round + 1,
SrcRoot: emptyRoot,
DstRound: blk.Header.Round + 1,
DstRoot: inputRoot,
WriteLog: inputWriteLog,
})
}
func (n *Node) schedulerCreateProposalLocked(ctx context.Context, inputRoot hash.Hash, txHashes []hash.Hash) (*commitment.Proposal, error) {
blk := n.commonNode.CurrentBlock
// Create new proposal.
proposal := &commitment.Proposal{
NodeID: n.commonNode.Identity.NodeSigner.Public(),
Header: commitment.ProposalHeader{
Round: blk.Header.Round + 1,
PreviousHash: blk.Header.EncodedHash(),
BatchHash: inputRoot,
},
Batch: txHashes,
}
if err := proposal.Sign(n.commonNode.Identity.NodeSigner, blk.Header.Namespace); err != nil {
return nil, fmt.Errorf("failed to sign proposal header: %w", err)
}
n.logger.Debug("dispatching a new batch proposal",
"input_root", inputRoot,
"batch_size", len(txHashes),
)
n.commonNode.P2P.PublishCommittee(ctx, n.commonNode.Runtime.ID(), &p2p.CommitteeMessage{
Epoch: n.commonNode.CurrentEpoch,
Proposal: proposal,
})
crash.Here(crashPointBatchPublishAfter)
return proposal, nil
}
func (n *Node) startRuntimeBatchSchedulingLocked(
rtState *roothash.RuntimeState,
roundResults *roothash.RoundResults,
rt host.RichRuntime,
batch []*transaction.CheckedTransaction,
) {
n.logger.Debug("asking runtime to schedule batch",
"initial_batch_size", len(batch),
)
// Create batch processing context and channel for receiving the response.
ctx, cancel := context.WithCancel(n.roundCtx)
done := make(chan *processedBatch, 1)
batchStartTime := time.Now()
n.transitionLocked(StateProcessingBatch{&unresolvedBatch{}, batchStartTime, cancel, done, protocol.ExecutionModeSchedule})
// Request the worker host to process a batch. This is done in a separate
// goroutine so that the committee node can continue processing blocks.
blk := n.commonNode.CurrentBlock
consensusBlk := n.commonNode.CurrentConsensusBlock
epoch := n.commonNode.CurrentEpoch
go func() {
defer close(done)
initialBatch := make([][]byte, 0, len(batch))
for _, tx := range batch {
initialBatch = append(initialBatch, tx.Raw())
}
// Ask the runtime to execute the batch.
rsp, err := n.runtimeExecuteTxBatch(
ctx,
rt,
protocol.ExecutionModeSchedule,
epoch,
consensusBlk,
blk,
rtState,
roundResults,
hash.Hash{}, // IORoot is ignored as it is yet to be determined.
initialBatch,
)
if err != nil {
n.logger.Error("runtime batch execution failed",
"err", err,
)
return
}
// Remove any rejected transactions.
n.commonNode.TxPool.RemoveTxBatch(rsp.TxRejectHashes)
// Mark any proposed transactions.
n.commonNode.TxPool.PromoteProposedBatch(rsp.TxHashes)
// Submit response to the executor worker.
done <- &processedBatch{
computed: &rsp.Batch,
txHashes: rsp.TxHashes,
txInputRoot: rsp.TxInputRoot,
txInputWriteLog: rsp.TxInputWriteLog,
}
}()
}
// Guarded by n.commonNode.CrossNode.
func (n *Node) maybeStartProcessingBatchLocked(batch *unresolvedBatch) {
epoch := n.commonNode.Group.GetEpochSnapshot()
switch {
case epoch.IsExecutorWorker():
// Worker, start processing immediately.
n.startProcessingBatchLocked(batch)
case epoch.IsExecutorBackupWorker():
// Backup worker, wait for discrepancy event.
state, ok := n.state.(StateWaitingForBatch)
if ok && state.pendingEvent != nil {
// We have already received a discrepancy event, start processing immediately.
n.logger.Info("already received a discrepancy event, start processing batch")
n.startProcessingBatchLocked(batch)
return
}
n.transitionLocked(StateWaitingForEvent{batch: batch})
default:
// Currently not a member of an executor committee, log.
n.logger.Debug("not an executor committee member, ignoring batch")
}
}
func (n *Node) startLocalStorageReplication(
ctx context.Context,
blk *block.Block,
ioRootHash hash.Hash,
batch transaction.RawBatch,
) <-chan error {
ch := make(chan error, 1)
ioRoot := storage.Root{
Namespace: blk.Header.Namespace,
Version: blk.Header.Round + 1,
Type: storage.RootTypeIO,
Hash: ioRootHash,
}
// If we have a local storage node, replicate batch locally so we will be able to Apply
// locally later when proposing a batch. This also avoids needless replication for things
// that we already have.
replicateIO := make(chan error)
go func() {
defer close(replicateIO)
// Check if the root is already present as in this case no replication is needed.
if n.storage.NodeDB().HasRoot(ioRoot) {
replicateIO <- nil
return
}
n.logger.Debug("replicating I/O root locally",
"io_root", ioRoot,
)
emptyRoot := ioRoot
emptyRoot.Hash.Empty()
ioTree := transaction.NewTree(nil, emptyRoot)
defer ioTree.Close()
for idx, tx := range batch {
if err := ioTree.AddTransaction(ctx, transaction.Transaction{Input: tx, BatchOrder: uint32(idx)}, nil); err != nil {
n.logger.Error("failed to create I/O tree",
"err", err,
)
replicateIO <- err
return
}
}
ioWriteLog, ioRootHashCheck, err := ioTree.Commit(ctx)
if err != nil {
n.logger.Error("failed to create I/O tree",
"err", err,
)
replicateIO <- err
return
}
if !ioRootHashCheck.Equal(&ioRootHash) {
n.logger.Error("inconsistent I/O root",
"io_root_hash", ioRootHashCheck,
"expected", ioRootHash,