-
Notifications
You must be signed in to change notification settings - Fork 115
/
Copy pathroothash.go
947 lines (815 loc) · 26.6 KB
/
roothash.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
// Package roothash implements the CometBFT backed roothash backend.
package roothash
import (
"context"
"errors"
"fmt"
"sync"
cmtabcitypes "github.com/cometbft/cometbft/abci/types"
cmtpubsub "github.com/cometbft/cometbft/libs/pubsub"
cmtrpctypes "github.com/cometbft/cometbft/rpc/core/types"
cmttypes "github.com/cometbft/cometbft/types"
"github.com/oasisprotocol/oasis-core/go/common"
"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/pubsub"
eventsAPI "github.com/oasisprotocol/oasis-core/go/consensus/api/events"
tmapi "github.com/oasisprotocol/oasis-core/go/consensus/cometbft/api"
app "github.com/oasisprotocol/oasis-core/go/consensus/cometbft/apps/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/roothash/api/message"
runtimeRegistry "github.com/oasisprotocol/oasis-core/go/runtime/registry"
)
const (
crashPointBlockBeforeIndex = "roothash.before_index"
reindexWriteBatchSize = 1000
)
// ServiceClient is the roothash service client interface.
type ServiceClient interface {
api.Backend
tmapi.ServiceClient
}
type runtimeBrokers struct {
blockNotifier *pubsub.Broker
eventNotifier *pubsub.Broker
ecNotifier *pubsub.Broker
}
type trackedRuntime struct {
runtimeID common.Namespace
height int64
blockHistory api.BlockHistory
reindexDone bool
}
type cmdTrackRuntime struct {
runtimeID common.Namespace
blockHistory api.BlockHistory
}
type serviceClient struct {
tmapi.BaseServiceClient
sync.RWMutex
ctx context.Context
logger *logging.Logger
backend tmapi.Backend
querier *app.QueryFactory
allBlockNotifier *pubsub.Broker
runtimeNotifiers map[common.Namespace]*runtimeBrokers
genesisBlocks map[common.Namespace]*block.Block
queryCh chan cmtpubsub.Query
cmdCh chan interface{}
trackedRuntime map[common.Namespace]*trackedRuntime
pruneHandler *pruneHandler
}
// Implements api.Backend.
func (sc *serviceClient) GetGenesisBlock(ctx context.Context, request *api.RuntimeRequest) (*block.Block, error) {
// First check if we have the genesis blocks cached. They are immutable so easy
// to cache to avoid repeated requests to the CometBFT app.
sc.RLock()
if blk := sc.genesisBlocks[request.RuntimeID]; blk != nil {
sc.RUnlock()
return blk, nil
}
sc.RUnlock()
q, err := sc.querier.QueryAt(ctx, request.Height)
if err != nil {
return nil, err
}
blk, err := q.GenesisBlock(ctx, request.RuntimeID)
if err != nil {
return nil, err
}
// Update the genesis block cache.
sc.Lock()
sc.genesisBlocks[request.RuntimeID] = blk
sc.Unlock()
return blk, nil
}
// Implements api.Backend.
func (sc *serviceClient) GetLatestBlock(ctx context.Context, request *api.RuntimeRequest) (*block.Block, error) {
return sc.getLatestBlockAt(ctx, request.RuntimeID, request.Height)
}
func (sc *serviceClient) getLatestBlockAt(ctx context.Context, runtimeID common.Namespace, height int64) (*block.Block, error) {
q, err := sc.querier.QueryAt(ctx, height)
if err != nil {
return nil, err
}
return q.LatestBlock(ctx, runtimeID)
}
// Implements api.Backend.
func (sc *serviceClient) GetRuntimeState(ctx context.Context, request *api.RuntimeRequest) (*api.RuntimeState, error) {
q, err := sc.querier.QueryAt(ctx, request.Height)
if err != nil {
return nil, err
}
return q.RuntimeState(ctx, request.RuntimeID)
}
// Implements api.Backend.
func (sc *serviceClient) GetLastRoundResults(ctx context.Context, request *api.RuntimeRequest) (*api.RoundResults, error) {
q, err := sc.querier.QueryAt(ctx, request.Height)
if err != nil {
return nil, err
}
return q.LastRoundResults(ctx, request.RuntimeID)
}
func (sc *serviceClient) GetRoundRoots(ctx context.Context, request *api.RoundRootsRequest) (*api.RoundRoots, error) {
q, err := sc.querier.QueryAt(ctx, request.Height)
if err != nil {
return nil, err
}
return q.RoundRoots(ctx, request.RuntimeID, request.Round)
}
func (sc *serviceClient) GetPastRoundRoots(ctx context.Context, request *api.RuntimeRequest) (map[uint64]api.RoundRoots, error) {
q, err := sc.querier.QueryAt(ctx, request.Height)
if err != nil {
return nil, err
}
return q.PastRoundRoots(ctx, request.RuntimeID)
}
// Implements api.Backend.
func (sc *serviceClient) GetIncomingMessageQueueMeta(ctx context.Context, request *api.RuntimeRequest) (*message.IncomingMessageQueueMeta, error) {
q, err := sc.querier.QueryAt(ctx, request.Height)
if err != nil {
return nil, err
}
return q.IncomingMessageQueueMeta(ctx, request.RuntimeID)
}
// Implements api.Backend.
func (sc *serviceClient) GetIncomingMessageQueue(ctx context.Context, request *api.InMessageQueueRequest) ([]*message.IncomingMessage, error) {
q, err := sc.querier.QueryAt(ctx, request.Height)
if err != nil {
return nil, err
}
return q.IncomingMessageQueue(ctx, request.RuntimeID, request.Offset, request.Limit)
}
// Implements api.Backend.
func (sc *serviceClient) WatchBlocks(_ context.Context, id common.Namespace) (<-chan *api.AnnotatedBlock, pubsub.ClosableSubscription, error) {
notifiers := sc.getRuntimeNotifiers(id)
sub := notifiers.blockNotifier.Subscribe()
ch := make(chan *api.AnnotatedBlock)
sub.Unwrap(ch)
// Start tracking this runtime if we are not tracking it yet.
if err := sc.trackRuntime(sc.ctx, id, nil); err != nil {
sub.Close()
return nil, nil, err
}
return ch, sub, nil
}
func (sc *serviceClient) WatchAllBlocks() (<-chan *block.Block, *pubsub.Subscription) {
sub := sc.allBlockNotifier.Subscribe()
ch := make(chan *block.Block)
sub.Unwrap(ch)
return ch, sub
}
// Implements api.Backend.
func (sc *serviceClient) WatchEvents(_ context.Context, id common.Namespace) (<-chan *api.Event, pubsub.ClosableSubscription, error) {
notifiers := sc.getRuntimeNotifiers(id)
sub := notifiers.eventNotifier.Subscribe()
ch := make(chan *api.Event)
sub.Unwrap(ch)
// Start tracking this runtime if we are not tracking it yet.
if err := sc.trackRuntime(sc.ctx, id, nil); err != nil {
sub.Close()
return nil, nil, err
}
return ch, sub, nil
}
// Implements api.Backend.
func (sc *serviceClient) WatchExecutorCommitments(_ context.Context, id common.Namespace) (<-chan *commitment.ExecutorCommitment, pubsub.ClosableSubscription, error) {
notifiers := sc.getRuntimeNotifiers(id)
sub := notifiers.ecNotifier.Subscribe()
ch := make(chan *commitment.ExecutorCommitment)
sub.Unwrap(ch)
// Start tracking this runtime if we are not tracking it yet.
if err := sc.trackRuntime(sc.ctx, id, nil); err != nil {
sub.Close()
return nil, nil, err
}
return ch, sub, nil
}
// Implements api.Backend.
func (sc *serviceClient) TrackRuntime(ctx context.Context, history api.BlockHistory) error {
sc.pruneHandler.trackRuntime(history)
return sc.trackRuntime(ctx, history.RuntimeID(), history)
}
func (sc *serviceClient) trackRuntime(ctx context.Context, id common.Namespace, history api.BlockHistory) error {
cmd := &cmdTrackRuntime{
runtimeID: id,
blockHistory: history,
}
select {
case sc.cmdCh <- cmd:
case <-ctx.Done():
return ctx.Err()
}
return nil
}
// Implements api.Backend.
func (sc *serviceClient) StateToGenesis(ctx context.Context, height int64) (*api.Genesis, error) {
q, err := sc.querier.QueryAt(ctx, height)
if err != nil {
return nil, err
}
return q.Genesis(ctx)
}
func (sc *serviceClient) ConsensusParameters(ctx context.Context, height int64) (*api.ConsensusParameters, error) {
q, err := sc.querier.QueryAt(ctx, height)
if err != nil {
return nil, err
}
return q.ConsensusParameters(ctx)
}
func (sc *serviceClient) getEvents(ctx context.Context, height int64, txns [][]byte) ([]*api.Event, error) {
// Get block results at given height.
var results *cmtrpctypes.ResultBlockResults
results, err := sc.backend.GetBlockResults(ctx, height)
if err != nil {
sc.logger.Error("failed to get cometbft block results",
"err", err,
"height", height,
)
return nil, err
}
var events []*api.Event
// Decode events from block results (at the beginning of the block).
blockEvs, err := EventsFromCometBFT(nil, results.Height, results.BeginBlockEvents)
if err != nil {
return nil, err
}
events = append(events, blockEvs...)
// Decode events from transaction results.
for txIdx, txResult := range results.TxsResults {
// The order of transactions in txns and results.TxsResults is
// supposed to match, so the same index in both slices refers to the
// same transaction.
var tx cmttypes.Tx
if txns != nil {
tx = txns[txIdx]
}
evs, txErr := EventsFromCometBFT(tx, results.Height, txResult.Events)
if txErr != nil {
return nil, txErr
}
events = append(events, evs...)
}
// Decode events from block results (at the end of the block).
blockEvs, err = EventsFromCometBFT(nil, results.Height, results.EndBlockEvents)
if err != nil {
return nil, err
}
events = append(events, blockEvs...)
return events, nil
}
// Implements api.Backend.
func (sc *serviceClient) GetEvents(ctx context.Context, height int64) ([]*api.Event, error) {
// Get transactions at given height.
txns, err := sc.backend.GetTransactions(ctx, height)
if err != nil {
sc.logger.Error("failed to get cometbft transactions",
"err", err,
"height", height,
)
return nil, err
}
return sc.getEvents(ctx, height, txns)
}
// Implements api.Backend.
func (sc *serviceClient) Cleanup() {
}
func (sc *serviceClient) getRuntimeNotifiers(id common.Namespace) *runtimeBrokers {
sc.Lock()
defer sc.Unlock()
notifiers := sc.runtimeNotifiers[id]
if notifiers == nil {
notifiers = &runtimeBrokers{
blockNotifier: pubsub.NewBroker(true),
eventNotifier: pubsub.NewBroker(false),
ecNotifier: pubsub.NewBroker(false),
}
sc.runtimeNotifiers[id] = notifiers
}
return notifiers
}
func (sc *serviceClient) reindexBlocks(ctx context.Context, currentHeight int64, bh api.BlockHistory) (uint64, error) {
lastRound := api.RoundInvalid
if currentHeight <= 0 {
return lastRound, nil
}
runtimeID := bh.RuntimeID()
logger := sc.logger.With("runtime_id", runtimeID)
var err error
var lastHeight int64
if lastHeight, err = bh.LastConsensusHeight(); err != nil {
logger.Error("failed to get last indexed height",
"err", err,
)
return 0, fmt.Errorf("failed to get last indexed height: %w", err)
}
// +1 since we want the last non-seen height.
lastHeight++
// Take prune strategy into account.
lastRetainedHeight, err := sc.backend.GetLastRetainedVersion(ctx)
if err != nil {
return 0, fmt.Errorf("failed to get last retained height: %w", err)
}
if lastHeight < lastRetainedHeight {
logger.Debug("last height pruned, skipping until last retained",
"last_retained_height", lastRetainedHeight,
"last_height", lastHeight,
)
lastHeight = lastRetainedHeight
}
// Take initial genesis height into account.
genesisDoc, err := sc.backend.GetGenesisDocument(ctx)
if err != nil {
return 0, fmt.Errorf("failed to get genesis document: %w", err)
}
if lastHeight < genesisDoc.Height {
lastHeight = genesisDoc.Height
}
// Scan all blocks between last indexed height and current height.
logger.Info("reindexing blocks",
"last_height", lastHeight,
"current_height", currentHeight,
logging.LogEvent, api.LogEventHistoryReindexing,
)
for height := lastHeight; height <= currentHeight; height += reindexWriteBatchSize {
end := height + reindexWriteBatchSize - 1
if end > currentHeight {
end = currentHeight
}
last, err := sc.reindexBatch(ctx, runtimeID, bh, height, end)
if err != nil {
return 0, fmt.Errorf("failed to reindex batch: %w", err)
}
if last != api.RoundInvalid {
// New rounds indexed.
lastRound = last
}
}
if lastRound == api.RoundInvalid {
logger.Debug("no new round reindexed, return latest known round")
switch blk, err := bh.GetCommittedBlock(ctx, api.RoundLatest); err {
case api.ErrNotFound:
case nil:
lastRound = blk.Header.Round
default:
return lastRound, fmt.Errorf("failed to get latest block: %w", err)
}
}
logger.Info("block reindex complete",
"last_round", lastRound,
)
return lastRound, nil
}
func (sc *serviceClient) reindexBatch(
ctx context.Context,
runtimeID common.Namespace,
bh api.BlockHistory,
start int64,
end int64,
) (uint64, error) {
logger := sc.logger.With("runtime_id", runtimeID)
logger.Debug("reindexing batch",
"start", start,
"end", end,
)
lastRound := api.RoundInvalid
var blocks []*api.AnnotatedBlock
var roundResults []*api.RoundResults
for height := start; height <= end; height++ {
results, err := sc.backend.GetBlockResults(ctx, height)
if err != nil {
// XXX: could soft-fail first few heights in case more heights were
// pruned right after the GetLastRetainedVersion query.
logger.Error("failed to get cometbft block results",
"err", err,
"height", height,
)
return 0, fmt.Errorf("failed to get cometbft block results: %w", err)
}
// Index block.
tmEvents := results.BeginBlockEvents
for _, txResults := range results.TxsResults {
tmEvents = append(tmEvents, txResults.Events...)
}
tmEvents = append(tmEvents, results.EndBlockEvents...)
for _, tmEv := range tmEvents {
if tmEv.GetType() != app.EventType {
continue
}
var evRtID *common.Namespace
var ev *api.FinalizedEvent
for _, pair := range tmEv.GetAttributes() {
key := pair.GetKey()
val := pair.GetValue()
switch {
case eventsAPI.IsAttributeKind(key, &api.RuntimeIDAttribute{}):
if evRtID != nil {
return 0, fmt.Errorf("roothash: duplicate runtime ID attribute")
}
var rtAttribute api.RuntimeIDAttribute
if err = eventsAPI.DecodeValue(val, &rtAttribute); err != nil {
return 0, fmt.Errorf("roothash: corrupt runtime ID: %w", err)
}
evRtID = &rtAttribute.ID
case eventsAPI.IsAttributeKind(key, &api.FinalizedEvent{}):
var e api.FinalizedEvent
if err = eventsAPI.DecodeValue(val, &e); err != nil {
logger.Error("failed to unmarshal finalized event",
"err", err,
"height", height,
)
return 0, fmt.Errorf("failed to unmarshal finalized event: %w", err)
}
ev = &e
default:
}
}
// Only process finalized events.
if ev == nil {
continue
}
// Only process events for the given runtime.
if !evRtID.Equal(&runtimeID) {
continue
}
annBlk, rr, err := sc.fetchFinalizedRound(ctx, height, runtimeID, &ev.Round)
if err != nil {
return 0, fmt.Errorf("failed to fetch roothash finalized round: %w", err)
}
blocks = append(blocks, annBlk)
roundResults = append(roundResults, rr)
logger.Debug("block added to batch",
"height", height,
"round", annBlk.Block.Header.Round,
)
lastRound = ev.Round
}
}
// Do not notify watchers during history reindex.
err := bh.CommitBatch(blocks, roundResults, false)
if err != nil {
logger.Error("failed to commit batch",
"err", err,
"start", start,
"end", end,
)
return 0, fmt.Errorf("failed to commit batch: %w", err)
}
return lastRound, nil
}
// Implements api.ServiceClient.
func (sc *serviceClient) ServiceDescriptor() tmapi.ServiceDescriptor {
return tmapi.NewServiceDescriptor(api.ModuleName, app.EventType, sc.queryCh, sc.cmdCh)
}
// Implements api.ServiceClient.
func (sc *serviceClient) DeliverCommand(ctx context.Context, height int64, cmd interface{}) error {
switch c := cmd.(type) {
case *cmdTrackRuntime:
// Request to track a new runtime.
etr := sc.trackedRuntime[c.runtimeID]
if etr != nil {
// Ignore duplicate runtime tracking requests unless this updates the block history.
if etr.blockHistory != nil || c.blockHistory == nil {
break
}
} else {
sc.logger.Debug("tracking new runtime",
"runtime_id", c.runtimeID,
"height", height,
)
}
// We need to start watching a new block history.
tr := &trackedRuntime{
runtimeID: c.runtimeID,
blockHistory: c.blockHistory,
}
sc.trackedRuntime[c.runtimeID] = tr
// Request subscription to events for this runtime.
sc.queryCh <- app.QueryForRuntime(tr.runtimeID)
// Resolve the correct block finalization height to use for the latest block at the current
// height as the current height may not correspond to the latest block finalization height.
rs, err := sc.GetRuntimeState(ctx, &api.RuntimeRequest{
RuntimeID: tr.runtimeID,
Height: height,
})
if err != nil {
sc.logger.Warn("failed to get runtime state for latest block",
"err",
"runtime_id", tr.runtimeID,
"height", height,
)
return nil
}
// Emit latest block.
if err := sc.processFinalizedEvent(ctx, rs.LastBlockHeight, tr.runtimeID, nil); err != nil {
sc.logger.Warn("failed to emit latest block",
"err", err,
"runtime_id", tr.runtimeID,
"height", height,
)
}
// Make sure we reindex again when receiving the first event.
tr.reindexDone = false
default:
return fmt.Errorf("roothash: unknown command: %T", cmd)
}
return nil
}
// Implements api.ServiceClient.
func (sc *serviceClient) DeliverEvent(ctx context.Context, height int64, tx cmttypes.Tx, ev *cmtabcitypes.Event) error {
events, err := EventsFromCometBFT(tx, height, []cmtabcitypes.Event{*ev})
if err != nil {
return fmt.Errorf("roothash: failed to process cometbft events: %w", err)
}
for _, ev := range events {
// Notify non-finalized events.
if ev.Finalized == nil {
notifiers := sc.getRuntimeNotifiers(ev.RuntimeID)
notifiers.eventNotifier.Broadcast(ev)
continue
}
// Only process finalized events for tracked runtimes.
if sc.trackedRuntime[ev.RuntimeID] == nil {
continue
}
if err = sc.processFinalizedEvent(ctx, height, ev.RuntimeID, &ev.Finalized.Round); err != nil { //nolint:gosec
return fmt.Errorf("roothash: failed to process finalized event: %w", err)
}
}
return nil
}
// Implements api.ExecutorCommitmentNotifier.
func (sc *serviceClient) DeliverExecutorCommitment(runtimeID common.Namespace, ec *commitment.ExecutorCommitment) {
notifiers := sc.getRuntimeNotifiers(runtimeID)
notifiers.ecNotifier.Broadcast(ec)
}
func (sc *serviceClient) processFinalizedEvent(
ctx context.Context,
height int64,
runtimeID common.Namespace,
round *uint64,
) (err error) {
tr := sc.trackedRuntime[runtimeID]
if tr == nil {
sc.logger.Error("runtime not tracked",
"runtime_id", runtimeID,
"tracked_runtimes", sc.trackedRuntime,
)
return fmt.Errorf("roothash: runtime not tracked: %s", runtimeID)
}
defer func() {
// If there was an error, flag the tracked runtime for reindex.
if err == nil {
return
}
tr.reindexDone = false
}()
if height <= tr.height {
return nil
}
// Process finalized event.
annBlk, roundResults, err := sc.fetchFinalizedRound(ctx, height, runtimeID, round)
if err != nil {
return fmt.Errorf("failed to fetch roothash finalized round: %w", err)
}
// Commit the block to history if needed.
if tr.blockHistory != nil {
crash.Here(crashPointBlockBeforeIndex)
// Perform reindex if required.
lastRound := api.RoundInvalid
if !tr.reindexDone {
// Note that we need to reindex up to the previous height as the current height is
// already being processed right now.
if lastRound, err = sc.reindexBlocks(ctx, height-1, tr.blockHistory); err != nil {
sc.logger.Error("failed to reindex blocks",
"err", err,
"runtime_id", runtimeID,
)
return fmt.Errorf("failed to reindex blocks: %w", err)
}
tr.reindexDone = true
}
// Only commit the block in case it was not already committed during reindex. Note that even
// in case we only reindex up to height-1 this can still happen on the first emitted block
// since that height is not guaranteed to be the one that contains a round finalized event.
if lastRound == api.RoundInvalid || annBlk.Block.Header.Round > lastRound {
sc.logger.Debug("commit block",
"runtime_id", runtimeID,
"height", height,
"round", annBlk.Block.Header.Round,
)
err = tr.blockHistory.Commit(annBlk, roundResults, true)
if err != nil {
sc.logger.Error("failed to commit block to history keeper",
"err", err,
"runtime_id", runtimeID,
"height", height,
"round", annBlk.Block.Header.Round,
)
return fmt.Errorf("failed to commit block to history keeper: %w", err)
}
}
}
notifiers := sc.getRuntimeNotifiers(runtimeID)
notifiers.blockNotifier.Broadcast(annBlk)
sc.allBlockNotifier.Broadcast(annBlk.Block)
tr.height = height
return nil
}
func (sc *serviceClient) fetchFinalizedRound(
ctx context.Context,
height int64,
runtimeID common.Namespace,
round *uint64,
) (*api.AnnotatedBlock, *api.RoundResults, error) {
blk, err := sc.getLatestBlockAt(ctx, runtimeID, height)
if err != nil {
sc.logger.Error("failed to fetch latest block",
"err", err,
"height", height,
"runtime_id", runtimeID,
)
return nil, nil, fmt.Errorf("roothash: failed to fetch latest block: %w", err)
}
if round != nil && blk.Header.Round != *round {
sc.logger.Error("finalized event/query round mismatch",
"block_round", blk.Header.Round,
"event_round", *round,
)
return nil, nil, fmt.Errorf("roothash: finalized event/query round mismatch")
}
roundResults, err := sc.GetLastRoundResults(ctx, &api.RuntimeRequest{
RuntimeID: runtimeID,
Height: height,
})
if err != nil {
sc.logger.Error("failed to fetch round results",
"err", err,
"height", height,
"runtime_id", runtimeID,
)
return nil, nil, fmt.Errorf("roothash: failed to fetch round results: %w", err)
}
annBlk := &api.AnnotatedBlock{
Height: height,
Block: blk,
}
return annBlk, roundResults, nil
}
// EventsFromCometBFT extracts staking events from CometBFT events.
func EventsFromCometBFT(
tx cmttypes.Tx,
height int64,
tmEvents []cmtabcitypes.Event,
) ([]*api.Event, error) {
var txHash hash.Hash
switch tx {
case nil:
txHash.Empty()
default:
txHash = hash.NewFromBytes(tx)
}
var events []*api.Event
var errs error
EventLoop:
for _, tmEv := range tmEvents {
// Ignore events that don't relate to the roothash app.
if tmEv.GetType() != app.EventType {
continue
}
var (
runtimeID *common.Namespace
ev *api.Event
)
for _, pair := range tmEv.GetAttributes() {
key := pair.GetKey()
val := pair.GetValue()
switch {
case eventsAPI.IsAttributeKind(key, &api.FinalizedEvent{}):
// Finalized event.
var e api.FinalizedEvent
if err := eventsAPI.DecodeValue(val, &e); err != nil {
errs = errors.Join(errs, fmt.Errorf("roothash: corrupt Finalized event: %w", err))
continue EventLoop
}
ev = &api.Event{Finalized: &e}
case eventsAPI.IsAttributeKind(key, &api.ExecutionDiscrepancyDetectedEvent{}):
// An execution discrepancy has been detected.
var e api.ExecutionDiscrepancyDetectedEvent
if err := eventsAPI.DecodeValue(val, &e); err != nil {
errs = errors.Join(errs, fmt.Errorf("roothash: corrupt ExecutionDiscrepancyDetected event: %w", err))
continue EventLoop
}
ev = &api.Event{ExecutionDiscrepancyDetected: &e}
case eventsAPI.IsAttributeKind(key, &api.ExecutorCommittedEvent{}):
// An executor commit has been processed.
var e api.ExecutorCommittedEvent
if err := eventsAPI.DecodeValue(val, &e); err != nil {
errs = errors.Join(errs, fmt.Errorf("roothash: corrupt ExecutorComitted event: %w", err))
continue EventLoop
}
ev = &api.Event{ExecutorCommitted: &e}
case eventsAPI.IsAttributeKind(key, &api.InMsgProcessedEvent{}):
// Incoming message processed event.
var e api.InMsgProcessedEvent
if err := eventsAPI.DecodeValue(val, &e); err != nil {
errs = errors.Join(errs, fmt.Errorf("roothash: corrupt InMsgProcessed event: %w", err))
continue EventLoop
}
ev = &api.Event{InMsgProcessed: &e}
case eventsAPI.IsAttributeKind(key, &api.RuntimeIDAttribute{}):
if runtimeID != nil {
errs = errors.Join(errs, fmt.Errorf("roothash: duplicate runtime ID attribute"))
continue EventLoop
}
rtAttribute := api.RuntimeIDAttribute{}
if err := eventsAPI.DecodeValue(val, &rtAttribute); err != nil {
errs = errors.Join(errs, fmt.Errorf("roothash: corrupt runtime ID: %w", err))
continue EventLoop
}
runtimeID = &rtAttribute.ID
default:
errs = errors.Join(errs, fmt.Errorf("roothash: unknown event type: key: %s, val: %s", key, val))
}
}
if runtimeID == nil {
errs = errors.Join(errs, fmt.Errorf("roothash: missing runtime ID attribute"))
continue
}
if ev != nil {
ev.RuntimeID = *runtimeID
ev.Height = height
ev.TxHash = txHash
events = append(events, ev)
}
}
return events, errs
}
type pruneHandler struct {
sync.Mutex
logger *logging.Logger
trackedRuntimes []api.BlockHistory
}
func (ph *pruneHandler) trackRuntime(bh api.BlockHistory) {
ph.Lock()
defer ph.Unlock()
ph.trackedRuntimes = append(ph.trackedRuntimes, bh)
}
// Implements api.StatePruneHandler.
func (ph *pruneHandler) Prune(version uint64) error {
ph.Lock()
defer ph.Unlock()
for _, bh := range ph.trackedRuntimes {
lastHeight, err := bh.LastConsensusHeight()
if err != nil {
ph.logger.Warn("failed to fetch last consensus height for tracked runtime",
"err", err,
"runtime_id", bh.RuntimeID(),
)
// We can't be sure if it is ok to prune this version, so prevent pruning to be safe.
return fmt.Errorf("failed to fetch last consensus height for tracked runtime: %w", err)
}
if version > uint64(lastHeight) {
return fmt.Errorf("version %d not yet indexed for %s", version, bh.RuntimeID())
}
}
return nil
}
// New constructs a new CometBFT-based root hash backend.
func New(
ctx context.Context,
backend tmapi.Backend,
) (ServiceClient, error) {
sc := serviceClient{
ctx: ctx,
logger: logging.GetLogger("cometbft/roothash"),
backend: backend,
allBlockNotifier: pubsub.NewBroker(false),
runtimeNotifiers: make(map[common.Namespace]*runtimeBrokers),
genesisBlocks: make(map[common.Namespace]*block.Block),
queryCh: make(chan cmtpubsub.Query, runtimeRegistry.MaxRuntimeCount),
cmdCh: make(chan interface{}, runtimeRegistry.MaxRuntimeCount),
trackedRuntime: make(map[common.Namespace]*trackedRuntime),
}
// Initialize and register the CometBFT service component.
a := app.New(&sc)
if err := backend.RegisterApplication(a); err != nil {
return nil, err
}
sc.querier = a.QueryFactory().(*app.QueryFactory)
// Register a consensus state prune handler to make sure that we don't prune blocks that haven't
// yet been indexed by the roothash backend.
sc.pruneHandler = &pruneHandler{
logger: logging.GetLogger("cometbft/roothash/prunehandler"),
}
backend.Pruner().RegisterHandler(sc.pruneHandler)
return &sc, nil
}
func init() {
crash.RegisterCrashPoints(
crashPointBlockBeforeIndex,
)
}