-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathconsensus.go
More file actions
1579 lines (1433 loc) · 51.4 KB
/
Copy pathconsensus.go
File metadata and controls
1579 lines (1433 loc) · 51.4 KB
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 consensus implements an analyzer for the consensus layer.
package consensus
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"os"
"reflect"
"strings"
coreCommon "github.com/oasisprotocol/oasis-core/go/common"
"github.com/oasisprotocol/oasis-core/go/common/cbor"
"github.com/oasisprotocol/oasis-core/go/common/crypto/signature"
"github.com/oasisprotocol/oasis-core/go/common/quantity"
"github.com/oasisprotocol/oasis-core/go/consensus/cometbft/crypto"
sdkConfig "github.com/oasisprotocol/oasis-sdk/client-sdk/go/config"
sdkTypes "github.com/oasisprotocol/oasis-sdk/client-sdk/go/types"
"github.com/oasisprotocol/nexus/analyzer/consensus/static"
"github.com/oasisprotocol/nexus/analyzer/util/addresses"
beacon "github.com/oasisprotocol/nexus/coreapi/v22.2.11/beacon/api"
"github.com/oasisprotocol/nexus/coreapi/v22.2.11/consensus/api/transaction"
staking "github.com/oasisprotocol/nexus/coreapi/v22.2.11/staking/api"
cometbft "github.com/oasisprotocol/nexus/coreapi/v24.0/consensus/cometbft/api"
"github.com/oasisprotocol/nexus/analyzer"
"github.com/oasisprotocol/nexus/analyzer/block"
"github.com/oasisprotocol/nexus/analyzer/queries"
"github.com/oasisprotocol/nexus/analyzer/util"
apiTypes "github.com/oasisprotocol/nexus/api/v1/types"
"github.com/oasisprotocol/nexus/common"
"github.com/oasisprotocol/nexus/config"
"github.com/oasisprotocol/nexus/log"
"github.com/oasisprotocol/nexus/metrics"
"github.com/oasisprotocol/nexus/storage"
"github.com/oasisprotocol/nexus/storage/oasis/nodeapi"
)
const (
consensusAnalyzerName = "consensus"
)
type EventType = apiTypes.ConsensusEventType // alias for brevity
type parsedEvent struct {
eventIdx int
ty EventType
rawBody json.RawMessage
roothashRuntimeID *coreCommon.Namespace
roothashRuntime *common.Runtime
roothashRuntimeRound *uint64
relatedAddresses []staking.Address
}
// OpenSignedTxNoVerify decodes the Transaction inside a Signed transaction
// without verifying the signature. Callers should be sure to check if the
// transaction actually succeeded. Nexus trusts its oasis-node to
// provide the correct transaction result, which will indicate if there was an
// authentication problem. Skipping the verification saves CPU on the analyzer.
// Due to the chain context being global, we cannot verify transactions for
// multiple networks anyway.
func OpenSignedTxNoVerify(signedTx *transaction.SignedTransaction) (*transaction.Transaction, error) {
var tx transaction.Transaction
if err := cbor.Unmarshal(signedTx.Blob, &tx); err != nil {
return nil, fmt.Errorf("signed tx unmarshal: %w", err)
}
return &tx, nil
}
// processor is the block processor for the consensus layer.
type processor struct {
mode analyzer.BlockAnalysisMode
history config.History
source nodeapi.ConsensusApiLite
network sdkConfig.Network
target storage.TargetStorage
logger *log.Logger
metrics metrics.AnalysisMetrics
}
var _ block.BlockProcessor = (*processor)(nil)
// NewAnalyzer returns a new analyzer for the consensus layer.
func NewAnalyzer(blockRange config.BlockRange, batchSize uint64, mode analyzer.BlockAnalysisMode, history config.History, source nodeapi.ConsensusApiLite, network sdkConfig.Network, target storage.TargetStorage, logger *log.Logger) (analyzer.Analyzer, error) {
processor := &processor{
mode: mode,
history: history,
source: source,
network: network,
target: target,
logger: logger.With("analyzer", consensusAnalyzerName),
metrics: metrics.NewDefaultAnalysisMetrics(consensusAnalyzerName),
}
return block.NewAnalyzer(blockRange, batchSize, mode, consensusAnalyzerName, processor, target, logger)
}
// Implements BlockProcessor interface.
func (m *processor) PreWork(ctx context.Context) error {
batch := &storage.QueryBatch{}
// Register special addresses.
zeroKey := signature.PublicKey{}
zeroKeyAddr := staking.NewAddress(zeroKey).String()
zeroKeyData, err := zeroKey.MarshalBinary()
if err != nil {
panic(fmt.Errorf("zero key marshal binary: %w", err))
}
batch.Queue(
queries.AddressPreimageInsert,
zeroKeyAddr, // oasis1qpg3hpf3vtuueyl8f8jzgsy8clqqw6qgxgurwfy5
staking.AddressV0Context.Identifier, // context_identifier
int32(staking.AddressV0Context.Version), // context_version
zeroKeyData, // address_data
)
if err = m.target.SendBatch(ctx, batch); err != nil {
return err
}
m.logger.Info("registered special addresses")
// Insert static account first activity timestamps.
batch = &storage.QueryBatch{}
if err = static.QueueConsensusAccountsFirstActivity(batch, m.history.ChainName, m.logger); err != nil {
return err
}
if err = m.target.SendBatch(ctx, batch); err != nil {
return err
}
m.logger.Info("inserted static account first active timestamps")
return nil
}
// Implements block.BlockProcessor interface. Downloads and processes the genesis document
// that immediately precedes block `lastFastSyncHeight`+1, i.e. the first slow-sync block
// we're about to process.
// If that block is the first block of a chain (cobalt, damask, etc), we download the chain's
// original genesis document. Otherwise, we download the genesis-formatted state at `lastFastSyncHeight`.
func (m *processor) FinalizeFastSync(ctx context.Context, lastFastSyncHeight int64) error {
// Aggregate append-only tables that were used during fast sync.
if err := m.aggregateFastSyncTables(ctx); err != nil {
return err
}
// Recompute account first activity for all accounts scanned during fast-sync.
batch := &storage.QueryBatch{}
m.logger.Info("computing account first activity for all accounts scanned during fast-sync")
batch.Queue(queries.ConsensusAccountsFirstActivityRecompute)
if err := m.target.SendBatch(ctx, batch); err != nil {
return fmt.Errorf("recomputing consensus accounts first activity: %w", err)
}
// Recompute tx count for all accounts scanned during fast-sync.
batch = &storage.QueryBatch{}
m.logger.Info("computing tx count for all accounts scanned during fast-sync")
batch.Queue(queries.ConsensusAccountTxCountRecompute)
if err := m.target.SendBatch(ctx, batch); err != nil {
return fmt.Errorf("recomputing consensus accounts tx count: %w", err)
}
// Fetch a data snapshot (= genesis doc) from the node; see function docstring.
firstSlowSyncHeight := lastFastSyncHeight + 1
r, err := m.history.RecordForHeight(firstSlowSyncHeight)
if err != nil {
return fmt.Errorf("no history record for first slow-sync height %d: %w", firstSlowSyncHeight, err)
}
var genesisDoc *nodeapi.GenesisDocument
var nodes []nodeapi.Node
if r.GenesisHeight == firstSlowSyncHeight {
m.logger.Info("fetching genesis document before starting with the first block of a chain", "chain_context", r.ChainContext, "genesis_height", r.GenesisHeight)
genesisDoc, err = m.source.GetGenesisDocument(ctx, r.ChainContext)
if err != nil {
return err
}
m.debugDumpGenesisJSON(genesisDoc, r.ArchiveName)
} else {
m.logger.Info("fetching state at last fast-sync height, using StateToGenesis; this can take a while, up to an hour on mainnet", "state_to_genesis_height", lastFastSyncHeight, "chain_genesis_height", r.GenesisHeight, "first_slow_sync_height", firstSlowSyncHeight)
genesisDoc, err = m.source.StateToGenesis(ctx, lastFastSyncHeight)
if err != nil {
return err
}
nodes, err = m.source.GetNodes(ctx, lastFastSyncHeight)
if err != nil {
return err
}
m.debugDumpGenesisJSON(genesisDoc, fmt.Sprintf("%d", lastFastSyncHeight))
}
return m.processGenesis(ctx, genesisDoc, nodes)
}
// Aggregates rows from the temporary, append-only `todo_updates.*` tables, and appropriately updates
// the regular DB tables.
func (m *processor) aggregateFastSyncTables(ctx context.Context) error {
batch := &storage.QueryBatch{}
m.logger.Info("computing epoch boundaries for epochs scanned during fast-sync")
batch.Queue(queries.ConsensusEpochsRecompute)
batch.Queue("DELETE FROM todo_updates.epochs")
batch.Queue(queries.ConsensusBlockSignersFinalize)
batch.Queue("DELETE FROM todo_updates.block_signers")
if err := m.target.SendBatch(ctx, batch); err != nil {
return err
}
return nil
}
// Dumps the genesis document to a JSON file if instructed via env variables. For debug only.
func (m *processor) debugDumpGenesisJSON(genesisDoc *nodeapi.GenesisDocument, heightOrName string) {
debugPath := os.Getenv("NEXUS_DUMP_GENESIS") // can be templatized with "{{height}}"
if debugPath == "" {
return
}
debugPath = strings.ReplaceAll(debugPath, "{{height}}", heightOrName)
prettyJSON, err := json.MarshalIndent(genesisDoc, "", " ")
if err != nil {
m.logger.Error("failed to marshal genesis document", "err", err)
return
}
if err := os.WriteFile(debugPath, prettyJSON, 0o600 /* Permissions: rw------- */); err != nil {
m.logger.Error("failed to write genesis JSON to file", "err", err)
} else {
m.logger.Info("wrote genesis JSON to file", "path", debugPath, "height_or_name", heightOrName)
}
}
// Executes SQL queries to index the contents of the genesis document.
// If nodesOverride is non-nil, it is used instead of the nodes from the genesis document.
func (m *processor) processGenesis(ctx context.Context, genesisDoc *nodeapi.GenesisDocument, nodesOverride []nodeapi.Node) error {
m.logger.Info("processing genesis document")
gen := NewGenesisProcessor(m.logger.With("height", "genesis"))
batch, err := gen.Process(genesisDoc, nodesOverride)
if err != nil {
return err
}
// Debug: log the SQL into a file if requested.
debugPath := os.Getenv("NEXUS_DUMP_GENESIS_SQL")
if debugPath != "" {
queries, err := json.Marshal(batch.Queries())
if err != nil {
return err
}
if err := os.WriteFile(debugPath, queries, 0o600 /* Permissions: rw------- */); err != nil {
gen.logger.Error("failed to write genesis queries to file", "err", err)
} else {
gen.logger.Info("wrote genesis queries to file", "path", debugPath)
}
}
if err := m.target.SendBatch(ctx, batch); err != nil {
return err
}
m.logger.Info("genesis document processed")
return nil
}
// Expands `batch` with DB statements that reflect the contents of `data`.
func (m *processor) queueDbUpdates(batch *storage.QueryBatch, data allData) error {
if err := m.queueBlockInserts(batch, data.BlockData, data.StakingData.TotalSupply); err != nil {
return err
}
for _, f := range []func(*storage.QueryBatch, *consensusBlockData) error{
m.queueEpochInserts,
m.queueTransactionInserts,
} {
if err := f(batch, data.BlockData); err != nil {
return err
}
}
if err := m.queueTxEventInserts(batch, &data); err != nil {
return err
}
for _, f := range []func(*storage.QueryBatch, *registryData) error{
m.queueEntityEvents,
m.queueRuntimeRegistrations,
m.queueRegistryEventInserts,
} {
if err := f(batch, data.RegistryData); err != nil {
return err
}
}
if err := m.queueNodeEvents(batch, data.RegistryData, uint64(data.BlockData.Epoch)); err != nil {
return err
}
for _, f := range []func(*storage.QueryBatch, *stakingData, beacon.EpochTime) error{
m.queueRegularTransfers,
m.queueBurns,
m.queueEscrows,
m.queueAllowanceChanges,
m.queueStakingEventInserts,
m.queueDisbursementTransfers,
} {
if err := f(batch, data.StakingData, data.BeaconData.Epoch); err != nil {
return err
}
}
for _, f := range []func(*storage.QueryBatch, *schedulerData) error{
m.queueValidatorUpdates,
m.queueCommitteeUpdates,
} {
if err := f(batch, data.SchedulerData); err != nil {
return err
}
}
for _, f := range []func(*storage.QueryBatch, *governanceData) error{
m.queueSubmissions,
m.queueExecutions,
m.queueFinalizations,
m.queueVotes,
m.queueGovernanceEventInserts,
} {
if err := f(batch, data.GovernanceData); err != nil {
return err
}
}
for _, f := range []func(*storage.QueryBatch, *rootHashData) error{
m.queueRootHashMessageUpserts,
m.queueRootHashEventInserts,
} {
if err := f(batch, data.RootHashData); err != nil {
return err
}
}
return nil
}
// Implements BlockProcessor interface.
func (m *processor) ProcessBlock(ctx context.Context, uheight uint64) error {
if uheight > math.MaxInt64 {
return fmt.Errorf("height %d is too large", uheight)
}
height := int64(uheight)
batch := &storage.QueryBatch{}
if _, isBlockAbsent := m.history.MissingBlocks[uheight]; !isBlockAbsent {
// Fetch all data.
fetchTimer := m.metrics.BlockFetchLatencies()
data, err := fetchAllData(ctx, m.source, m.network, height, m.mode == analyzer.FastSyncMode)
if err != nil {
return err
}
// We make no observation in case of a data fetch error; those timings are misleading.
fetchTimer.ObserveDuration()
// Process data, prepare updates.
analysisTimer := m.metrics.BlockAnalysisLatencies()
err = m.queueDbUpdates(batch, *data)
analysisTimer.ObserveDuration()
if err != nil {
return err
}
}
// Update indexing progress.
batch.Queue(
queries.IndexingProgress,
height,
consensusAnalyzerName,
m.mode == analyzer.FastSyncMode,
)
// Apply updates to DB.
opName := "process_block_consensus"
timer := m.metrics.DatabaseLatencies(m.target.Name(), opName)
defer timer.ObserveDuration()
if err := m.target.SendBatch(ctx, batch); err != nil {
m.metrics.DatabaseOperations(m.target.Name(), opName, "failure").Inc()
return err
}
m.metrics.DatabaseOperations(m.target.Name(), opName, "success").Inc()
return nil
}
func (m *processor) queueBlockInserts(batch *storage.QueryBatch, data *consensusBlockData, totalSupply *quantity.Quantity) error {
// Prepare a mapping of node consensus addresses.
//
// CometBFT (formerly Tendermint) uses a truncated hash of the entity's
// public key as its address format. Specifically, the address (a
// [20]byte) is the first 20 bytes of the SHA-256 of the public key.
// Since CometBFT is what oasis-core uses for its consensus mechanism,
// these addresses are what we're given in the block metadata for the
// proposer and signers. Because the address derivation is one-way, we
// need a map to convert them to Oasis-style addresses (base64 public
// keys).
consensusToEntity := map[string]signature.PublicKey{}
for _, n := range data.Nodes {
consensusAddress := crypto.PublicKeyToCometBFT(common.Ptr(n.Consensus.ID)).Address().String()
consensusToEntity[consensusAddress] = n.EntityID
}
var cmtMeta cometbft.BlockMeta
if err := cmtMeta.TryUnmarshal(data.BlockHeader.Meta); err != nil {
m.logger.Warn("could not unmarshal block meta, may be incompatible version",
"height", data.BlockHeader.Height,
"err", err,
)
// We just skip indexing the block metadata if we cannot unmarshal it
// and don't stop indexing the rest of the block.
}
var proposerAddr *string
if cmtMeta.Header != nil {
entity, ok := consensusToEntity[cmtMeta.Header.ProposerAddress.String()]
if !ok {
m.logger.Warn("could not convert block proposer address to entity id (address not found)",
"height", data.BlockHeader.Height,
"proposer", cmtMeta.Header.ProposerAddress.String(),
)
} else {
proposerAddr = common.Ptr(entity.String())
}
}
var gasUsed uint64
for _, txr := range data.TransactionsWithResults {
gasUsed += txr.Result.GasUsed
}
batch.Queue(
queries.ConsensusBlockUpsert,
data.BlockHeader.Height,
data.BlockHeader.Hash.Hex(),
data.BlockHeader.Time.UTC(),
len(data.TransactionsWithResults),
data.GasLimit,
gasUsed,
data.SizeLimit,
data.BlockHeader.Size,
data.Epoch,
data.BlockHeader.StateRoot.Namespace.String(),
int64(data.BlockHeader.StateRoot.Version),
data.BlockHeader.StateRoot.Hash.Hex(),
proposerAddr,
totalSupply,
)
if cmtMeta.LastCommit != nil && cmtMeta.LastCommit.BlockID.IsComplete() {
prevSigners := make([]string, 0, len(cmtMeta.LastCommit.Signatures))
for _, cs := range cmtMeta.LastCommit.Signatures {
if cs.Absent() {
continue
}
entity, ok := consensusToEntity[cs.ValidatorAddress.String()]
if !ok {
m.logger.Warn("could not convert block signer address to entity id (address not found)",
"height", data.BlockHeader.Height,
"signer", cs.ValidatorAddress.String(),
)
continue
}
prevSigners = append(prevSigners, entity.String())
}
switch m.mode {
case analyzer.FastSyncMode:
// During fast-sync, blocks are processed out of order, meaning the parent block may not yet be available.
// To avoid missing dependencies, signers are stored in a temporary table.
// These entries will be finalized during the fast-sync completion phase.
batch.Queue(
queries.ConsensusBlockAddSignersFastSync,
cmtMeta.LastCommit.Height,
prevSigners,
)
case analyzer.SlowSyncMode:
batch.Queue(
queries.ConsensusBlockAddSigners,
cmtMeta.LastCommit.Height,
prevSigners,
)
}
}
return nil
}
func (m *processor) queueEpochInserts(batch *storage.QueryBatch, data *consensusBlockData) error {
if m.mode == analyzer.SlowSyncMode {
// In slow-sync mode, update our knowledge about the epoch in-place.
batch.Queue(
queries.ConsensusEpochUpsert,
data.Epoch,
data.BlockHeader.Height,
)
} else {
// In fast-sync mode, record the association between the height and the epoch in a temporary table, to reduce write contention.
batch.Queue(
queries.ConsensusFastSyncEpochHeightInsert,
data.Epoch,
data.BlockHeader.Height,
)
}
return nil
}
// Adapted from https://github.com/oasisprotocol/oasis-core/blob/master/go/consensus/api/transaction/transaction.go#L58
func unpackTxBody(t *transaction.Transaction) (interface{}, error) {
err := fmt.Errorf("unknown tx method")
for _, mapping := range []map[string]interface{}{bodyTypeForTxMethodEden, bodyTypeForTxMethodDamask, bodyTypeForTxMethodCobalt} {
bodyType, ok := mapping[string(t.Method)]
if !ok {
continue
}
v := reflect.New(reflect.TypeOf(bodyType)).Interface()
if err = cbor.Unmarshal(t.Body, v); err != nil {
continue
}
return v, nil
}
return nil, fmt.Errorf("unable to cbor-decode consensus tx body: %w, method: %s, body: %x", err, t.Method, t.Body)
}
func (m *processor) queueTransactionInserts(batch *storage.QueryBatch, data *consensusBlockData) error {
for i, txr := range data.TransactionsWithResults {
signedTx := txr.Transaction
result := txr.Result
tx, err := OpenSignedTxNoVerify(&signedTx)
if err != nil {
m.logger.Info("couldn't parse transaction",
"err", err,
"height", data.Height,
"tx_index", i,
)
continue
}
sender := staking.NewAddress(
signedTx.Signature.PublicKey,
).String()
body, err := unpackTxBody(tx)
if err != nil {
m.logger.Warn("failed to unpack tx body", "err", err, "tx_hash", signedTx.Hash().Hex(), "height", data.Height)
}
// We explicitly json-marshal the body here to ensure that any custom
// MarshalJSON() added to the vendored types are used.
var bodyJSON []byte
bodyJSON, err = json.Marshal(body)
if err != nil {
m.logger.Warn("error json-marshalling struct", "err", err, "tx_hash", signedTx.Hash().Hex(), "height", data.Height)
}
var module *string
if len(result.Error.Module) > 0 {
module = &result.Error.Module
}
var message *string
if len(result.Error.Message) > 0 {
// The message should be well-formed since it comes from oasis-core.
// However postgres requires valid UTF-8 with no 0x00, so we sanitize the message just in case.
sanitizedMsg := strings.ToValidUTF8(strings.ReplaceAll(result.Error.Message, "\x00", "?"), "?")
message = &sanitizedMsg
}
// Use default values for fee if tx.Fee is absent.
fee := &transaction.Fee{}
if tx.Fee != nil {
fee = tx.Fee
}
batch.Queue(queries.ConsensusTransactionInsert,
data.BlockHeader.Height,
signedTx.Hash().Hex(),
i,
tx.Nonce,
fee.Amount.String(),
fmt.Sprintf("%d", fee.Gas),
tx.Method,
sender,
bodyJSON,
module,
result.Error.Code,
message,
result.GasUsed,
)
// Bump the nonce.
if m.mode != analyzer.FastSyncMode { // Skip during fast sync; nonce will be provided by the genesis.
if tx.Method != "consensus.Meta" { // consensus.Meta is a special internal tx that doesn't affect the nonce.
batch.Queue(queries.ConsensusAccountNonceUpsert,
sender,
tx.Nonce+1,
)
}
}
// TODO: Use event when available
// https://github.com/oasisprotocol/oasis-core/issues/4818
if tx.Method == "staking.AmendCommissionSchedule" && result.IsSuccess() {
var rawSchedule staking.AmendCommissionSchedule
if err := cbor.Unmarshal(tx.Body, &rawSchedule); err != nil {
return err
}
schedule, err := json.Marshal(rawSchedule)
if err != nil {
return err
}
if m.mode != analyzer.FastSyncMode {
// Skip during fast sync; will be provided by the genesis.
batch.Queue(queries.ConsensusCommissionsUpsert,
staking.NewAddress(signedTx.Signature.PublicKey).String(),
string(schedule),
)
}
}
}
return nil
}
// Enqueue DB statements to store events that were generated as the result of a TX execution.
func (m *processor) queueTxEventInserts(batch *storage.QueryBatch, data *allData) error {
for i, txr := range data.BlockData.TransactionsWithResults {
tx, err := OpenSignedTxNoVerify(&txr.Transaction)
if err != nil {
m.logger.Info("couldn't parse transaction",
"err", err,
"height", data.BlockData.Height,
"tx_index", i,
)
continue
}
txAccounts := []staking.Address{
// Always insert sender as a related address, some transactions (e.g. failed ones) might not have
// any events associated.
// TODO: this could also track the receiver (when applicable), but currently we don't do
// much transaction parsing, where we could extract it for each transaction type.
staking.NewAddress(txr.Transaction.Signature.PublicKey),
}
// Find all events associated with transaction.
// We don't use txr.Result.Events, because those do not have the event index unique within the block.
txEvents := make([]nodeapi.Event, 0, len(txr.Result.Events))
for _, event := range data.GovernanceData.Events {
if event.TxHash == txr.Transaction.Hash() {
txEvents = append(txEvents, event)
}
}
for _, event := range data.RegistryData.Events {
if event.TxHash == txr.Transaction.Hash() {
txEvents = append(txEvents, event)
}
}
for _, event := range data.RootHashData.Events {
if event.TxHash == txr.Transaction.Hash() {
txEvents = append(txEvents, event)
}
}
for _, event := range data.StakingData.Events {
if event.TxHash == txr.Transaction.Hash() {
txEvents = append(txEvents, event)
}
}
// Sanity check that the number of event matches.
if len(txEvents) != len(txr.Result.Events) {
return fmt.Errorf("transaction %s has %d events, but only %d were found", txr.Transaction.Hash().Hex(), len(txr.Result.Events), len(txEvents))
}
for _, event := range txEvents {
eventData := m.extractEventData(event)
txAccounts = append(txAccounts, eventData.relatedAddresses...)
accounts := extractUniqueAddresses(eventData.relatedAddresses)
body, err := json.Marshal(eventData.rawBody)
if err != nil {
return err
}
batch.Queue(queries.ConsensusEventInsert,
data.BlockData.Height,
string(eventData.ty),
eventData.eventIdx,
string(body),
txr.Transaction.Hash().Hex(),
i,
common.StringOrNil(eventData.roothashRuntimeID),
eventData.roothashRuntime,
eventData.roothashRuntimeRound,
)
batch.Queue(queries.ConsensusEventRelatedAccountsInsert,
data.BlockData.Height,
string(eventData.ty),
eventData.eventIdx,
i,
accounts,
)
}
uniqueTxAccounts := extractUniqueAddresses(txAccounts)
for _, addr := range uniqueTxAccounts {
batch.Queue(queries.ConsensusAccountRelatedTransactionInsert,
addr,
tx.Method,
data.BlockData.Height,
i,
)
if m.mode != analyzer.FastSyncMode {
// Increment the tx count for the related account.
// Skip in fast-sync mode; it will be recomputed at fast-sync finalization.
batch.Queue(queries.ConsensusAccountTxCountIncrement,
addr,
)
// Set the first activity for the related account if not set yet.
// Skip in fast sync mode; it will be recomputed at fast-sync finalization.
batch.Queue(
queries.ConsensusAccountFirstActivityUpsert,
addr,
data.BlockData.BlockHeader.Time.UTC(),
)
}
}
}
return nil
}
func (m *processor) queueRuntimeRegistrations(batch *storage.QueryBatch, data *registryData) error {
// Runtime registered or (re)started.
for _, runtimeEvent := range data.RuntimeStartedEvents {
var keyManager *string
if runtimeEvent.KeyManager != nil {
km := runtimeEvent.KeyManager.String()
keyManager = &km
}
if m.mode != analyzer.FastSyncMode {
// Skip during fast sync; will be provided by the genesis.
batch.Queue(queries.ConsensusRuntimeUpsert,
runtimeEvent.ID.String(),
false, // suspended
runtimeEvent.Kind,
runtimeEvent.TEEHardware,
keyManager,
)
}
}
// Runtime got suspended.
for _, runtimeEvent := range data.RuntimeSuspendedEvents {
if m.mode != analyzer.FastSyncMode {
// Skip during fast sync; will be provided by the genesis.
batch.Queue(queries.ConsensusRuntimeSuspendedUpdate,
runtimeEvent.RuntimeID.String(),
true, // suspended
)
}
}
return nil
}
// RegisterConsensusAddress inserts the address preimage of the given consensus address and ID.
func RegisterConsensusAddress(batch *storage.QueryBatch, address staking.Address, id []byte) {
batch.Queue(queries.AddressPreimageInsert,
address,
sdkTypes.AddressV0Ed25519Context.Identifier,
sdkTypes.AddressV0Ed25519Context.Version,
id,
)
}
func (m *processor) queueEntityEvents(batch *storage.QueryBatch, data *registryData) error {
for _, entityEvent := range data.EntityEvents {
entityID := entityEvent.Entity.ID.String()
for _, node := range entityEvent.Entity.Nodes {
batch.Queue(queries.ConsensusClaimedNodeInsert,
entityID,
node.String(),
)
}
entityAddress := staking.NewAddress(entityEvent.Entity.ID)
batch.Queue(queries.ConsensusEntityUpsert,
entityID,
entityAddress.String(),
data.Height,
)
RegisterConsensusAddress(batch, entityAddress, entityEvent.Entity.ID[:])
}
return nil
}
// Performs bookkeeping related to node (de)registrations, ignoring registrations that are already expired.
func (m *processor) queueNodeEvents(batch *storage.QueryBatch, data *registryData, currentEpoch uint64) error {
if m.mode == analyzer.FastSyncMode {
// Skip node updates during fast sync; this function only modifies chain.nodes and chain.runtime_nodes,
// which are both recreated from scratch by the genesis.
return nil
}
for _, nodeEvent := range data.NodeEvents {
if nodeEvent.IsRegistration && nodeEvent.Expiration >= currentEpoch {
// A new node is registered; the expiration check above is needed because oasis-node sometimes returns
// obsolete registration events, i.e. registrations that are already expired when they are produced.
batch.Queue(queries.ConsensusNodeUpsert,
nodeEvent.NodeID.String(),
nodeEvent.EntityID.String(),
nodeEvent.Expiration,
nodeEvent.TLSPubKey.String(),
nodeEvent.TLSNextPubKey.String(),
nodeEvent.TLSAddresses,
nodeEvent.P2PID.String(),
nodeEvent.P2PAddresses,
nodeEvent.ConsensusID.String(),
strings.Join(nodeEvent.ConsensusAddresses, ","), // TODO: store as array
nodeEvent.VRFPubKey,
nodeEvent.Roles,
nodeEvent.SoftwareVersion,
0,
)
RegisterConsensusAddress(batch, staking.NewAddress(nodeEvent.NodeID), nodeEvent.NodeID[:])
// Update the node's runtime associations by deleting
// previous node records and inserting new ones.
batch.Queue(queries.ConsensusRuntimeNodesDelete, nodeEvent.NodeID.String())
for _, rt := range nodeEvent.Runtimes {
batch.Queue(queries.ConsensusRuntimeNodesUpsert, rt.ID.String(), nodeEvent.NodeID.String(), rt.Version, rt.RawCapabilities, rt.ExtraInfo)
}
} else {
// An existing node is expired.
batch.Queue(queries.ConsensusRuntimeNodesDelete, nodeEvent.NodeID.String())
batch.Queue(queries.ConsensusNodeDelete,
nodeEvent.NodeID.String(),
)
}
}
return nil
}
func (m *processor) queueRegistryEventInserts(batch *storage.QueryBatch, data *registryData) error {
for _, event := range data.Events {
hash := util.SanitizeTxHash(event.TxHash.Hex())
if hash != nil {
continue // Events associated with a tx are processed in queueTxEventInserts
}
eventData := m.extractEventData(event)
if err := m.queueSingleEventInserts(batch, &eventData, data.Height); err != nil {
return err
}
}
return nil
}
func (m *processor) queueRootHashMessageUpserts(batch *storage.QueryBatch, data *rootHashData) error {
// Collect (I) roothash messages being scheduled and (II) roothash
// messages being finalized. They're always scheduled in the first
// ExecutorCommitedEvent (i.e. the proposal). They're finalized in (a)
// MessageEvent in Cobalt and in (b) the last round results in Damask and
// later.
finalized := map[coreCommon.Namespace]uint64{}
var roothashMessageEvents []nodeapi.Event
for _, event := range data.Events {
switch {
case event.RoothashMisc != nil:
switch event.Type { //nolint:gocritic,exhaustive // singleCaseSwitch, no special handling for other types
case apiTypes.ConsensusEventTypeRoothashFinalized:
// (II.a) MessageEvent does not have its own Round field, so
// use the value from the FinalizedEvent that happens at the
// same time.
finalized[event.RoothashMisc.RuntimeID] = *event.RoothashMisc.Round
}
case event.RoothashExecutorCommitted != nil:
runtime := RuntimeFromID(event.RoothashExecutorCommitted.RuntimeID, m.network)
if runtime == nil {
break
}
round := event.RoothashExecutorCommitted.Round
// (I) Extract roothash messages from the ExecutorCommittedEvent.
// Only the proposal has the messages, so the other commits will
// harmlessly skip over this part.
for i, message := range event.RoothashExecutorCommitted.Messages {
logger := m.logger.With(
"height", data.Height,
"runtime", runtime,
"round", round,
"message_index", i,
)
messageData := extractMessageData(logger, message)
// The runtime has its own staking account, which is what
// performs these actions, e.g. when sending or receiving the
// consensus token. Register that as related to the message.
if runtimeAddr, err := addresses.RegisterRuntimeAddress(messageData.addressPreimages, event.RoothashExecutorCommitted.RuntimeID); err != nil {
logger.Info("register runtime address failed",
"runtime_id", event.RoothashExecutorCommitted.RuntimeID,
"err", err,
)
} else {
messageData.relatedAddresses[runtimeAddr] = struct{}{}
}
for addr, preimageData := range messageData.addressPreimages {
batch.Queue(queries.AddressPreimageInsert,
addr,
preimageData.ContextIdentifier,
preimageData.ContextVersion,
preimageData.Data,
)
}
batch.Queue(queries.ConsensusRoothashMessageScheduleUpsert,
runtime,
round,
i,
messageData.messageType,
messageData.body,
addresses.SliceFromSet(messageData.relatedAddresses),
)
}
case event.RoothashMessage != nil:
// (II.a) Extract message results from the MessageEvents.
// Save these for after we collect all roothash finalized events.
roothashMessageEvents = append(roothashMessageEvents, event)
}
}
for _, event := range roothashMessageEvents {
runtime := RuntimeFromID(event.RoothashMessage.RuntimeID, m.network)
if runtime == nil {
continue
}
batch.Queue(queries.ConsensusRoothashMessageFinalizeUpsert,
runtime,
finalized[event.RoothashMessage.RuntimeID],
event.RoothashMessage.Index,
event.RoothashMessage.Module,
event.RoothashMessage.Code,
nil,
)
}
for rtid, results := range data.LastRoundResults {
runtime := RuntimeFromID(rtid, m.network)
if runtime == nil {
// We shouldn't even have gathered last round results for unknown
// runtimes. But prevent nil-runtime inserts anyway.
continue
}
round, ok := finalized[rtid]
if !ok {
continue
}
// (II.b) Extract message results from the last round results.
for _, message := range results.Messages {
batch.Queue(queries.ConsensusRoothashMessageFinalizeUpsert,
runtime,
round,
message.Index,
message.Module,
message.Code,
cbor.Marshal(message.Result),
)
}
}
return nil
}
func (m *processor) queueRootHashEventInserts(batch *storage.QueryBatch, data *rootHashData) error {
for _, event := range data.Events {
hash := util.SanitizeTxHash(event.TxHash.Hex())
if hash != nil {
continue // Events associated with a tx are processed in queueTxEventInserts
}
eventData := m.extractEventData(event)
if err := m.queueSingleEventInserts(batch, &eventData, data.Height); err != nil {
return err
}
}
return nil
}
// Enum of transfer types. We single out transfers that deduct from the special
// "fee accumulator" account. These deductions/disbursements happen at the end
// of each block. However, oasis-core returns each block's events in the
// following order: BeginBlockEvents, EndBlockEvents (which include
// disbursements), TxEvents (which fill the fee accumulator). Thus, processing
// the events in order results in a temporary negative balance for the fee
// accumulator, which violates our DB checks. We therefore artificially split
// transfer events into two: accumulator disbursements, and all others. We