/
full.go
1614 lines (1398 loc) · 51.4 KB
/
full.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 full implements a full Tendermint consensus node.
package full
import (
"bytes"
"context"
"fmt"
"math/rand"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/prometheus/client_golang/prometheus"
flag "github.com/spf13/pflag"
"github.com/spf13/viper"
tmabcitypes "github.com/tendermint/tendermint/abci/types"
tmconfig "github.com/tendermint/tendermint/config"
tmpubsub "github.com/tendermint/tendermint/libs/pubsub"
tmlight "github.com/tendermint/tendermint/light"
tmmempool "github.com/tendermint/tendermint/mempool"
tmnode "github.com/tendermint/tendermint/node"
tmp2p "github.com/tendermint/tendermint/p2p"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmproxy "github.com/tendermint/tendermint/proxy"
tmcli "github.com/tendermint/tendermint/rpc/client/local"
tmrpctypes "github.com/tendermint/tendermint/rpc/core/types"
tmstate "github.com/tendermint/tendermint/state"
tmstatesync "github.com/tendermint/tendermint/statesync"
tmtypes "github.com/tendermint/tendermint/types"
tmdb "github.com/tendermint/tm-db"
beaconAPI "github.com/oasisprotocol/oasis-core/go/beacon/api"
"github.com/oasisprotocol/oasis-core/go/common/cbor"
"github.com/oasisprotocol/oasis-core/go/common/crypto/hash"
"github.com/oasisprotocol/oasis-core/go/common/crypto/signature"
"github.com/oasisprotocol/oasis-core/go/common/errors"
"github.com/oasisprotocol/oasis-core/go/common/identity"
"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/random"
cmservice "github.com/oasisprotocol/oasis-core/go/common/service"
"github.com/oasisprotocol/oasis-core/go/common/version"
consensusAPI "github.com/oasisprotocol/oasis-core/go/consensus/api"
"github.com/oasisprotocol/oasis-core/go/consensus/api/transaction"
"github.com/oasisprotocol/oasis-core/go/consensus/api/transaction/results"
"github.com/oasisprotocol/oasis-core/go/consensus/metrics"
"github.com/oasisprotocol/oasis-core/go/consensus/tendermint/abci"
"github.com/oasisprotocol/oasis-core/go/consensus/tendermint/api"
"github.com/oasisprotocol/oasis-core/go/consensus/tendermint/apps/supplementarysanity"
tmbeacon "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/beacon"
tmcommon "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/common"
"github.com/oasisprotocol/oasis-core/go/consensus/tendermint/crypto"
"github.com/oasisprotocol/oasis-core/go/consensus/tendermint/db"
tmgovernance "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/governance"
tmkeymanager "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/keymanager"
"github.com/oasisprotocol/oasis-core/go/consensus/tendermint/light"
tmregistry "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/registry"
tmroothash "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/roothash"
tmscheduler "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/scheduler"
tmstaking "github.com/oasisprotocol/oasis-core/go/consensus/tendermint/staking"
genesisAPI "github.com/oasisprotocol/oasis-core/go/genesis/api"
governanceAPI "github.com/oasisprotocol/oasis-core/go/governance/api"
keymanagerAPI "github.com/oasisprotocol/oasis-core/go/keymanager/api"
cmbackground "github.com/oasisprotocol/oasis-core/go/oasis-node/cmd/common/background"
cmflags "github.com/oasisprotocol/oasis-core/go/oasis-node/cmd/common/flags"
cmmetrics "github.com/oasisprotocol/oasis-core/go/oasis-node/cmd/common/metrics"
"github.com/oasisprotocol/oasis-core/go/registry"
registryAPI "github.com/oasisprotocol/oasis-core/go/registry/api"
"github.com/oasisprotocol/oasis-core/go/roothash"
roothashAPI "github.com/oasisprotocol/oasis-core/go/roothash/api"
schedulerAPI "github.com/oasisprotocol/oasis-core/go/scheduler/api"
stakingAPI "github.com/oasisprotocol/oasis-core/go/staking/api"
"github.com/oasisprotocol/oasis-core/go/storage/mkvs/checkpoint"
upgradeAPI "github.com/oasisprotocol/oasis-core/go/upgrade/api"
)
const (
// CfgABCIPruneStrategy configures the ABCI state pruning strategy.
CfgABCIPruneStrategy = "consensus.tendermint.abci.prune.strategy"
// CfgABCIPruneNumKept configures the amount of kept heights if pruning is enabled.
CfgABCIPruneNumKept = "consensus.tendermint.abci.prune.num_kept"
// CfgABCIPruneInterval configures the ABCI state pruning interval.
CfgABCIPruneInterval = "consensus.tendermint.abci.prune.interval"
// CfgCheckpointerDisabled disables the ABCI state checkpointer.
CfgCheckpointerDisabled = "consensus.tendermint.checkpointer.disabled"
// CfgCheckpointerCheckInterval configures the ABCI state checkpointing check interval.
CfgCheckpointerCheckInterval = "consensus.tendermint.checkpointer.check_interval"
// CfgSentryUpstreamAddress defines nodes for which we act as a sentry for.
CfgSentryUpstreamAddress = "consensus.tendermint.sentry.upstream_address"
// CfgP2PPersistentPeer configures tendermint's persistent peer(s).
CfgP2PPersistentPeer = "consensus.tendermint.p2p.persistent_peer"
// CfgP2PPersistenPeersMaxDialPeriod configures the tendermint's persistent peer max dial period.
CfgP2PPersistenPeersMaxDialPeriod = "consensus.tendermint.p2p.persistent_peers_max_dial_period"
// CfgP2PDisablePeerExchange disables tendermint's peer-exchange (Pex) reactor.
CfgP2PDisablePeerExchange = "consensus.tendermint.p2p.disable_peer_exchange"
// CfgP2PUnconditionalPeerIDs configures tendermint's unconditional peer(s).
CfgP2PUnconditionalPeerIDs = "consensus.tendermint.p2p.unconditional_peer_ids"
// CfgDebugUnsafeReplayRecoverCorruptedWAL enables the debug and unsafe
// automatic corrupted WAL recovery during replay.
CfgDebugUnsafeReplayRecoverCorruptedWAL = "consensus.tendermint.debug.unsafe_replay_recover_corrupted_wal"
// CfgMinGasPrice configures the minimum gas price for this validator.
CfgMinGasPrice = "consensus.tendermint.min_gas_price"
// CfgSupplementarySanityEnabled is the supplementary sanity enabled flag.
CfgSupplementarySanityEnabled = "consensus.tendermint.supplementarysanity.enabled"
// CfgSupplementarySanityInterval configures the supplementary sanity check interval.
CfgSupplementarySanityInterval = "consensus.tendermint.supplementarysanity.interval"
// CfgConsensusStateSyncEnabled enabled consensus state sync.
CfgConsensusStateSyncEnabled = "consensus.tendermint.state_sync.enabled"
// CfgConsensusStateSyncConsensusNode specifies nodes exposing public consensus services which
// are used to sync a light client.
CfgConsensusStateSyncConsensusNode = "consensus.tendermint.state_sync.consensus_node"
// CfgConsensusStateSyncTrustPeriod is the light client trust period.
CfgConsensusStateSyncTrustPeriod = "consensus.tendermint.state_sync.trust_period"
// CfgConsensusStateSyncTrustHeight is the known trusted height for the light client.
CfgConsensusStateSyncTrustHeight = "consensus.tendermint.state_sync.trust_height"
// CfgConsensusStateSyncTrustHash is the known trusted block header hash for the light client.
CfgConsensusStateSyncTrustHash = "consensus.tendermint.state_sync.trust_hash"
// CfgUpgradeStopDelay is the average amount of time to delay shutting down the node on upgrade.
CfgUpgradeStopDelay = "consensus.tendermint.upgrade.stop_delay"
)
const (
// Time difference threshold used when considering if node is done with
// initial syncing. If difference is greater than the specified threshold
// the node is considered not yet synced.
// NOTE: this is only used during the initial sync.
syncWorkerLastBlockTimeDiffThreshold = 1 * time.Minute
minUpgradeStopWaitPeriod = 5 * time.Second
// tmSubscriberID is the subscriber identifier used for all internal Tendermint pubsub
// subscriptions. If any other subscriber IDs need to be derived they will be under this prefix.
tmSubscriberID = "oasis-core"
)
var (
_ api.Backend = (*fullService)(nil)
labelTendermint = prometheus.Labels{"backend": "tendermint"}
// Flags has the configuration flags.
Flags = flag.NewFlagSet("", flag.ContinueOnError)
)
// fullService implements a full Tendermint node.
type fullService struct { // nolint: maligned
sync.Mutex
cmservice.BaseBackgroundService
ctx context.Context
svcMgr *cmbackground.ServiceManager
upgrader upgradeAPI.Backend
mux *abci.ApplicationServer
node *tmnode.Node
client *tmcli.Local
blockNotifier *pubsub.Broker
failMonitor *failMonitor
stateStore tmstate.Store
beacon beaconAPI.Backend
governance governanceAPI.Backend
keymanager keymanagerAPI.Backend
registry registryAPI.Backend
roothash roothashAPI.Backend
scheduler schedulerAPI.Backend
staking stakingAPI.Backend
submissionMgr consensusAPI.SubmissionManager
serviceClients []api.ServiceClient
serviceClientsWg sync.WaitGroup
genesis *genesisAPI.Document
genesisProvider genesisAPI.Provider
identity *identity.Identity
dataDir string
isInitialized, isStarted bool
startedCh chan struct{}
syncedCh chan struct{}
quitCh chan struct{}
startFn func() error
stopOnce sync.Once
nextSubscriberID uint64
}
func (t *fullService) initialized() bool {
t.Lock()
defer t.Unlock()
return t.isInitialized
}
func (t *fullService) started() bool {
t.Lock()
defer t.Unlock()
return t.isStarted
}
// Implements service.BackgroundService.
func (t *fullService) Start() error {
if t.started() {
return fmt.Errorf("tendermint: service already started")
}
switch t.initialized() {
case true:
if err := t.mux.Start(); err != nil {
return err
}
if err := t.startFn(); err != nil {
return err
}
if err := t.node.Start(); err != nil {
return fmt.Errorf("tendermint: failed to start service: %w", err)
}
// Make sure the quit channel is closed when the node shuts down.
go func() {
select {
case <-t.quitCh:
case <-t.node.Quit():
select {
case <-t.quitCh:
default:
close(t.quitCh)
}
}
}()
// Start event dispatchers for all the service clients.
t.serviceClientsWg.Add(len(t.serviceClients))
for _, svc := range t.serviceClients {
go t.serviceClientWorker(t.ctx, svc)
}
// Start sync checker.
go t.syncWorker()
// Start block notifier.
go t.blockNotifierWorker()
// Optionally start metrics updater.
if cmmetrics.Enabled() {
go t.metrics()
}
case false:
close(t.syncedCh)
}
t.Lock()
t.isStarted = true
t.Unlock()
close(t.startedCh)
return nil
}
// Implements service.BackgroundService.
func (t *fullService) Quit() <-chan struct{} {
return t.quitCh
}
// Implements service.BackgroundService.
func (t *fullService) Cleanup() {
t.serviceClientsWg.Wait()
t.svcMgr.Cleanup()
}
// Implements service.BackgroundService.
func (t *fullService) Stop() {
if !t.initialized() || !t.started() {
return
}
t.stopOnce.Do(func() {
t.failMonitor.markCleanShutdown()
if err := t.node.Stop(); err != nil {
t.Logger.Error("Error on stopping node", err)
}
t.svcMgr.Stop()
t.mux.Stop()
})
}
func (t *fullService) Started() <-chan struct{} {
return t.startedCh
}
func (t *fullService) SupportedFeatures() consensusAPI.FeatureMask {
return consensusAPI.FeatureServices | consensusAPI.FeatureFullNode
}
func (t *fullService) Synced() <-chan struct{} {
return t.syncedCh
}
func (t *fullService) GetAddresses() ([]node.ConsensusAddress, error) {
u, err := tmcommon.GetExternalAddress()
if err != nil {
return nil, err
}
var addr node.ConsensusAddress
if err = addr.Address.UnmarshalText([]byte(u.Host)); err != nil {
return nil, fmt.Errorf("tendermint: failed to parse external address host: %w", err)
}
addr.ID = t.identity.P2PSigner.Public()
return []node.ConsensusAddress{addr}, nil
}
func (t *fullService) Checkpointer() checkpoint.Checkpointer {
return t.mux.State().Checkpointer()
}
func (t *fullService) StateToGenesis(ctx context.Context, blockHeight int64) (*genesisAPI.Document, error) {
blk, err := t.GetTendermintBlock(ctx, blockHeight)
if err != nil {
t.Logger.Error("failed to get tendermint block",
"err", err,
"block_height", blockHeight,
)
return nil, err
}
if blk == nil {
return nil, consensusAPI.ErrNoCommittedBlocks
}
blockHeight = blk.Header.Height
// Get initial genesis doc.
genesisDoc, err := t.GetGenesisDocument(ctx)
if err != nil {
t.Logger.Error("failed getting genesis document",
"err", err,
)
return nil, err
}
// Call StateToGenesis on all backends and merge the results together.
beaconGenesis, err := t.beacon.StateToGenesis(ctx, blockHeight)
if err != nil {
t.Logger.Error("beacon StateToGenesis failure",
"err", err,
"block_height", blockHeight,
)
return nil, err
}
registryGenesis, err := t.registry.StateToGenesis(ctx, blockHeight)
if err != nil {
t.Logger.Error("registry StateToGenesis failure",
"err", err,
"block_height", blockHeight,
)
return nil, err
}
roothashGenesis, err := t.roothash.StateToGenesis(ctx, blockHeight)
if err != nil {
t.Logger.Error("roothash StateToGenesis failure",
"err", err,
"block_height", blockHeight,
)
return nil, err
}
stakingGenesis, err := t.staking.StateToGenesis(ctx, blockHeight)
if err != nil {
t.Logger.Error("staking StateToGenesis failure",
"err", err,
"block_height", blockHeight,
)
return nil, err
}
keymanagerGenesis, err := t.keymanager.StateToGenesis(ctx, blockHeight)
if err != nil {
t.Logger.Error("keymanager StateToGenesis failure",
"err", err,
"block_height", blockHeight,
)
return nil, err
}
schedulerGenesis, err := t.scheduler.StateToGenesis(ctx, blockHeight)
if err != nil {
t.Logger.Error("scheduler StateToGenesis failure",
"err", err,
"block_height", blockHeight,
)
return nil, err
}
governanceGenesis, err := t.governance.StateToGenesis(ctx, blockHeight)
if err != nil {
t.Logger.Error("governance StateToGenesis failure",
"err", err,
"block_height", blockHeight,
)
return nil, err
}
return &genesisAPI.Document{
Height: blockHeight,
ChainID: genesisDoc.ChainID,
HaltEpoch: genesisDoc.HaltEpoch,
Time: blk.Header.Time,
Beacon: *beaconGenesis,
Registry: *registryGenesis,
RootHash: *roothashGenesis,
Staking: *stakingGenesis,
Governance: *governanceGenesis,
KeyManager: *keymanagerGenesis,
Scheduler: *schedulerGenesis,
Consensus: genesisDoc.Consensus,
}, nil
}
func (t *fullService) GetGenesisDocument(ctx context.Context) (*genesisAPI.Document, error) {
return t.genesis, nil
}
func (t *fullService) GetChainContext(ctx context.Context) (string, error) {
return t.genesis.ChainContext(), nil
}
func (t *fullService) RegisterHaltHook(hook consensusAPI.HaltHook) {
if !t.initialized() {
return
}
t.mux.RegisterHaltHook(hook)
}
func (t *fullService) SubmitTx(ctx context.Context, tx *transaction.SignedTransaction) error {
// Subscribe to the transaction being included in a block.
data := cbor.Marshal(tx)
query := tmtypes.EventQueryTxFor(data)
subID := t.newSubscriberID()
txSub, err := t.subscribe(subID, query)
if err != nil {
return err
}
if ptrSub, ok := txSub.(*tendermintPubsubBuffer).tmSubscription.(*tmpubsub.Subscription); ok && ptrSub == nil {
t.Logger.Debug("broadcastTx: service has shut down. Cancel our context to recover")
<-ctx.Done()
return ctx.Err()
}
defer t.unsubscribe(subID, query) // nolint: errcheck
// Subscribe to the transaction becoming invalid.
txHash := hash.NewFromBytes(data)
recheckCh, recheckSub, err := t.mux.WatchInvalidatedTx(txHash)
if err != nil {
return err
}
defer recheckSub.Close()
// First try to broadcast.
if err := t.broadcastTxRaw(data); err != nil {
return err
}
// Wait for the transaction to be included in a block.
select {
case v := <-recheckCh:
return v
case v := <-txSub.Out():
if result := v.Data().(tmtypes.EventDataTx).Result; !result.IsOK() {
return errors.FromCode(result.GetCodespace(), result.GetCode(), result.GetLog())
}
return nil
case <-txSub.Cancelled():
return context.Canceled
case <-ctx.Done():
return ctx.Err()
}
}
func (t *fullService) broadcastTxRaw(data []byte) error {
// We could use t.client.BroadcastTxSync but that is annoying as it
// doesn't give you the right fields when CheckTx fails.
mp := t.node.Mempool()
// Submit the transaction to mempool and wait for response.
ch := make(chan *tmabcitypes.Response, 1)
err := mp.CheckTx(tmtypes.Tx(data), func(rsp *tmabcitypes.Response) {
ch <- rsp
close(ch)
}, tmmempool.TxInfo{})
switch err {
case nil:
case tmmempool.ErrTxInCache:
// Transaction already in the mempool or was recently there.
return consensusAPI.ErrDuplicateTx
default:
return fmt.Errorf("tendermint: failed to submit to local mempool: %w", err)
}
rsp := <-ch
if result := rsp.GetCheckTx(); !result.IsOK() {
return errors.FromCode(result.GetCodespace(), result.GetCode(), result.GetLog())
}
return nil
}
func (t *fullService) newSubscriberID() string {
return fmt.Sprintf("%s/subscriber-%d", tmSubscriberID, atomic.AddUint64(&t.nextSubscriberID, 1))
}
func (t *fullService) SubmitEvidence(ctx context.Context, evidence *consensusAPI.Evidence) error {
var protoEv tmproto.Evidence
if err := protoEv.Unmarshal(evidence.Meta); err != nil {
return fmt.Errorf("tendermint: malformed evidence while unmarshalling: %w", err)
}
ev, err := tmtypes.EvidenceFromProto(&protoEv)
if err != nil {
return fmt.Errorf("tendermint: malformed evidence while converting: %w", err)
}
if _, err := t.client.BroadcastEvidence(ctx, ev); err != nil {
return fmt.Errorf("tendermint: broadcast evidence failed: %w", err)
}
return nil
}
func (t *fullService) EstimateGas(ctx context.Context, req *consensusAPI.EstimateGasRequest) (transaction.Gas, error) {
return t.mux.EstimateGas(req.Signer, req.Transaction)
}
func (t *fullService) subscribe(subscriber string, query tmpubsub.Query) (tmtypes.Subscription, error) {
// Note: The tendermint documentation claims using SubscribeUnbuffered can
// freeze the server, however, the buffered Subscribe can drop events, and
// force-unsubscribe the channel if processing takes too long.
subFn := func() (tmtypes.Subscription, error) {
sub, err := t.node.EventBus().SubscribeUnbuffered(t.ctx, subscriber, query)
if err != nil {
return nil, err
}
// Oh yes, this can actually return a nil subscription even though the
// error was also nil if the node is just shutting down.
if sub == (*tmpubsub.Subscription)(nil) {
return nil, context.Canceled
}
return newTendermintPubsubBuffer(sub), nil
}
if t.started() {
return subFn()
}
// The node doesn't exist until it's started since, creating the node
// triggers replay, InitChain, and etc.
t.Logger.Debug("Subscribe: node not available yet, blocking",
"subscriber", subscriber,
"query", query,
)
// XXX/yawning: As far as I can tell just blocking here is safe as
// ever single consumer of the API subscribes from a go routine.
select {
case <-t.startedCh:
case <-t.ctx.Done():
return nil, t.ctx.Err()
}
return subFn()
}
func (t *fullService) unsubscribe(subscriber string, query tmpubsub.Query) error {
if t.started() {
return t.node.EventBus().Unsubscribe(t.ctx, subscriber, query)
}
return fmt.Errorf("tendermint: unsubscribe called with no backing service")
}
func (t *fullService) RegisterApplication(app api.Application) error {
return t.mux.Register(app)
}
func (t *fullService) SetTransactionAuthHandler(handler api.TransactionAuthHandler) error {
return t.mux.SetTransactionAuthHandler(handler)
}
func (t *fullService) TransactionAuthHandler() consensusAPI.TransactionAuthHandler {
return t.mux.TransactionAuthHandler()
}
func (t *fullService) SubmissionManager() consensusAPI.SubmissionManager {
return t.submissionMgr
}
func (t *fullService) Beacon() beaconAPI.Backend {
return t.beacon
}
func (t *fullService) KeyManager() keymanagerAPI.Backend {
return t.keymanager
}
func (t *fullService) Registry() registryAPI.Backend {
return t.registry
}
func (t *fullService) RootHash() roothashAPI.Backend {
return t.roothash
}
func (t *fullService) Staking() stakingAPI.Backend {
return t.staking
}
func (t *fullService) Scheduler() schedulerAPI.Backend {
return t.scheduler
}
func (t *fullService) Governance() governanceAPI.Backend {
return t.governance
}
func (t *fullService) GetBlock(ctx context.Context, height int64) (*consensusAPI.Block, error) {
blk, err := t.GetTendermintBlock(ctx, height)
if err != nil {
return nil, err
}
if blk == nil {
return nil, consensusAPI.ErrNoCommittedBlocks
}
return api.NewBlock(blk), nil
}
func (t *fullService) GetSignerNonce(ctx context.Context, req *consensusAPI.GetSignerNonceRequest) (uint64, error) {
return t.mux.TransactionAuthHandler().GetSignerNonce(ctx, req)
}
func (t *fullService) GetTransactions(ctx context.Context, height int64) ([][]byte, error) {
blk, err := t.GetTendermintBlock(ctx, height)
if err != nil {
return nil, err
}
if blk == nil {
return nil, consensusAPI.ErrNoCommittedBlocks
}
txs := make([][]byte, 0, len(blk.Data.Txs))
for _, v := range blk.Data.Txs {
txs = append(txs, v[:])
}
return txs, nil
}
func (t *fullService) GetTransactionsWithResults(ctx context.Context, height int64) (*consensusAPI.TransactionsWithResults, error) {
var txsWithResults consensusAPI.TransactionsWithResults
blk, err := t.GetTendermintBlock(ctx, height)
if err != nil {
return nil, err
}
if blk == nil {
return nil, consensusAPI.ErrNoCommittedBlocks
}
for _, tx := range blk.Data.Txs {
txsWithResults.Transactions = append(txsWithResults.Transactions, tx[:])
}
res, err := t.GetBlockResults(ctx, blk.Height)
if err != nil {
return nil, err
}
for txIdx, rs := range res.TxsResults {
// Transaction result.
result := &results.Result{
Error: results.Error{
Module: rs.GetCodespace(),
Code: rs.GetCode(),
Message: rs.GetLog(),
},
}
// Transaction staking events.
stakingEvents, err := tmstaking.EventsFromTendermint(
txsWithResults.Transactions[txIdx],
blk.Height,
rs.Events,
)
if err != nil {
return nil, err
}
for _, e := range stakingEvents {
result.Events = append(result.Events, &results.Event{Staking: e})
}
// Transaction registry events.
registryEvents, _, err := tmregistry.EventsFromTendermint(
txsWithResults.Transactions[txIdx],
blk.Height,
rs.Events,
)
if err != nil {
return nil, err
}
for _, e := range registryEvents {
result.Events = append(result.Events, &results.Event{Registry: e})
}
// Transaction roothash events.
roothashEvents, err := tmroothash.EventsFromTendermint(
txsWithResults.Transactions[txIdx],
blk.Height,
rs.Events,
)
if err != nil {
return nil, err
}
for _, e := range roothashEvents {
result.Events = append(result.Events, &results.Event{RootHash: e})
}
// Transaction governance events.
governanceEvents, err := tmgovernance.EventsFromTendermint(
txsWithResults.Transactions[txIdx],
blk.Height,
rs.Events,
)
if err != nil {
return nil, err
}
for _, e := range governanceEvents {
result.Events = append(result.Events, &results.Event{Governance: e})
}
txsWithResults.Results = append(txsWithResults.Results, result)
}
return &txsWithResults, nil
}
func (t *fullService) GetUnconfirmedTransactions(ctx context.Context) ([][]byte, error) {
mempoolTxs := t.node.Mempool().ReapMaxTxs(-1)
txs := make([][]byte, 0, len(mempoolTxs))
for _, v := range mempoolTxs {
txs = append(txs, v[:])
}
return txs, nil
}
func (t *fullService) GetStatus(ctx context.Context) (*consensusAPI.Status, error) {
status := &consensusAPI.Status{
Version: version.ConsensusProtocol,
Backend: api.BackendName,
Features: t.SupportedFeatures(),
}
status.ChainContext = t.genesis.ChainContext()
status.GenesisHeight = t.genesis.Height
if t.started() {
// Only attempt to fetch blocks in case the consensus service has started as otherwise
// requests will block.
genBlk, err := t.GetBlock(ctx, t.genesis.Height)
switch err {
case nil:
status.GenesisHash = genBlk.Hash
default:
// We may not be able to fetch the genesis block in case it has been pruned.
}
lastRetainedHeight, err := t.GetLastRetainedVersion(ctx)
if err != nil {
return nil, fmt.Errorf("failed to get last retained height: %w", err)
}
// Some pruning configurations return 0 instead of a valid block height. Clamp those to the genesis height.
if lastRetainedHeight < t.genesis.Height {
lastRetainedHeight = t.genesis.Height
}
status.LastRetainedHeight = lastRetainedHeight
lastRetainedBlock, err := t.GetBlock(ctx, lastRetainedHeight)
switch err {
case nil:
status.LastRetainedHash = lastRetainedBlock.Hash
default:
// Before we commit the first block, we can't load it from GetBlock. Don't give its hash in this case.
}
// Latest block.
latestBlk, err := t.GetBlock(ctx, consensusAPI.HeightLatest)
switch err {
case nil:
status.LatestHeight = latestBlk.Height
status.LatestHash = latestBlk.Hash
status.LatestTime = latestBlk.Time
status.LatestStateRoot = latestBlk.StateRoot
var epoch beaconAPI.EpochTime
epoch, err = t.beacon.GetEpoch(ctx, status.LatestHeight)
if err != nil {
return nil, fmt.Errorf("failed to fetch epoch: %w", err)
}
status.LatestEpoch = epoch
case consensusAPI.ErrNoCommittedBlocks:
// No committed blocks yet.
default:
return nil, fmt.Errorf("failed to fetch current block: %w", err)
}
// List of consensus peers.
tmpeers := t.node.Switch().Peers().List()
peers := make([]string, 0, len(tmpeers))
for _, tmpeer := range tmpeers {
p := string(tmpeer.ID()) + "@" + tmpeer.RemoteAddr().String()
peers = append(peers, p)
}
status.NodePeers = peers
// Check if the local node is in the validator set for the latest (uncommitted) block.
valSetHeight := status.LatestHeight + 1
if valSetHeight < status.GenesisHeight {
valSetHeight = status.GenesisHeight
}
vals, err := t.stateStore.LoadValidators(valSetHeight)
if err != nil {
// Failed to load validator set.
status.IsValidator = false
} else {
consensusPk := t.identity.ConsensusSigner.Public()
consensusAddr := []byte(crypto.PublicKeyToTendermint(&consensusPk).Address())
status.IsValidator = vals.HasAddress(consensusAddr)
}
}
return status, nil
}
func (t *fullService) GetNextBlockState(ctx context.Context) (*consensusAPI.NextBlockState, error) {
if !t.started() {
return nil, fmt.Errorf("tendermint: not yet started")
}
rs := t.node.ConsensusState().GetRoundState()
nbs := &consensusAPI.NextBlockState{
Height: rs.Height,
NumValidators: uint64(rs.Validators.Size()),
VotingPower: uint64(rs.Validators.TotalVotingPower()),
}
for i, val := range rs.Validators.Validators {
var vote consensusAPI.Vote
valNode, err := t.Registry().GetNodeByConsensusAddress(ctx, ®istryAPI.ConsensusAddressQuery{
Height: consensusAPI.HeightLatest,
Address: val.Address,
})
if err == nil {
vote.NodeID = valNode.ID
vote.EntityID = valNode.EntityID
vote.EntityAddress = stakingAPI.NewAddress(valNode.EntityID)
}
vote.VotingPower = uint64(val.VotingPower)
if prevote := rs.Votes.Prevotes(rs.Round).GetByIndex(int32(i)); prevote != nil {
nbs.Prevotes.Votes = append(nbs.Prevotes.Votes, vote)
nbs.Prevotes.VotingPower = nbs.Prevotes.VotingPower + vote.VotingPower
}
if precommit := rs.Votes.Precommits(rs.Round).GetByIndex(int32(i)); precommit != nil {
nbs.Precommits.Votes = append(nbs.Precommits.Votes, vote)
nbs.Precommits.VotingPower = nbs.Precommits.VotingPower + vote.VotingPower
}
}
nbs.Prevotes.Ratio = float64(nbs.Prevotes.VotingPower) / float64(nbs.VotingPower)
nbs.Precommits.Ratio = float64(nbs.Precommits.VotingPower) / float64(nbs.VotingPower)
return nbs, nil
}
func (t *fullService) WatchBlocks(ctx context.Context) (<-chan *consensusAPI.Block, pubsub.ClosableSubscription, error) {
ch, sub := t.WatchTendermintBlocks()
mapCh := make(chan *consensusAPI.Block)
go func() {
defer close(mapCh)
for {
select {
case tmBlk, ok := <-ch:
if !ok {
return
}
mapCh <- api.NewBlock(tmBlk)
case <-ctx.Done():
return
}
}
}()
return mapCh, sub, nil
}
func (t *fullService) ensureStarted(ctx context.Context) error {
// Make sure that the Tendermint service has started so that we
// have the client interface available.
select {
case <-t.startedCh:
case <-t.ctx.Done():
return t.ctx.Err()
case <-ctx.Done():
return ctx.Err()
}
return nil
}
func (t *fullService) initialize() error {
t.Lock()
defer t.Unlock()
if t.isInitialized {
return nil
}
if err := t.lazyInit(); err != nil {
return err
}
// Apply the genesis public key blacklist.
for _, v := range t.genesis.Consensus.Parameters.PublicKeyBlacklist {
if err := v.Blacklist(); err != nil {
t.Logger.Error("initialize: failed to blacklist key",
"err", err,
"pk", v,
)
return err
}
}
// Initialize the beacon/epochtime backend.
var (
err error
scBeacon tmbeacon.ServiceClient
)
if scBeacon, err = tmbeacon.New(t.ctx, t); err != nil {
t.Logger.Error("initialize: failed to initialize beapoch backend",
"err", err,
)
return err
}
t.beacon = scBeacon
t.serviceClients = append(t.serviceClients, scBeacon)
if err = t.mux.SetEpochtime(t.beacon); err != nil {
return err
}
// Initialize the rest of backends.
var scKeyManager tmkeymanager.ServiceClient
if scKeyManager, err = tmkeymanager.New(t.ctx, t); err != nil {
t.Logger.Error("initialize: failed to initialize keymanager backend",
"err", err,
)
return err
}
t.keymanager = scKeyManager
t.serviceClients = append(t.serviceClients, scKeyManager)
var scRegistry tmregistry.ServiceClient
if scRegistry, err = tmregistry.New(t.ctx, t); err != nil {
t.Logger.Error("initialize: failed to initialize registry backend",
"err", err,
)
return err
}
t.registry = scRegistry
if cmmetrics.Enabled() {
t.svcMgr.RegisterCleanupOnly(registry.NewMetricsUpdater(t.ctx, t.registry), "registry metrics updater")
}
t.serviceClients = append(t.serviceClients, scRegistry)
t.svcMgr.RegisterCleanupOnly(t.registry, "registry backend")
var scStaking tmstaking.ServiceClient
if scStaking, err = tmstaking.New(t.ctx, t); err != nil {
t.Logger.Error("staking: failed to initialize staking backend",
"err", err,