-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathnode.go
More file actions
2529 lines (2455 loc) · 97.6 KB
/
Copy pathnode.go
File metadata and controls
2529 lines (2455 loc) · 97.6 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"
"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/config/cardano"
"github.com/blinklabs-io/dingo/connmanager"
"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/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/node/ledgerpeers"
"github.com/blinklabs-io/dingo/internal/offchainmetadata"
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/leader"
"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"
ochainsync "github.com/blinklabs-io/gouroboros/protocol/chainsync"
okeepalive "github.com/blinklabs-io/gouroboros/protocol/keepalive"
olocalstatequery "github.com/blinklabs-io/gouroboros/protocol/localstatequery"
)
type Node struct {
connManager *connmanager.ConnectionManager
peerGov *peergov.PeerGovernor
// 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
eventBus *event.EventBus
pluginHost *plugin.Host
destinationRegistry *lifecycle.DestinationRegistry
mempool mempool.Service
chainManager *chain.ChainManager
db *database.Database
ledgerState *ledger.LedgerState
snapshotMgr *snapshot.Manager
dbLifecycleMgr *dblifecycle.Manager
leiosVoteManager *leios.VoteManager
leiosPipelineManager *leios.PipelineManager
bark *bark.Bark
historyExpiry *historyexpiry.Pruner
committeeAuthSync *committeeauth.Syncer
koiosParityObserver *koiosparity.Observer
midnightServer *midnightserver.Server
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]
// 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
// 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 *leader.Election
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
// 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 snapshotMu is always liveLifecycleMu, 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
// 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
}
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,
}
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)
}
// 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)
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()
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 {
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 {
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 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 ""
}
// 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)
//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 the ledgerState.Close 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
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 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 {
n.config.logger.Error(
"skipping plugin host shutdown during startup-failure cleanup because ledger state 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,
)
}
})
// 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.reconcileInterruptedLiveRestoreSwap(); err != nil {
return fmt.Errorf(
"reconcile interrupted live restore swap: %w", 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.
stores, err := internalplugins.ResolveStorage(
n.ctx,
n.pluginHost,
internalplugins.StorageSelections{
Blob: n.config.pluginSelections[plugin.CapabilityStorageBlob],
Metadata: n.config.pluginSelections[plugin.CapabilityStorageMetadata],
},
internalplugins.StorageDependencies{
DataDir: n.config.dataDir, RunMode: n.config.runMode,
StorageMode: string(n.config.storageMode),
MaxConnections: n.config.DatabaseWorkerPoolConfig.WorkerPoolSize,
Logger: n.config.logger, PromRegistry: n.config.promRegistry,
TracingEnabled: n.config.tracing,
},
)
if err != nil {
return err
}
// Load database
dbNeedsRecovery := false
dbConfig := &database.Config{
DataDir: n.config.dataDir,
Logger: n.config.logger,
PromRegistry: n.config.promRegistry,
StorageMode: string(n.config.storageMode),
Network: n.config.network,
NetworkMagic: n.config.networkMagic,
StartEra: string(n.config.startEra),
StrictUtxoValidation: n.config.strictUtxoValidation,
BlobPlugin: n.config.pluginSelections[plugin.CapabilityStorageBlob].
Provider,
MetadataPlugin: n.config.pluginSelections[plugin.CapabilityStorageMetadata].
Provider,
CacheConfig: database.CborCacheConfig{
BlockLRUEntries: n.config.cacheBlockLRUEntries,
HotUtxoEntries: n.config.cacheHotUtxoEntries,
HotTxEntries: n.config.cacheHotTxEntries,
HotTxMaxBytes: n.config.cacheHotTxMaxBytes,
},
AlonzoLovelacePerUtxoWord: cardano.AlonzoLovelacePerUtxoWord(
n.config.cardanoNodeConfig, "", n.config.network,
),
}
db, err := database.New(dbConfig, stores)
if db == nil {
if err != nil {
n.config.logger.Error(
"failed to create database",
"error",
err,
)
return 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 {
n.config.logger.Error(
"skipping database close during startup-failure cleanup because ledger state 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
}
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.db.EnforceNodeSettings(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,
)
}
// Load chain manager
cm, err := chain.NewManager(
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.ledgerState = state
// 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,
HTTPClient: &http.Client{
Timeout: 30 * time.Second,
},
}, n.db.Blob())
if err != nil {
return fmt.Errorf("failed to create bark blob store: %w", err)
}
// The wrapper's upstream is the store it replaces and its Close
// forwards there, so the replaced store stays in use: there is
// nothing to drain and nothing to close. Both results are
// deliberately discarded.
n.db.SetBlobStore(barkBlobStore)
}
// Recovery changes both the ledger tip and blob contents. Complete it
// before starting background maintenance that reads or prunes either store.
if dbNeedsRecovery {
if err := n.ledgerState.RecoverCommitTimestampConflict(); err != nil {
return fmt.Errorf("failed to recover database: %w", err)
}
if err := n.enforceRecoveredNodeSettings(); err != nil {
return err
}
}
if n.config.historyExpiry.Enabled {
prunerFreq := n.config.historyExpiry.Frequency
if prunerFreq <= 0 {
prunerFreq = time.Hour
}
n.historyExpiry = historyexpiry.NewPruner(historyexpiry.PrunerConfig{
LedgerState: state,
DB: n.db,
Logger: n.config.logger,
Frequency: prunerFreq,
})
if err := n.historyExpiry.Start(n.ctx); err != nil {
return fmt.Errorf("failed to start history expiry: %w", err)
}
started = append(started, func() {
_ = n.historyExpiry.Stop(context.Background())
})
}
// Unconditional and independent of history expiry: the committee
// hot-key authorization pruner in the metadata store always runs and
// always needs the live immutable-slot bound to be safe on a sparse
// chain. A sync failure here is not fatal -- the pruner
// falls back to its slot-window assumption when no live value has been
// pushed -- so this only logs.
n.committeeAuthSync = committeeauth.NewSyncer(committeeauth.SyncerConfig{
PointAtDepth: state.Chain().PointAtDepth,
SecurityParam: state.SecurityParam,
SetImmutableSlot: n.db.SetCommitteeAuthImmutableSlot,
Logger: n.config.logger,
})
if err := n.committeeAuthSync.Start(n.ctx); err != nil {
n.config.logger.Warn(
"failed to start committee auth immutable slot sync",
"error", err,
)
} else {
started = append(started, func() {
_ = n.committeeAuthSync.Stop(context.Background())
})
}
if err := n.backfillRewardLiveStake(); err != nil {
return err
}
// Create and start the Midnight indexer before LedgerState.Start so that
// (a) the synchronous backfill runs while no new blocks can arrive, and
// (b) the EventBus subscription exists before any BlockActionApply events
// can be emitted, eliminating the startup gap. The
// epoch cache is loaded first because Midnight backfill writes epoch-keyed
// Ariadne/candidate rows. Both the explicit opt-in and API storage mode
// are required: the indexer depends on the api-mode indexes to function,
// and storage mode alone is no longer sufficient to start it (an api-mode
// deployment may not want Midnight indexing at all).
if midnightIndexerActive(n.config.storageMode, n.config.midnight) {
if err := n.ledgerState.PrepareEpochCacheForStartup(); err != nil {
return fmt.Errorf(
"load epoch cache before Midnight indexer start: %w",
err,
)
}
midnightIdx, err := midnightindexer.New(n.midnightIndexerConfig())
if err != nil {
return fmt.Errorf("creating midnight indexer: %w", err)
}
n.midnightIndexer = midnightIdx
n.config.logger.Info(
"midnight indexer created, running backfill and subscribing to live events",
)
if err := n.midnightIndexer.Start(); err != nil {
return fmt.Errorf("starting midnight indexer: %w", err)
}
}
// Initialize snapshot manager for stake snapshot capture and wire the
// authoritative epoch-boundary capture hooks before n.ledgerState.Start
// below, whose slot-clock/block-processing goroutines are what can
// first fire an epoch rollover: an epoch boundary reached before these
// hooks exist would fall back to the event-driven capture only, and — if
// the Koios parity observer is also enabled — race the observer's own
// event.EpochTransitionEvent subscription into validating an epoch whose
// reward rows the snapshot manager never got a chance to commit via
// these hooks. Configuring both before the observer is wired below (and
// both before Start) keeps the dependency ordering unambiguous: hooks
// configured → observer subscribed → ledger started.
n.snapshotMgr = snapshot.NewManager(
n.db,
n.eventBus,
n.config.logger,
)
// Mirror the CIP-0163 reward-account inactivity gate into snapshot capture
// so it matches the ledger config that drives account expiry stamping.
if err := n.snapshotMgr.SetDelegatorInactivity(
n.config.delegatorInactivityEnabled,
n.config.delegatorInactivity,
); err != nil {
return fmt.Errorf("configuring snapshot manager: %w", err)
}
n.snapshotMgr.SetPromRegistry(n.config.promRegistry)
// When the Koios parity observer is enabled, retain reward_account_output
// without bound in CORE storage mode too: the observer only
// validates a closed epoch after fetching and comparing against Koios over
// the network, which can fall arbitrarily far behind chain progression
// during a from-genesis or catch-up sync, well past the fixed 4-epoch
// window cleanupOldSnapshots otherwise prunes reward_account_output to.
// Set before CaptureGenesisSnapshot/Start below, matching every other
// snapshot-manager configuration call in this sequence.
n.snapshotMgr.SetRewardAccountOutputRetentionUnbounded(
n.config.koiosParity.Enabled,
)
// Prune pool snapshots through the deferred-header retention guard, so a
// snapshot a queued/deferred header still needs for leader validation is
// never pruned out from under it and misread as pool absence, and the
// floor selection is atomic with deferred-header admission.
// Set before Start; the pin is released automatically as headers resolve.
n.snapshotMgr.SetPoolSnapshotRetentionGuard(
n.ledgerState.PrunePoolSnapshotsWithRetentionFloor,
)
// Wire the authoritative epoch-boundary capture before block sync begins so
// each epoch rollover stages its mark snapshot atomically at the SNAP point.
// Set before CaptureGenesisSnapshot/sync; a nil hook (never set) would leave
// only the event-driven fallback capture.
// The stake read runs at the SNAP point (after MIR and before POOLREAP/
// enactment) and
// the row write at the end of the rollover, both inside the same
// transaction.
n.ledgerState.SetEpochBoundarySnapshotStakeHook(
func(txn *database.Txn, evt event.EpochTransitionEvent) error {
return n.snapshotMgr.ComputeEpochBoundarySnapshot(n.ctx, txn, evt)
},
)
n.ledgerState.SetEpochBoundarySnapshotHook(
func(txn *database.Txn, evt event.EpochTransitionEvent) error {
return n.snapshotMgr.CaptureEpochBoundarySnapshot(n.ctx, txn, evt)
},
)
wireDeferredRewardStakeInputs(n.ledgerState, n.snapshotMgr)
// Wire governance's same-boundary SPO stake read: RATIFY
// tallies mark[NewEpoch] -- this same boundary's own mark snapshot -- but
// that row is not durably written until the hook above runs, later in
// the same rollover. Without this, governance would silently see zero
// SPO stake for every SPO-gated action at every boundary.
n.ledgerState.SetCurrentBoundarySPOStakeHook(
func(
txn *database.Txn,
evt event.EpochTransitionEvent,
) ([]*models.PoolStakeSnapshot, error) {
return n.snapshotMgr.CurrentBoundarySPOStakeRows(n.ctx, txn, evt)
},
)
// A Conway boundary leaves its mark snapshot to the ledger's post-commit
// job, which rebuilds the SNAP point from a read transaction pinned at the
// boundary's commit.
n.ledgerState.SetDeferredEpochBoundarySnapshotHooks(
n.snapshotMgr.DeferEpochBoundaryCapture,
n.snapshotMgr.DiscardEpochBoundaryCapture,
func(
txn *database.Txn,
evt event.EpochTransitionEvent,
) (ledger.DeferredBoundarySnapshot, error) {
return n.snapshotMgr.PrepareEpochBoundarySnapshot(n.ctx, txn, evt)
},
)
// Optional in-process Koios reward-parity observer. Wired
// (and, critically, subscribed to event.EpochTransitionEventType) before
// n.ledgerState.Start below, whose slot-clock/block-processing
// goroutines are what can first publish that event — see
// startKoiosParityObserver's doc comment (node_koiosparity.go). Wired
// after the snapshot-manager hooks immediately above, so an epoch
// boundary the observer reacts to always has its reward rows committed
// via those hooks first.
if n.config.koiosParity.Enabled {
if err := n.startKoiosParityObserver(); err != nil {
return fmt.Errorf("starting koios parity observer: %w", err)
}
started = append(started, func() {
stopCtx, cancel := context.WithTimeout(
context.Background(), n.configuredShutdownTimeout(),
)
defer cancel()
if err := n.koiosParityObserver.Stop(stopCtx); err != nil {
n.config.logger.Error(
"failed to stop koios parity observer during cleanup",
"error", err,
)
}
})
}