Repository navigation
Expand file tree
/
Copy pathnode.go
More file actions
2852 lines (2760 loc) · 109 KB
/
Copy pathnode.go
File metadata and controls
2852 lines (2760 loc) · 109 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
// Copyright 2026 Blink Labs Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dingo
import (
"context"
"errors"
"fmt"
"log/slog"
"math"
"math/big"
"net/http"
"slices"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/blinklabs-io/dingo/api/blockfrost"
"github.com/blinklabs-io/dingo/api/kupo"
"github.com/blinklabs-io/dingo/api/mcp"
"github.com/blinklabs-io/dingo/api/mesh"
"github.com/blinklabs-io/dingo/api/utxorpc"
"github.com/blinklabs-io/dingo/bark"
"github.com/blinklabs-io/dingo/chain"
"github.com/blinklabs-io/dingo/chainselection"
"github.com/blinklabs-io/dingo/chainsync"
"github.com/blinklabs-io/dingo/connmanager"
nodeconsensus "github.com/blinklabs-io/dingo/consensus"
"github.com/blinklabs-io/dingo/database"
"github.com/blinklabs-io/dingo/database/lifecycle"
"github.com/blinklabs-io/dingo/database/models"
"github.com/blinklabs-io/dingo/database/nodesettings"
"github.com/blinklabs-io/dingo/database/plugin/metadata"
"github.com/blinklabs-io/dingo/dmq"
"github.com/blinklabs-io/dingo/event"
"github.com/blinklabs-io/dingo/internal/apiconfig"
"github.com/blinklabs-io/dingo/internal/chainsyncrecycler"
"github.com/blinklabs-io/dingo/internal/committeeauth"
internalconfig "github.com/blinklabs-io/dingo/internal/config"
"github.com/blinklabs-io/dingo/internal/dblifecycle"
"github.com/blinklabs-io/dingo/internal/historyexpiry"
"github.com/blinklabs-io/dingo/internal/koiosparity"
"github.com/blinklabs-io/dingo/internal/offchainmetadata"
"github.com/blinklabs-io/dingo/internal/plannerstats"
internalplugins "github.com/blinklabs-io/dingo/internal/plugins"
"github.com/blinklabs-io/dingo/internal/promutil"
"github.com/blinklabs-io/dingo/kesagent"
"github.com/blinklabs-io/dingo/ledger"
"github.com/blinklabs-io/dingo/ledger/forging"
"github.com/blinklabs-io/dingo/ledger/leios"
"github.com/blinklabs-io/dingo/ledger/snapshot"
"github.com/blinklabs-io/dingo/mempool"
midnightindexer "github.com/blinklabs-io/dingo/midnight/indexer"
midnightserver "github.com/blinklabs-io/dingo/midnight/server"
ouroborosPkg "github.com/blinklabs-io/dingo/ouroboros"
"github.com/blinklabs-io/dingo/peergov"
"github.com/blinklabs-io/dingo/plugin"
ouroboros "github.com/blinklabs-io/gouroboros"
"github.com/blinklabs-io/gouroboros/muxer"
ochainsync "github.com/blinklabs-io/gouroboros/protocol/chainsync"
okeepalive "github.com/blinklabs-io/gouroboros/protocol/keepalive"
olocalstatequery "github.com/blinklabs-io/gouroboros/protocol/localstatequery"
"github.com/prometheus/client_golang/prometheus"
)
type Node struct {
connManager *connmanager.ConnectionManager
peerGovMu sync.RWMutex
peerGov *peergov.PeerGovernor
// networkingCoreMu keeps actions that must use peerGov and connManager as
// one generation from landing between live lifecycle quiesce and rebuild.
// Restore and Truncate hold it for their complete operation; shutdown does
// not, because it stops the retained chain selector while holding its own
// lifecycle gates.
networkingCoreMu sync.Mutex
// poolRelayProvider backs peerGov's LedgerPeerProvider. Tracked here (not
// a throwaway local) so quiesceForLiveLifecycleOp can Close it -- it has
// no Stop of its own otherwise, so a live database restore/truncate,
// which constructs a fresh one on every cycle, would leak its EventBus
// subscription every time (node_lifecycle.go).
poolRelayProvider *ledger.PoolRelayProvider
chainsyncState *chainsync.State
chainSelector *chainselection.ChainSelector
chainSelectionMetrics *chainSelectionMetrics
chainSelectorForGauges atomic.Pointer[chainselection.ChainSelector]
equivocation *equivocationDetector
eventBus *event.EventBus
pluginHost *plugin.Host
consensusProvider nodeconsensus.Provider
destinationRegistry *lifecycle.DestinationRegistry
mempool mempool.Service
chainManager *chain.ChainManager
db *database.Database
ledgerState *ledger.LedgerState
snapshotMgr *snapshot.Manager
dbLifecycleMgr *dblifecycle.Manager
plannerStatsMgr *plannerstats.Manager
leiosVoteManager *leios.VoteManager
leiosPipelineManager *leios.PipelineManager
bark *bark.Bark
historyExpiry *historyexpiry.Pruner
committeeAuthSync *committeeauth.Syncer
koiosParityObserver *koiosparity.Observer
midnightServer *midnightserver.Server
dmqStack *dmq.Stack
dmqStake dmqStakeAuthority
offchainMetadataFetcher *offchainmetadata.Fetcher
tokenRegistrySync *offchainmetadata.TokenRegistrySync
midnightIndexer *midnightindexer.Indexer
// ouroborosRef holds the current Ouroboros. It is atomic because a live
// snapshot/restore replaces the instance while EventBus handlers and
// component callbacks -- which resolve it at call time, by design -- may
// be reading it from other goroutines. Read it through the ouroboros()
// accessor; the only writer is the replacement in
// reinitializeNetworkingCore and the initial construction in Run.
ouroborosRef atomic.Pointer[ouroborosPkg.Ouroboros]
// leiosCertificateVerifier is leiosVoteManager as seen by the ledger's
// certificate callback. The ledger's block-processing goroutine starts
// before initLeiosVoteManager runs, at startup and after a live
// restore/truncate, so the callback cannot read the plain field.
leiosCertificateVerifier atomic.Pointer[leios.VoteManager]
// ouroborosConfig retains the settings half of the config Run built, so a
// live restore can reconstruct ouroboros against rebuilt dependencies
// without recomputing them and drifting from Run.
ouroborosConfig ouroborosPkg.OuroborosConfig
blockForger *forging.BlockForger
// blockProducerCreds is the live credential set the forger, builder and
// leader election draw on. The node owns it: it is the target of a
// credential reload and is closed, zeroizing the keys, when the forging
// path stops. An atomic pointer because the reload trigger runs on its
// own goroutine, concurrently with a live lifecycle teardown.
blockProducerCreds atomic.Pointer[forging.PoolCredentials]
// kesAgentClient is set when shelleyKESAgentSocket is configured, in
// either serve-key or sign mode. validateBlockProducerStartup owns
// dialing/closing it (closing the prior one before replacing it, so a
// live-lifecycle rebuild via reinitializeBlockProducer cannot leak a
// connection); node_shutdown.go closes it during graceful shutdown.
kesAgentClient *kesagent.Client
kesAgentCancel context.CancelFunc
kesAgentMetrics *kesagent.Metrics
leaderElection nodeconsensus.LeaderScheduler
rtsMetrics *rtsMetrics
shutdownFuncs []func(context.Context) error
deferredIndexMaintenanceDone chan struct{}
config Config
ctx context.Context
cancel context.CancelFunc
fatalErrMu sync.Mutex
fatalErr error
shutdownMu sync.Mutex
shutdownWait chan struct{}
shutdownRunning bool
shutdownDone bool
shutdownErr error
startedAt time.Time
remoteLifecycle remoteLifecycle
// startupLifecycleMu keeps the startup rollback and normal shutdown from
// operating on the same partially initialized component concurrently. Run
// holds it until startup has either completed or unwound its LIFO cleanup;
// shutdown takes it before it begins its phase-ordered teardown.
startupLifecycleMu sync.Mutex
chainsyncStallRecycler *chainsyncrecycler.Recycler
chainsyncIngressEligibilityMu sync.RWMutex
chainsyncIngressEligibilityCache map[ouroboros.ConnectionId]bool
// EventBus subscriber IDs for handlers bound to components that a live
// database restore/truncate rebuilds from scratch (node_lifecycle.go).
// Every other Run()-registered handler is either a closure over n itself
// (self-healing — reads the current field value at call time) or bound
// to a component that lifecycle rebuild leaves untouched, so it needs no
// tracked ID. Captured here (rather than discarded, as Run() otherwise
// would) purely so node_lifecycle.go can unsubscribe the stale handler
// before rebuilding its component; Run()'s own behavior is unchanged.
chainsyncClientRemoveSubId event.EventSubscriberId
connManagerRecycleSubId event.EventSubscriberId
leiosVoteEmittedSubId event.EventSubscriberId
leiosVoteReceivedSubId event.EventSubscriberId
// koiosParitySubId is tracked for the same reason: observer.
// HandleEpochTransitionEvent is bound to the *koiosparity.Observer
// instance startKoiosParityObserver creates, which a live database
// restore/truncate must tear down and rebuild (a stale observer would
// otherwise keep running against the pre-rebuild n.db) -- see
// node_lifecycle.go's quiesceForLiveLifecycleOp/
// reinitializeBackgroundManagers handling of it.
koiosParitySubId event.EventSubscriberId
// liveLifecycleMu serializes live database Restore/Truncate calls
// (node_lifecycle.go) so two can never quiesce/rebuild concurrently.
// Shutdown takes this mutex before cancelling components or closing
// storage, so it cannot tear down a live operation in progress. The lock
// order with networkingCoreMu and snapshotMu is always liveLifecycleMu,
// then networkingCoreMu, then snapshotMu.
// Deliberately NOT held by Snapshot (see snapshotMu): Snapshot never
// nils/rebuilds n.ledgerState or n.chainsyncState the way Restore/
// Truncate do, so a background reader like the chainsync recycler
// tick only needs to know whether a REBUILD is in flight -- not
// whether an unrelated, non-rebuilding Snapshot happens to be
// running, which this mutex would otherwise make indistinguishable.
liveLifecycleMu sync.Mutex
// ingestHold carries the network ingest hold across chainsync state
// rebuilds. Created by networkIngestHold.
ingestHoldOnce sync.Once
ingestHold *chainsync.IngestHold
// mithrilCoordinator runs node-managed Mithril catch-up, when enabled.
// Set once at startup under liveLifecycleMu; a live Restore, Truncate or
// shutdown aborts its run in progress through quiesceComponentStops.
mithrilCoordinator *mithrilCoordinator
// mithrilSource is the Mithril half of node-managed Mithril, nil when it
// is not enabled. Built before the chain manager, so snapshot mode can
// restore into the database before anything reads it.
mithrilSource MithrilCatchUp
// mithrilSuppressedUntil holds the coordinator's first check back after
// a failed startup restore, as a failed check does.
mithrilSuppressedUntil time.Time
// mithrilRestore is the startup snapshot restore's progress, for the
// readiness probe; nil when none is running.
mithrilRestore atomic.Pointer[mithrilRestoreStatus]
// mithrilRestoreGauge is dingo_mithril_snapshot_restore_state, nil
// without a metrics registry.
mithrilRestoreGauge prometheus.Gauge
// mithrilMetrics counts source decisions and fallbacks; nil without a
// metrics registry.
mithrilMetrics *mithrilNodeMetrics
// wallClockLedger is n.ledgerState once its Start has returned, for the
// chain selector's wall-clock hook, which runs on the selector's goroutine
// across live rebuilds. Start initializes the slot clock the hook reads,
// so a ledger is published only after it (publishStartedLedgerState) and
// withdrawn before it is replaced or closed (setLedgerState).
wallClockLedger atomic.Pointer[ledger.LedgerState]
// A selected-to-none transition cannot be dropped while a live database
// lifecycle operation holds liveLifecycleMu. One node-owned worker retains
// only the latest contended transition and retries until the lifecycle lock
// is available or the node context is cancelled, bounding both queued work
// and goroutine count.
chainSelectedNoneMu sync.Mutex
chainSelectedNonePending chainselection.ChainSelectedNoneEvent
chainSelectedNonePendingSet bool
chainSelectedNoneWake chan struct{}
chainSelectedNoneWorkerDone chan struct{}
// snapshotMu serializes Snapshot calls against each other and against
// a concurrent Restore/Truncate (which closes n.db out from under an
// in-progress Snapshot if not excluded), and is what enforces bark
// DatabaseService's "one operation at a time" invariant for Snapshot
// specifically. Restore/Truncate take both this and liveLifecycleMu, and
// shutdown takes both in that same order; Snapshot takes only this one --
// so a long-running Snapshot (a full
// local copy plus cloud upload) never blocks a background reader that
// only cares about liveLifecycleMu, such as the chainsync recycler
// tick's stall-detection/plateau-recovery check, matching Snapshot's
// own documented "keeps syncing normally" behavior.
snapshotMu sync.Mutex
// health carries the sync signals the readiness probe reads. See
// node_health.go; it survives a live database restore/truncate rebuild.
health nodeHealth
// rebuildableMetrics tracks every Prometheus collector registered by a
// component a live database restore/truncate rebuilds, so
// closeStorageForLiveLifecycleOp can unregister them before the
// rebuild re-registers fresh ones under the same names. See
// metrics_registerer.go.
rebuildableMetrics *rebuildableRegisterer
}
// consensusPluginSelection returns the consensus plugin selection, defaulting
// an unset provider to Praos. A config built from a caller-supplied internal
// config bypasses the loader's defaults, and an empty name would otherwise
// fail startup with a missing-provider error.
func (c *Config) consensusPluginSelection() plugin.Selection {
selection := c.pluginSelections[plugin.CapabilityConsensus]
if selection.Provider == "" {
selection.Provider = nodeconsensus.PraosProviderName
}
return selection
}
func (n *Node) selectedConsensusProvider() nodeconsensus.Provider {
if n != nil && n.consensusProvider != nil {
return n.consensusProvider
}
return nodeconsensus.NewPraosProvider()
}
func New(cfg Config) (*Node, error) {
pluginHost, err := internalplugins.NewHost()
if err != nil {
return nil, fmt.Errorf("create plugin host: %w", err)
}
// Cloud destination schemes (s3, gcs) are registered explicitly here,
// at composition time, rather than via a process-global registry each
// scheme's own package would otherwise populate through an init() —
// see database/lifecycle/destination.go's DestinationRegistry doc
// comment.
destinationRegistry := lifecycle.NewDestinationRegistry()
lifecycle.RegisterBuiltinDestinations(destinationRegistry)
n := &Node{
config: cfg,
pluginHost: pluginHost,
destinationRegistry: destinationRegistry,
startedAt: time.Now(),
remoteLifecycle: remoteLifecycle{
requests: make(chan ShutdownRequest, 1),
},
}
for capability, selection := range cfg.pluginSelections {
// API capabilities are validated against their *merged* config
// (shared api.tls defaults folded in) so an invalid
// effective TLS policy -- e.g. a partial certificate/key
// pair -- is rejected here, before any listener starts, using
// the exact same merge apiPluginSelection applies at Start()/
// reinitializeAPIServers time. See apiProviderConfig.
if configPath, ok := apiProviderConfigPath[capability]; ok {
var err error
selection, err = cfg.apiProviderConfig(capability, selection)
if err != nil {
return nil, fmt.Errorf("invalid plugin selection: %w", err)
}
if err := validateAPIProviderSecurityPolicy(
configPath, selection.Config,
); err != nil {
return nil, fmt.Errorf("invalid plugin selection: %w", err)
}
}
if err := pluginHost.ValidateSelection(
capability, selection.Provider, selection.Config,
); err != nil {
return nil, fmt.Errorf("invalid plugin selection: %w", err)
}
}
if err := n.configPopulateNetworkMagic(); err != nil {
return nil, fmt.Errorf("invalid configuration: %w", err)
}
if err := n.configPopulateDMQNetworkMagic(); err != nil {
return nil, fmt.Errorf("invalid configuration: %w", err)
}
// Invalid configuration must not leave collectors in a caller-owned
// registry: callers may correct it and retry construction with that registry.
if err := n.configValidate(); err != nil {
return nil, fmt.Errorf("invalid configuration: %w", err)
}
// Wrap the prometheus registry with a "network" label so all metrics
// registered by subsystems carry the network name automatically.
// This must happen before any component registers metrics.
n.configWrapPromRegistry()
metricsRegistration := promutil.NewRegistration(n.config.promRegistry)
n.registerBuildInfo(metricsRegistration)
n.registerRTSMetrics(metricsRegistration)
n.registerChainSelectionMetrics(metricsRegistration)
var equivocationRegistration *promutil.Registration
if n.config.promRegistry != nil {
equivocationRegistration = metricsRegistration
n.mithrilRestoreGauge = promutil.Register(
metricsRegistration,
prometheus.NewGauge(prometheus.GaugeOpts{
Name: "dingo_mithril_snapshot_restore_state",
Help: "startup Mithril snapshot restore: 0 none running, " +
"1 restoring, 2 stuck (failing without progress), " +
"3 waiting on the Mithril source",
}),
)
n.mithrilMetrics = newMithrilNodeMetrics(metricsRegistration)
}
n.equivocation = newEquivocationDetector(
equivocationRegistration,
n.config.logger,
)
if err := metricsRegistration.Err(); err != nil {
metricsRegistration.Rollback()
return nil, fmt.Errorf("register metrics: %w", err)
}
// NewEventBus starts background async-worker goroutines, so create the bus
// only after configuration validates. If it were created earlier, a
// validation failure would return a nil Node while leaving those goroutines
// running, with no handle for the caller to Stop() them.
eventBus, err := event.TryNewEventBus(
n.config.promRegistry,
n.config.logger,
)
if err != nil {
metricsRegistration.Rollback()
// TryNewEventBus names the failed registration in its error.
return nil, err
}
n.eventBus = eventBus
// Everything registered above (build info, RTS gauges, the EventBus)
// lives for the node's entire lifetime and is never rebuilt, so it's
// registered directly against the pre-wrap registerer. Everything
// that reads n.config.promRegistry from here on — in Run() and in
// every node_lifecycle.go reinitialize call — goes through this
// wrapper instead, so a live restore/truncate can unregister and
// re-register it without a duplicate-collector panic.
if n.config.promRegistry != nil {
n.rebuildableMetrics = newRebuildableRegisterer(n.config.promRegistry)
n.config.promRegistry = n.rebuildableMetrics
}
return n, nil
}
// legacyUtxorpcTLSPolicy expresses the legacy root tlsCertFilePath/
// tlsKeyFilePath fields as an apiconfig.TLSPolicy, for UTxORPC only. It
// deliberately does not feed cfg.apiConfig.TLS (the shared api.tls default
// every provider inherits from): UTxORPC was the only provider these root
// fields ever configured TLS for, and promoting them to a shared default
// would silently switch Blockfrost/Kupo/Mesh from plaintext to TLS on upgrade
// for any deployment that set them, breaking existing plaintext clients.
// See ARCHITECTURE.md's "API security" section for this compatibility
// decision. Returns the zero TLSPolicy (no effect on the merge) unless
// both root fields are set.
func legacyUtxorpcTLSPolicy(cfg *Config) apiconfig.TLSPolicy {
if cfg.tlsCertFilePath == "" || cfg.tlsKeyFilePath == "" {
return apiconfig.TLSPolicy{}
}
mode := string(apiconfig.TLSModeServer)
return apiconfig.TLSPolicy{
Mode: &mode,
CertFilePath: &cfg.tlsCertFilePath,
KeyFilePath: &cfg.tlsKeyFilePath,
}
}
// apiProviderConfig merges the shared api.tls policy (and, for
// UTxORPC only, the legacy root TLS compatibility fields) into selection's
// own "tls" config section, field by field, and returns the result.
// It is the single place this merge happens, called both by the early
// plugin-selection validation in New() and by apiPluginSelection, so a
// provider config validated at startup and the one actually resolved at
// Start()/reinitializeAPIServers time can never diverge.
func (c *Config) apiProviderConfig(
capability plugin.Capability,
selection plugin.Selection,
) (plugin.Selection, error) {
var legacyTLS apiconfig.TLSPolicy
if capability == plugin.CapabilityAPIUtxorpc {
legacyTLS = legacyUtxorpcTLSPolicy(c)
}
merged, err := apiconfig.MergeProviderConfig(
selection.Config,
legacyTLS,
c.apiConfig.TLS,
)
if err != nil {
return selection, fmt.Errorf(
"merge api security policy for capability %s: %w",
capability, err,
)
}
selection.Config = merged
return selection, nil
}
// apiProviderConfigPath maps each API capability to the dotted config path
// its provider config lives at, for error messages -- see
// validateAPIProviderSecurityPolicy and each provider's own
// cfg.TLS.Resolve call, which uses the identical path.
var apiProviderConfigPath = map[plugin.Capability]string{
plugin.CapabilityAPIBlockfrost: "plugins.api.blockfrost.config",
plugin.CapabilityAPIKupo: "plugins.api.kupo.config",
plugin.CapabilityAPIMesh: "plugins.api.mesh.config",
plugin.CapabilityAPIUtxorpc: "plugins.api.utxorpc.config",
plugin.CapabilityAPIMcp: "plugins.api.mcp.config",
}
// validateAPIProviderSecurityPolicy resolves and validates the merged
// tls section of an API provider's config (already merged with the
// shared api.tls defaults by apiProviderConfig), surfacing a
// partial certificate/key pair or an invalid mode before any listener
// starts -- the same validation each provider's own RegisterProvider
// factory performs at Resolve()/Start() time, run here again so New()
// itself rejects it at construction, before Run() ever attempts to start
// a listener.
func validateAPIProviderSecurityPolicy(
configPath string,
rawConfig map[string]any,
) error {
tlsPolicy, err := apiconfig.DecodeTLSPolicy(rawConfig)
if err != nil {
return fmt.Errorf("%s.tls: %w", configPath, err)
}
if _, err := tlsPolicy.Resolve(configPath + ".tls"); err != nil {
// Resolve already prefixes its errors with the config path.
return err
}
return nil
}
func (n *Node) apiPluginSelection(
capability plugin.Capability,
) (plugin.Selection, uint, error) {
selection, ok := n.config.pluginSelections[capability]
if !ok {
return selection, 0, fmt.Errorf(
"plugin selection is missing for capability %s",
capability,
)
}
if selection.Provider == "" {
return selection, 0, fmt.Errorf(
"plugin provider is empty for capability %s",
capability,
)
}
if _, ok := apiProviderConfigPath[capability]; ok {
var err error
selection, err = n.config.apiProviderConfig(capability, selection)
if err != nil {
// apiProviderConfig names the capability in its error.
return selection, 0, err
}
}
portValue, ok := selection.Config["port"]
if !ok {
defaultPorts := map[plugin.Capability]uint{
plugin.CapabilityAPIBlockfrost: 3000,
plugin.CapabilityAPIKupo: 0,
plugin.CapabilityAPIMesh: 8080,
plugin.CapabilityAPIUtxorpc: 9090,
plugin.CapabilityAPIMcp: 0,
}
return selection, defaultPorts[capability], nil
}
var port uint64
switch value := portValue.(type) {
case int:
if value < 0 {
return selection, 0, fmt.Errorf("negative port for capability %s", capability)
}
port = uint64(value)
case uint:
port = uint64(value)
case uint64:
port = value
case int64:
if value < 0 {
return selection, 0, fmt.Errorf("negative port for capability %s", capability)
}
port = uint64(value)
case float64:
if value < 0 || value != float64(uint64(value)) {
return selection, 0, fmt.Errorf("invalid port for capability %s: %v", capability, value)
}
port = uint64(value)
default:
return selection, 0, fmt.Errorf("invalid port type for capability %s: %T", capability, portValue)
}
if port > 65535 {
return selection, 0, fmt.Errorf(
"port for capability %s exceeds 65535: %d",
capability,
port,
)
}
return selection, uint(port), nil
}
// effectiveBarkHost decides the interface Bark actually binds to.
// configuredHost (from --bark-host/DINGO_BARK_HOST/config) always wins when set
// -- an explicit operator choice. Otherwise, when lifecycleEnabled (the
// database lifecycle service's destructive Restore/Truncate/CreateSnapshot/
// etc. RPCs, or the remote Stop/Restart RPCs, will be mounted), this defaults
// to loopback-only rather than letting bark.go's own empty-Host default
// ("0.0.0.0") expose them on every interface; with no lifecycle service
// mounted, "" is returned unchanged so bark's own existing default behavior
// (all interfaces) is preserved for deployments only using it for the read-only
// Archive service. Bind address is a network control, independent of the mTLS
// client-certificate authentication and operator-fingerprint authorization
// checks Bark.Start enforces whenever lifecycleEnabled -- this default narrows
// exposure as defense in depth, it is not what makes those RPCs safe to reach.
func effectiveBarkHost(configuredHost string, lifecycleEnabled bool) string {
if configuredHost != "" {
return configuredHost
}
if lifecycleEnabled {
return "127.0.0.1"
}
return ""
}
// defaultMaxTxSubmissionsPerSecond is the per-peer transaction offer rate the
// node enforces on inbound TxSubmission.
const defaultMaxTxSubmissionsPerSecond = 100
// newOuroborosConfig builds the ouroboros configuration from the node's
// dependencies and settings. Run stores the result in n.ouroborosConfig, and
// the live restore path rebuilds from that copy, so the settings cannot differ
// between the two.
func (n *Node) newOuroborosConfig(
enableLeiosNetworking bool,
leiosTxFetchTailBudget time.Duration,
keepAliveTimeout time.Duration,
) ouroborosPkg.OuroborosConfig {
return ouroborosPkg.OuroborosConfig{
Logger: n.config.logger,
EventBus: n.eventBus,
ConnManager: n.connManager,
LedgerState: n.ledgerState,
LeiosAnnouncementLedger: n.ledgerState,
Mempool: n.mempool,
ChainsyncState: n.chainsyncState,
PeerGov: n.peerGov,
NetworkMagic: n.config.networkMagic,
PeerSharing: n.config.peerSharing,
IntersectTip: n.config.intersectTip,
IntersectPoints: n.config.intersectPoints,
PromRegistry: n.retainedComponentPromRegistry(),
ChainsyncBlockTimeout: n.config.chainsyncStallTimeout,
EnableLeios: enableLeiosNetworking,
LeiosPersistenceRetentionSlots: n.config.leiosPersistenceRetentionSlots,
// Bounds how long a LocalStateQuery session holds one ledger snapshot.
LocalStateQueryViewMaxLifetime: n.config.LocalStateQueryViewMaxLifetimeDuration(),
// Current prototype votes sign their announcing ranking-block hash and
// diffuse inline over leios-notify. Do not initiate protocol 20: its
// client requests legacy slot-plus-EB-hash votes, and an idle exact-count
// request eventually times out the shared bearer. The responder remains
// wired for legacy peers whose requests can be satisfied by legacy votes.
EnableLeiosVotes: false,
// Request endorser-block transaction bodies over leios-fetch, driven by
// the peer's transactions offer (MsgBlockTxsOffer) — the relay's signal
// that the EB's transactions are ready. Fetching before that offer
// (e.g. right after the manifest) makes the prototype relay reset the
// connection, so the fetch is gated on the txs offer, not the block
// offer. Best-effort: a fetch failure never tears down the shared
// connection.
EnableLeiosTxFetch: enableLeiosNetworking,
LeiosTxFetchTailBudget: leiosTxFetchTailBudget,
ChainsyncIngressEligible: n.isChainsyncIngressEligible,
ChainsyncHasBestPeer: n.chainsyncHasBestPeer,
ChainsyncApplyEligible: n.chainsyncApplyEligible,
ChainsyncAwaitEagerness: n.chainsyncAwaitEagerness,
ChainsyncAwaitCorroboration: n.chainsyncAwaitCorroboration,
ChainsyncObservePeerTip: n.chainsyncObservePeerTip,
ChainsyncPrepareForecastWitness: n.chainsyncPrepareForecastWitness,
ChainsyncRemoveForecastWitness: n.chainsyncRemoveForecastWitness,
ChainsyncResolvePeerTip: n.chainsyncResolvePeerTip,
ChainsyncObserveAwaitReply: n.chainsyncObserveAwaitReply,
ChainsyncSyncTarget: n.chainsyncSyncTarget,
ChainsyncObservePeerRollback: n.chainsyncObservePeerRollback,
// On the Musashi prototype network every mini-protocol shares one muxer
// to a single relay; block/EB traffic can delay the relay's keep-alive
// pong past the tight 10s gouroboros default, making dingo drop the
// only relay and pay a reconnect + fork rollback. Wait up to the
// keep-alive server timeout there so a slow-but-alive relay is not
// dropped. Unset on other networks (fast dead-peer eviction retained).
KeepAliveTimeout: keepAliveTimeout,
// Production bound on peer TxSubmission work. The ouroboros package
// leaves the limiter off at zero, so the node must set it.
MaxTxSubmissionsPerSecond: defaultMaxTxSubmissionsPerSecond,
}
}
// ouroboros returns the current Ouroboros instance. Callers resolve it through
// here rather than caching it, so a live restore's replacement is picked up
// automatically and the read is synchronized against the replacement.
func (n *Node) ouroboros() *ouroborosPkg.Ouroboros {
return n.ouroborosRef.Load()
}
// Run wires *ledger.LedgerState in as the mempool's TxValidator, and the
// mempool discovers the optional validation-session capability on it with a
// runtime type assertion, silently falling back to unpinned per-transaction
// validation when that fails. Guard the pairing here, in the package that
// makes it, so drift cannot quietly unpin mempool revalidation from its
// ledger snapshot.
var (
_ mempool.TxValidationSessionProvider = (*ledger.LedgerState)(nil)
_ mempool.TxSizeLimitProvider = (*ledger.LedgerState)(nil)
)
// The mempool resolves confirmed input addresses for its address index
// through the same validator's session, again by interface assertion; losing
// the method would leave those inputs out of the index with no error.
var _ mempool.ResolvingTxValidationSessionProvider = (*ledger.LedgerState)(nil)
//nolint:contextcheck // Run is the lifecycle boundary and derives n.ctx from the caller context.
func (n *Node) Run(ctx context.Context) (runErr error) {
// A signal can cancel ctx while this function is still constructing
// components. Hold the lifecycle gate until either the startup cleanup has
// finished or every component has started, so the command layer's Stop
// cannot tear down a component while the rollback is doing the same.
n.startupLifecycleMu.Lock()
startupGateHeld := true
var started []func()
// Set to false by a storage-using component's LIFO stop if it cannot confirm
// every background goroutine has exited. The db.Close and pluginHost.Stop
// LIFO stops registered below then skip closing storage a still-running
// goroutine may be using -- mirrors node_shutdown.go's shutdown()
// ledgerStateDrainConfirmed guard on the normal signal-driven path.
ledgerStateDrainConfirmed := true
// Set false if Ouroboros cannot confirm its persistence workers stopped.
// The DB and storage-provider cleanup below must then leave their backing
// storage open, just as they do for an unconfirmed ledger-state drain.
leiosPersistenceDrainConfirmed := true
defer func() {
if !startupGateHeld {
return
}
r := recover()
n.cleanupFailedStartup(started)
if r != nil {
panic(r)
}
}()
// Configure tracing
n.warnIfTracingMisconfigured()
if n.config.tracing {
if err := n.setupTracing(ctx); err != nil {
return fmt.Errorf("failed to set up tracing: %w", err)
}
}
n.ctx, n.cancel = context.WithCancel(ctx)
defer func() {
runErr = n.resolveRunError(runErr)
}()
// Start the RTS metrics updater goroutine. It samples runtime.MemStats
// on a ticker and exits when n.ctx is cancelled by the existing
// shutdown or startup-failure cleanup, so it does not need an entry in
// the `started` cleanup stack.
go n.runRTSMetricsUpdater(n.ctx, rtsMetricsUpdateInterval)
// Track started components for cleanup on failure
stopPluginCapability := func(capability plugin.Capability) func() {
return func() {
if err := n.pluginHost.StopCapability(
context.Background(),
capability,
); err != nil {
n.config.logger.Error(
"failed to stop plugin capability during cleanup",
"capability",
capability,
"error",
err,
)
}
}
}
// Register eventBus cleanup (created in New(), has background goroutines).
// Close (not Stop): startup-failure cleanup is terminal, and Stop restarts
// the async-worker pool, leaking those goroutines.
started = append(started, func() { n.eventBus.Close() })
started = append(started, func() {
// Skipped on an unconfirmed ledger state drain for the same reason
// the db.Close LIFO stop above is: storage plugins can be backed by
// the same n.db a still-running background goroutine may be using.
// This closure is registered before (so stops after) both the
// ledgerState.Close and db.Close stops below, so it observes
// ledgerStateDrainConfirmed's final value -- mirrors
// node_shutdown.go's shutdown() phase 3 guard on pluginHost.Stop.
if !ledgerStateDrainConfirmed || !leiosPersistenceDrainConfirmed {
n.config.logger.Error(
"skipping plugin host shutdown during startup-failure cleanup because a storage user drain was not confirmed",
)
return
}
if err := n.pluginHost.Stop(context.Background()); err != nil {
n.config.logger.Error(
"failed to stop plugin host during cleanup",
"error",
err,
)
}
})
consensusSelection := n.config.consensusPluginSelection()
provider, err := plugin.Resolve[nodeconsensus.Provider](
n.ctx,
n.pluginHost,
plugin.CapabilityConsensus,
consensusSelection.Provider,
consensusSelection.Config,
struct{}{},
)
if err != nil {
return fmt.Errorf("failed to resolve consensus plugin: %w", err)
}
n.consensusProvider = provider
// Reconcile a live Restore's directory swap (node_lifecycle.go's
// swapInRestoredDataDir) that was interrupted by a crash, process
// kill, or power failure before it could be confirmed and cleaned up
// -- must run before anything else below opens n.config.dataDir.
if err := n.reconcileInterruptedRestore(n.ctx); err != nil {
return err
}
// Resolve provider-owned storage before constructing the database that uses
// it. The startup cleanup stack stops any provider that started before a
// later storage resolution failure.
deps, err := n.storageDependencies(n.config.dataDir)
if err != nil {
return err
}
deps.PromRegistry = n.config.promRegistry
stores, err := internalplugins.ResolveStorage(
n.ctx, n.pluginHost, n.storageSelections(), deps,
)
if err != nil {
return fmt.Errorf("failed to resolve storage plugins: %w", err)
}
// Load database
dbNeedsRecovery := false
dbConfig := n.databaseConfig()
db, err := database.New(ctx, dbConfig, stores)
if db == nil {
if err != nil {
n.config.logger.Error(
"failed to create database",
"error",
err,
)
return fmt.Errorf("failed to create database: %w", err)
}
n.config.logger.Error(
"failed to create database",
"error",
"empty database returned",
)
return errors.New("empty database returned")
}
n.db = db
// ledgerStateDrainConfirmed (declared above) is set false by the
// ledgerState.Close LIFO stop below on an unconfirmed drain; this
// closure runs after that one in LIFO order (registered first, so
// stopped last), so it observes the flag's final value.
started = append(started, func() {
if !ledgerStateDrainConfirmed || !leiosPersistenceDrainConfirmed {
n.config.logger.Error(
"skipping database close during startup-failure cleanup because a storage user drain was not confirmed",
)
return
}
n.db.Close()
})
if err != nil {
if _, ok := errors.AsType[database.CommitTimestampError](err); !ok {
return fmt.Errorf("failed to open database: %w", err)
}
n.config.logger.Warn(
"database initialization error, needs recovery",
"error",
err,
)
dbNeedsRecovery = true
}
// Built before the node settings gate persists anything: a setting the
// gate would latch can make the node's own interrupted snapshot restore
// impossible to finish, and refusing first keeps the setting reversible.
n.mithrilSource = n.newMithrilSource()
if err := n.checkSnapshotRestoreSettings(n.ctx); err != nil {
return err
}
if dbNeedsRecovery {
// A database awaiting recovery has a known-inconsistent commit
// state. Enforcing gates against it here could report a spurious
// mismatch that masks the recovery path that is about to repair
// it, so both phases are deferred until
// RecoverCommitTimestampConflict has run, below. database.New
// never got to call phase 1 (CheckNodeSettings) on this path
// either -- checkCommitTimestamp failed first and New returned
// immediately -- so phase 1 is not just deferred here, it has not
// run for this startup at all until the deferred call below.
n.config.logger.Info(
"node settings gate enforcement deferred until database recovery completes",
)
} else {
if err := n.enforceConsensusDatabaseIdentity(); err != nil {
return fmt.Errorf("consensus database compatibility: %w", err)
}
if err := n.db.EnforceNodeSettings(ctx, n.nodeSettingsGateValues()); err != nil {
return fmt.Errorf("node settings: %w", err)
}
}
if pending, pendingErr := lifecycle.GetPendingTruncate(n.db); pendingErr != nil {
return fmt.Errorf(
"check for interrupted database truncate: %w",
pendingErr,
)
} else if pending != nil {
return fmt.Errorf(
"database truncate was interrupted after it started (target slot %d, target id %d); rerun the truncate operation before starting the node",
pending.TargetSlot,
pending.TargetID,
)
}
// Before the ledger is built: its commit-timestamp recovery rolls back,
// and so does the chain ingest it starts.
if err := n.repairCriticalIndexesBeforeIngest(ctx); err != nil {
return err
}
// Snapshot mode restores into an empty database here, before the chain
// manager and the ledger state read it, so both are built on the
// restored chain and the node goes live only once the restore is done.
if err := n.mithrilSnapshotStartup(n.ctx); err != nil {
return err
}
// Load chain manager
cm, err := chain.NewManager(
ctx,
n.db,
n.eventBus,
n.config.promRegistry,
)
if err != nil {
return fmt.Errorf("failed to load chain manager: %w", err)
}
n.chainManager = cm
n.chainsyncIngressEligibilityCache = make(
map[ouroboros.ConnectionId]bool,
)
// The Dijkstra ledger era and the Leios node-to-node mini-protocols are
// both enabled on the Leios testnet (and via explicit opt-in). The Leios
// protocols dingo offers beyond what the prototype relays serve — the
// standalone leios-votes protocol and leios-fetch BlockTxsRequest — are
// gated off for the prototype network below, since initiating them resets
// the connection. See Config.experimentalDijkstraEnabled /
// experimentalLeiosNetworkingEnabled.
enableDijkstra := n.config.experimentalDijkstraEnabled()
enableLeiosNetworking := n.config.experimentalLeiosNetworkingEnabled()
// Initialize Ouroboros
// The endorser-block tx fetch keeps re-requesting an EB's still-diffusing
// tail for up to the Leios diffusion window before giving up (the relay
// diffuses an EB's transactions over several seconds, so the last partial
// window lags). Derived from the pipeline timing (DiffuseWindowSlots) and
// the Shelley slot length; zero disables the retry (e.g. networking off or
// unknown slot length).
var leiosTxFetchTailBudget time.Duration
if enableLeiosNetworking && n.config.cardanoNodeConfig != nil {
if sg := n.config.cardanoNodeConfig.ShelleyGenesis(); sg != nil {
if secs, _ := sg.SlotLength.Float64(); secs > 0 {
leiosTxFetchTailBudget = time.Duration(
float64(n.leiosPipelineTiming().DiffuseWindowSlots) *
secs * float64(time.Second),
)
}
}
}
// On Musashi wait up to the same keep-alive server timeout bound that the
// ouroboros layer enforces; elsewhere leave it 0 so gouroboros keeps its
// default.
var keepAliveTimeout time.Duration
if n.config.isMusashiNetwork() {
keepAliveTimeout = okeepalive.ServerTimeout
}
// n.ouroboros is constructed further down, once every dependency it
// requires exists. Nothing between here and there dereferences it: the
// callbacks handed to ledger, connmanager and peergov below are closures
// that resolve n.ouroboros when they fire, not method values bound now.
// Load state
state, err := ledger.NewLedgerState(n.ledgerStateConfig())
if err != nil {
return fmt.Errorf("failed to load state database: %w", err)
}
n.setLedgerState(state)
started = append(started, func() {
// Start can fail after launching database workers. Drain even a
// partially started ledger before the earlier storage cleanup runs.
if err := n.ledgerState.Close(); err != nil {
ledgerStateDrainConfirmed = false
runErr = errors.Join(runErr, errStorageDrainUnconfirmed, err)
n.config.logger.Error(
"ledger startup rollback did not drain; preserving storage",
"error",
err,
)
}
})
// n.ouroboros is constructed once every dependency exists; see the
// NewOuroboros call below.
if err := n.chainManager.SetLedger(n.ledgerState); err != nil {
return fmt.Errorf(
"failed to configure chain security parameter: %w",
err,
)
}
if n.config.barkBaseUrl != "" {
barkBlobStore, err := bark.NewBarkBlobStore(bark.BlobStoreBarkConfig{
BaseUrl: n.config.barkBaseUrl,
BlockDownloadAllowedHosts: n.config.barkBlockDownloadHosts,
BlockDownloadAllowPrivateAddresses: n.config.barkBlockDownloadAllowPrivateAddresses,
MaxBlockSize: state.MaxBlockSize,
HTTPClient: &http.Client{
Timeout: 30 * time.Second,