-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathnode_forging.go
More file actions
1528 lines (1422 loc) · 49.3 KB
/
Copy pathnode_forging.go
File metadata and controls
1528 lines (1422 loc) · 49.3 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 (
"bytes"
"context"
"encoding/hex"
"errors"
"fmt"
"log/slog"
"math/big"
"time"
"github.com/blinklabs-io/bursa"
"github.com/blinklabs-io/dingo/chain"
"github.com/blinklabs-io/dingo/database"
"github.com/blinklabs-io/dingo/database/models"
"github.com/blinklabs-io/dingo/internal/leiosheader"
"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/hardfork"
"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"
"github.com/blinklabs-io/gouroboros/consensus"
gledger "github.com/blinklabs-io/gouroboros/ledger"
lcommon "github.com/blinklabs-io/gouroboros/ledger/common"
gdijkstra "github.com/blinklabs-io/gouroboros/ledger/dijkstra"
"github.com/blinklabs-io/gouroboros/ledger/shelley"
ochainsync "github.com/blinklabs-io/gouroboros/protocol/chainsync"
ocommon "github.com/blinklabs-io/gouroboros/protocol/common"
)
func (n *Node) validateBlockProducerStartup() (*forging.PoolCredentials, error) {
if _, err := n.blockProducerShelleyGenesis(); err != nil {
return nil, err
}
if n.ledgerState == nil {
return nil, errors.New(
"block producer mode requires ledger state for current slot",
)
}
if _, err := n.ledgerState.CurrentSlot(); err != nil {
if !errors.Is(err, ledger.ErrBeforeGenesis) {
return nil, fmt.Errorf("compute current slot: %w", err)
}
// Clock before genesis: preserve the historical hard fail through the
// strict preflight (an opcert can never be "current" before genesis).
return n.validateBlockProducerStartupForClock(0, true)
}
// The current wall-clock slot only reliably places an operational
// certificate in time when the confirmed era history spans the wall clock.
// A node importing from genesis or restarting far behind has confirmed
// history that stops at its newest applied era: CurrentSlot then
// extrapolates through that era's slot length — a fresh mainnet node
// judges the wall clock with Byron's 20s slots even though the real chain
// moved to one-second slots at epoch 208 — which cannot judge an opcert for
// the actual chain.
supportedSlot, supported, err := n.ledgerState.
WallClockSlotFromConfirmedHistory()
if err != nil {
return nil, fmt.Errorf(
"wall-clock slot from confirmed history: %w",
err,
)
}
return n.validateBlockProducerStartupForClock(supportedSlot, supported)
}
func (n *Node) validateBlockProducerStartupAtSlot(
currentSlot uint64,
) (creds *forging.PoolCredentials, retErr error) {
agentBacked := n.config.shelleyKESAgentSocket != ""
if agentBacked {
// Agent startup installs the client before the remaining credential
// validation below. Do not leave that client and its serve-key loop
// running when a later validation step rejects the credentials.
defer func() {
if retErr != nil {
n.closeKESAgentClient()
}
}()
}
creds, err := n.validateBlockProducerCredentialMaterial(currentSlot)
if err != nil {
return nil, err
}
genesis, err := n.blockProducerShelleyGenesis()
if err != nil {
return nil, err
}
if err := creds.ValidateKESPeriod(genesis, currentSlot); err != nil {
return nil, fmt.Errorf("validate KES period: %w", err)
}
currentPeriod, err := forging.CurrentKESPeriodFromGenesis(
genesis,
currentSlot,
)
if err != nil {
return nil, fmt.Errorf("compute current KES period: %w", err)
}
opCert := creds.GetOpCert()
if opCert == nil {
return nil, errors.New("block producer operational certificate is nil")
}
n.config.logger.Info(
"block producer credentials validated",
"component", "node",
"pool_id", creds.GetPoolID().String(),
"current_slot", currentSlot,
"current_kes_period", currentPeriod,
"opcert_kes_period", opCert.KESPeriod,
"opcert_counter", opCert.IssueNumber,
"opcert_expiry_period", creds.OpCertExpiryPeriod(),
)
return creds, nil
}
// validateBlockProducerStartupForClock decides how to judge the operational
// certificate given a wall-clock slot and whether the confirmed era history
// actually supports it.
//
// When supported, this is the strict historical preflight: a certificate
// staged for the future or already expired fails startup here. When not
// supported, the KES-period plausibility check is deferred rather than
// skipped — credential material is still validated and the protocol lifetime
// is still armed, so the forger's per-slot gate has the data it needs to
// reject the certificate before Praos leader selection.
//
// Split out from validateBlockProducerStartup so both branches are reachable
// without a live LedgerState, the same reason
// validateBlockProducerStartupAtSlot and validateBlockProducerLedgerWithView
// exist separately.
func (n *Node) validateBlockProducerStartupForClock(
slot uint64,
supported bool,
) (creds *forging.PoolCredentials, retErr error) {
if supported {
return n.validateBlockProducerStartupAtSlot(slot)
}
if n.config.shelleyKESAgentSocket != "" {
defer func() {
if retErr != nil {
n.closeKESAgentClient()
}
}()
}
creds, err := n.validateBlockProducerCredentialMaterial(slot)
if err != nil {
return nil, err
}
genesis, err := n.blockProducerShelleyGenesis()
if err != nil {
return nil, err
}
if err := creds.ArmKesProtocolLifetime(genesis); err != nil {
return nil, fmt.Errorf("arm KES protocol lifetime: %w", err)
}
opCert := creds.GetOpCert()
if opCert == nil {
return nil, errors.New("block producer operational certificate is nil")
}
var tipSlot uint64
if n.ledgerState != nil {
tipSlot = n.ledgerState.ChainTipSlot()
}
n.config.logger.Warn(
"block producer startup: confirmed era history does not span the current wall-clock slot yet; "+
"deferring the operational-certificate KES-period plausibility check until the ledger catches up. "+
"The opcert KES lifetime is re-checked per slot and forging cannot proceed while it fails; "+
"sync progress additionally gates forging whenever an upstream peer is active.",
"component",
"node",
"tip_slot",
tipSlot,
"opcert_kes_period",
opCert.KESPeriod,
"opcert_expiry_period",
creds.OpCertExpiryPeriod(),
)
return creds, nil
}
// validateBlockProducerCredentialMaterial loads the pool credentials and
// validates the operational certificate's structure and cold-key signature,
// without judging it against any slot. The slot-dependent KES-period
// plausibility check lives in validateBlockProducerStartupAtSlot; callers
// needing the certificate armed but not yet placed in time combine this with
// PoolCredentials.ArmKesProtocolLifetime.
func (n *Node) validateBlockProducerCredentialMaterial(
currentSlot uint64,
) (*forging.PoolCredentials, error) {
creds := forging.NewPoolCredentials()
if n.config.shelleyKESAgentSocket != "" {
if err := n.loadBlockProducerCredentialsFromAgent(
creds,
currentSlot,
); err != nil {
return nil, fmt.Errorf(
"load pool credentials from KES agent: %w",
err,
)
}
} else if err := creds.LoadFromFiles(
n.config.shelleyVRFKey,
n.config.shelleyKESKey,
n.config.shelleyOperationalCertificate,
); err != nil {
return nil, fmt.Errorf("load pool credentials: %w", err)
}
if err := creds.ValidateOpCert(); err != nil {
return nil, fmt.Errorf("validate operational certificate: %w", err)
}
return creds, nil
}
// loadBlockProducerCredentialsFromAgent dials the configured KES agent and
// installs its material into creds, in either serve-key or sign mode. VRF and
// the operational certificate are always still read from local files; the
// KES agent protocol carries only the KES signing key (and, in serve-key
// mode, the opcert alongside it).
//
// It closes and replaces any previously dialed agent client first: this
// method also runs on a live-lifecycle rebuild
// (reinitializeBlockProducer -> validateBlockProducerStartup), and must not
// leak the prior connection or its background goroutine.
func (n *Node) loadBlockProducerCredentialsFromAgent(
creds *forging.PoolCredentials,
currentSlot uint64,
) error {
n.closeKESAgentClient()
mode := n.config.shelleyKESAgentMode
if mode == "" {
mode = kesagent.ModeServeKey
}
switch mode {
case kesagent.ModeServeKey:
return n.startKESAgentServeKey(creds, currentSlot)
case kesagent.ModeSign:
return n.startKESAgentSign(creds)
default:
return fmt.Errorf("unknown KES agent mode %q", mode)
}
}
// startKESAgentServeKey blocks for the agent's initial key push, installs it,
// and starts a background loop that installs every subsequent push (a KES
// key rotation) for as long as the node runs.
func (n *Node) startKESAgentServeKey(
creds *forging.PoolCredentials,
startupSlot uint64,
) error {
opCertKey, err := bursa.LoadKeyFromFile(
n.config.shelleyOperationalCertificate,
)
if err != nil {
return fmt.Errorf(
"failed to load operational certificate for KES agent serve-key mode: %w",
err,
)
}
client, err := kesagent.NewClient(kesagent.Config{
SocketPath: n.config.shelleyKESAgentSocket,
Mode: kesagent.ModeServeKey,
Logger: n.config.logger,
Metrics: n.kesAgentClientMetrics(),
})
if err != nil {
return err
}
install := func(pk kesagent.PushedKey) error {
if pk.OpCert == nil || !bytes.Equal(
pk.OpCert.ColdVKey,
opCertKey.OpCertColdVKey,
) {
return errors.New(
"KES agent operational certificate cold key does not match local operational certificate",
)
}
return creds.LoadFromAgentServeKey(
n.config.shelleyVRFKey,
agentMaterialFromPushedKey(pk),
)
}
// Installing a push clears the validated KES protocol lifetime, exactly
// as LoadFromFiles does, so no credential can inherit a policy that was
// never checked against the material now installed. The initial push is
// followed by validateBlockProducerStartupAtSlot's own ValidateOpCert /
// ValidateKESPeriod, which re-establishes it; a push arriving later --
// a KES evolution, an opcert rotation, or a re-push after a reconnect --
// is not, so the loop must re-establish it itself. Without this,
// credentialGeneration.kesSign refuses every signature after the first
// mid-run push with "operational certificate is not validated" and the
// node stops forging until it is restarted.
//
// Installed and validated in one call rather than two: as two, the
// credentials are published with their lifetime cleared for the duration
// of the validation, and a leader slot landing in that window is refused
// for exactly the reason this callback exists to prevent. Every rotation
// crosses it.
loopInstall := func(pk kesagent.PushedKey) error {
if pk.OpCert == nil || !bytes.Equal(
pk.OpCert.ColdVKey,
opCertKey.OpCertColdVKey,
) {
return errors.New(
"KES agent operational certificate cold key does not match local operational certificate",
)
}
genesis, err := n.blockProducerShelleyGenesis()
if err != nil {
return err
}
return creds.LoadFromAgentServeKeyValidated(
n.config.shelleyVRFKey,
agentMaterialFromPushedKey(pk),
genesis,
n.agentInstallSlot(startupSlot),
)
}
// The initial push must succeed before startup can proceed -- the same
// contract LoadFromFiles has (a load failure fails block-producer
// startup outright) -- bounded so a dead agent fails startup rather than
// hanging it.
//nolint:contextcheck // n.ctx is the node's lifecycle context; startup itself is bounded here
ctx, cancel := context.WithTimeout(
n.blockProducerContext(),
kesagent.DefaultHelloTimeout*2,
)
defer cancel()
pk, err := client.AwaitPushedKey(ctx)
if err != nil {
_ = client.Close()
return fmt.Errorf("await initial KES agent key push: %w", err)
}
// ledger/forging copies the key bytes it keeps, so this copy is dead as
// soon as the install returns; Client.Run does the same for every later
// push.
installErr := install(pk)
pk.Wipe()
if installErr != nil {
_ = client.Close()
return installErr
}
n.kesAgentClient = client
//nolint:contextcheck // background loop is bound to the node's lifecycle, not this call
runCtx, runCancel := context.WithCancel(n.blockProducerContext())
n.kesAgentCancel = runCancel
go func() {
if err := client.Run(runCtx, loopInstall); err != nil &&
!errors.Is(err, context.Canceled) {
n.config.logger.Error(
"kes agent serve-key loop exited",
"error", err,
)
}
}()
return nil
}
// agentInstallSlot returns the slot an agent key install is validated
// against: the node's current slot, or fallbackSlot when no ledger state is
// wired or the slot clock cannot answer. Production block-producer startup
// always has ledger state -- validateBlockProducerStartup requires it before
// the agent path can run -- so the fallback exists for the same reason
// blockProducerContext's does: a test driving
// validateBlockProducerStartupAtSlot against a bare &Node{config} validates
// against the slot it passed in.
func (n *Node) agentInstallSlot(fallbackSlot uint64) uint64 {
if n.ledgerState == nil {
return fallbackSlot
}
currentSlot, err := n.ledgerState.CurrentSlot()
if err != nil {
return fallbackSlot
}
return currentSlot
}
// startKESAgentSign installs sign-mode credentials: VRF and the operational
// certificate from local files, KES signing delegated to the agent for the
// lifetime of the client. There is no background loop in this mode -- the
// agent evolves its own key internally on every Sign call.
func (n *Node) startKESAgentSign(creds *forging.PoolCredentials) error {
opCertKey, err := bursa.LoadKeyFromFile(
n.config.shelleyOperationalCertificate,
)
if err != nil {
return fmt.Errorf(
"failed to load operational certificate for KES agent sign mode: %w",
err,
)
}
client, err := kesagent.NewClient(kesagent.Config{
SocketPath: n.config.shelleyKESAgentSocket,
Mode: kesagent.ModeSign,
SignTimeout: n.config.shelleyKESAgentSignTimeout,
KESVKey: opCertKey.VKey,
OpCertStartPeriod: opCertKey.OpCertKesPeriod,
Logger: n.config.logger,
Metrics: n.kesAgentClientMetrics(),
})
if err != nil {
return err
}
if err := creds.LoadFromAgentSign(
n.config.shelleyVRFKey,
n.config.shelleyOperationalCertificate,
client,
); err != nil {
_ = client.Close()
return err
}
n.kesAgentClient = client
return nil
}
func (n *Node) kesAgentClientMetrics() *kesagent.Metrics {
if n.kesAgentMetrics == nil && n.config.promRegistry != nil {
n.kesAgentMetrics = kesagent.NewMetrics(n.config.promRegistry)
}
return n.kesAgentMetrics
}
// agentMaterialFromPushedKey adapts a validated kesagent.PushedKey to
// ledger/forging's own AgentKESMaterial shape, keeping ledger/forging free of
// a dependency on the kesagent package.
func agentMaterialFromPushedKey(
pk kesagent.PushedKey,
) forging.AgentKESMaterial {
return forging.AgentKESMaterial{
AbsolutePeriod: pk.AbsolutePeriod,
KESSKeyData: pk.KESSKeyData,
KESVKey: pk.KESVKey,
OpCert: forging.OpCert{
KESVKey: pk.OpCert.KESVKey,
IssueNumber: pk.OpCert.IssueNumber,
KESPeriod: pk.OpCert.KESPeriod,
Signature: pk.OpCert.ColdSig,
ColdVKey: pk.OpCert.ColdVKey,
},
}
}
// blockProducerContext returns n.ctx, or context.Background() when it is
// nil. Production nodes always have n.ctx set by Run() before block-producer
// startup runs; the fallback exists only so a test that exercises
// validateBlockProducerStartupAtSlot directly against a bare &Node{config}
// (the established pattern in node_forging_test.go) does not have to
// construct a full node lifecycle just to dial a KES agent.
func (n *Node) blockProducerContext() context.Context {
if n.ctx != nil {
return n.ctx
}
return context.Background()
}
// closeKESAgentClient stops the serve-key background loop (if any) and
// closes the agent connection. Safe to call when neither exists.
func (n *Node) closeKESAgentClient() {
if n.kesAgentCancel != nil {
n.kesAgentCancel()
n.kesAgentCancel = nil
}
if n.kesAgentClient != nil {
if err := n.kesAgentClient.Close(); err != nil {
n.config.logger.Warn(
"failed to close KES agent client",
"error", err,
)
}
n.kesAgentClient = nil
}
}
func (n *Node) blockProducerShelleyGenesis() (*shelley.ShelleyGenesis, error) {
// KES-period plausibility requires a Shelley genesis. Block producer
// mode without one is unsafe — a node with no genesis cannot tell
// whether the opcert is current — so refuse to start.
if n.config.cardanoNodeConfig == nil {
return nil, errors.New(
"block producer mode requires Cardano node config with Shelley genesis",
)
}
genesis := n.config.cardanoNodeConfig.ShelleyGenesis()
if genesis == nil {
return nil, errors.New(
"block producer mode requires Shelley genesis information",
)
}
return genesis, nil
}
// blockProducerLedgerView adapts ledger.LedgerState to
// forging.LedgerView. The interface lives in the forging package so the
// credential check can stay free of a ledger import; the concrete
// adapter belongs here in package dingo where both types are visible.
type blockProducerLedgerView struct {
ls *ledger.LedgerState
}
func (v blockProducerLedgerView) PoolRegistrationVRFKeyHash(
poolID [28]byte,
) ([32]byte, bool, error) {
return v.ls.PoolRegistrationVRFKeyHash(poolID)
}
func (v blockProducerLedgerView) LatestOpCertSequence(
poolID [28]byte,
) (uint64, bool, error) {
return v.ls.LatestOpCertSequence(poolID)
}
// blockProducerEraSource supplies the era context for the startup
// operational-certificate counter check. *ledger.LedgerState implements it.
type blockProducerEraSource interface {
forging.ProtocolParamsProvider
// Tip is the applied-chain tip. Its slot scopes the counter rule.
Tip() ochainsync.Tip
// CurrentSlot is the wall-clock slot. It is read only to report how far
// the applied tip lags; it must not scope the counter rule.
CurrentSlot() (uint64, error)
}
// validateBlockProducerLedger runs the ledger-aware cross-check against
// the loaded credentials. Must be called after the ledger has started so
// pool registrations can be queried. A pool that is not yet registered
// is logged as a warning and the node is allowed to continue.
func (n *Node) validateBlockProducerLedger(
creds *forging.PoolCredentials,
) error {
if n.ledgerState == nil {
return errors.New(
"block producer ledger cross-check requires ledger state",
)
}
return n.validateBlockProducerLedgerWithSource(
creds,
blockProducerLedgerView{ls: n.ledgerState},
n.ledgerState,
)
}
// validateBlockProducerLedgerWithSource resolves the slot whose era scopes the
// startup opcert counter rule, then runs the cross-check.
//
// The slot is the applied chain tip, never the wall clock. The counter
// baseline (LedgerView.LatestOpCertSequence) is produced by the applied-chain
// stage, so the era that scopes the rule has to be read from the same stage. A
// wall-clock slot makes LedgerState.ProtocolParamsForSlot forecast forward
// through the era shape: on a node whose applied tip lags -- interrupted sync,
// restart after downtime, restore from an older snapshot -- it resolves a
// Praos era the applied chain has not reached while the baseline is still
// pre-catch-up, so a pool several rotations into its life looks gapped and
// startup is refused, leaving the node unable to sync to the point that would
// make the baseline correct. LedgerState.CurrentOrTipSlot is not a substitute:
// it returns whichever of the two slots is ahead, which is the wall-clock slot
// in exactly that case.
func (n *Node) validateBlockProducerLedgerWithSource(
creds *forging.PoolCredentials,
view forging.LedgerView,
source blockProducerEraSource,
) error {
var slot uint64
if source != nil {
slot = source.Tip().Point.Slot
if wallSlot, wallErr := source.CurrentSlot(); wallErr == nil &&
wallSlot > slot {
n.config.logger.Warn(
"block producer opcert counter rule scoped to the applied chain tip, which is behind wall-clock time",
"component",
"node",
"tip_slot",
slot,
"wall_clock_slot",
wallSlot,
"slots_behind",
wallSlot-slot,
)
}
}
return n.validateBlockProducerLedgerWithViewAtSlot(
creds,
view,
source,
slot,
)
}
func (n *Node) validateBlockProducerLedgerWithViewAtSlot(
creds *forging.PoolCredentials,
view forging.LedgerView,
params forging.ProtocolParamsProvider,
slot uint64,
) error {
if creds == nil {
return errors.New("nil pool credentials")
}
result, err := creds.ValidateAgainstLedgerAtSlot(view, params, slot)
if result.EraUnevaluable != nil {
// Not evaluable is not violated. Startup continues; the forge loop
// applies the full era-scoped rule per won leader slot once the
// node is near the tip, and fails closed there.
n.config.logger.Warn(
"block producer opcert counter gap rule not evaluated at startup; the forge loop enforces it per leader slot",
"component",
"node",
"pool_id",
creds.GetPoolID().String(),
"slot",
slot,
"reason",
result.EraUnevaluable,
)
}
registered, vrfMatched := result.Registered, result.VRFMatched
if err != nil {
if errors.Is(err, forging.ErrVRFKeyHashMismatch) &&
n.config.network == "devnet" {
n.config.logger.Warn(
"devnet block producer VRF cross-check failed; node will continue",
"component",
"node",
"pool_id",
creds.GetPoolID().String(),
"error",
err,
)
return nil
}
return err
}
poolID := creds.GetPoolID().String()
switch {
case !registered:
n.config.logger.Warn(
"block producer pool not yet registered on chain; node will continue",
"component",
"node",
"pool_id",
poolID,
)
case vrfMatched:
n.config.logger.Info(
"block producer pool registration verified on chain",
"component", "node",
"pool_id", poolID,
)
default:
n.config.logger.Warn(
"block producer VRF cross-check skipped (seed-only VRF key)",
"component", "node",
"pool_id", poolID,
)
}
return nil
}
// handleGenesisSnapshotError returns a fatal error for block producers (which
// require the genesis snapshot for leader election) and logs a warning for
// relay nodes (which do not perform leader election).
func (n *Node) handleGenesisSnapshotError(err error) error {
return snapshot.HandleGenesisSnapshotError(
n.config.blockProducer,
n.config.logger,
err,
)
}
// applyForgeTuning is the runtime mapping for operator-configured forge knobs.
// Keeping the mapping together lets its test catch any setting that would
// otherwise stop affecting the forger when configuration wiring changes.
func applyForgeTuning(fc *forging.ForgerConfig, cfg *Config) {
fc.ForgeSyncToleranceSlots = cfg.forgeSyncToleranceSlots
fc.ForgeStaleGapThresholdSlots = cfg.forgeStaleGapThresholdSlots
fc.ForgeUpstreamStalenessSlots = cfg.forgeUpstreamStalenessSlots
fc.ForgeAppliedTipStalenessSlots = cfg.forgeAppliedTipStalenessSlots
fc.ForgeEndorserBlockStalenessSlots = cfg.forgeEndorserBlockStalenessSlots
fc.ForgeEBSelectionReserve = cfg.forgeEBSelectionReserve
fc.ForgeEBMaxTxRefs = cfg.forgeEBMaxTxRefs
fc.ForgeEBMaxBytes = cfg.forgeEBMaxBytes
}
// startBlockProducer validates the operator's credentials, starts leader
// election and the block forger, and returns Run's startup-cleanup stack with
// their stop appended.
//
// The stop is appended immediately after credential validation because that
// step may start a KES agent loop, and every later startup check can fail.
// Nil-guarded stops also cover failures while validating ledger credentials
// or starting the forger.
//
// The stack is returned rather than mutated in place because append may
// reallocate; the caller must use the returned slice on both the success and
// the error path.
func (n *Node) startBlockProducer(
ctx context.Context,
started []func(),
) ([]func(), error) {
creds, err := n.validateBlockProducerStartup()
if err != nil {
return started, fmt.Errorf(
"block producer startup validation failed: %w",
err,
)
}
started = append(started, func() {
if n.blockForger != nil {
n.blockForger.Stop()
}
n.closeKESAgentClient()
if n.leaderElection != nil {
logErrIfNotNil(
n.config.logger,
"failed to stop leader election during cleanup",
n.leaderElection.Stop(),
)
}
})
// Cross-check loaded credentials against ledger state. Mismatch
// against on-chain pool registration is fatal; "not yet
// registered" is a warning so operators can stage credentials
// before submitting the registration cert.
if err := n.validateBlockProducerLedger(creds); err != nil {
return started, fmt.Errorf(
"block producer credentials failed ledger check: %w",
err,
)
}
if err := n.initBlockForger(ctx, creds); err != nil {
return started, fmt.Errorf(
"failed to initialize block forger: %w",
err,
)
}
// Enable Leios vote emission when a vote signing key is
// configured (experimental, leios mode only)
if err := n.enableLeiosVoting(creds); err != nil {
return started, fmt.Errorf("failed to enable leios voting: %w", err)
}
// Wire forger's slot tracker into ledger state for slot
// battle detection. The forger is created after the ledger
// state, so we use the late-binding setter.
if n.blockForger != nil {
n.ledgerState.SetForgedBlockChecker(
n.blockForger.SlotTracker(),
)
n.ledgerState.SetForgingEnabled(true)
n.ledgerState.SetSlotBattleRecorder(
n.blockForger,
)
}
return started, nil
}
// initBlockForger initializes the block forger for production mode.
// This requires VRF, KES, and OpCert key files to be configured.
func (n *Node) initBlockForger(
ctx context.Context,
creds *forging.PoolCredentials,
) error {
if creds == nil {
return errors.New("nil pool credentials")
}
// Create mempool adapter for the forging package.
mempoolAdapter := &forgingMempoolAdapter{source: n.mempool}
// Create epoch nonce adapter for the builder
epochNonceAdapter := &epochNonceAdapter{ledgerState: n.ledgerState}
// Create block builder
builder, err := forging.NewDefaultBlockBuilder(forging.BlockBuilderConfig{
Logger: n.config.logger,
Mempool: mempoolAdapter,
PParamsProvider: n.ledgerState,
ChainTip: n.chainManager.PrimaryChain(),
EpochNonce: epochNonceAdapter,
Credentials: creds,
TxValidator: n.ledgerState,
})
if err != nil {
return fmt.Errorf("failed to create block builder: %w", err)
}
// Create block broadcaster for synchronous local chain adoption.
broadcaster := &blockBroadcaster{
chain: n.chainManager.PrimaryChain(),
logger: n.config.logger,
}
// Create the leader election component
// Convert pool ID from PoolId to PoolKeyHash (both are [28]byte)
poolID := creds.GetPoolID()
var poolKeyHash lcommon.PoolKeyHash
copy(poolKeyHash[:], poolID[:])
// Create adapters for the providers that leader.Election needs
stakeProvider := &stakeDistributionAdapter{ledgerState: n.ledgerState}
epochProvider := &epochInfoAdapter{ledgerState: n.ledgerState}
// Get VRF secret key from credentials
vrfSKey := creds.GetVRFSKey()
// Create leader election with real stake distribution
election := leader.NewElection(
poolKeyHash,
vrfSKey,
stakeProvider,
epochProvider,
n.eventBus,
n.config.logger,
)
election.SetPromRegistry(n.config.promRegistry)
if n.db != nil {
if scheduleStore := leader.NewSyncStateScheduleStore(
n.db.Metadata(),
); scheduleStore != nil {
election.SetScheduleStore(scheduleStore)
}
}
// Start leader election (subscribes to epoch transitions)
if err := election.Start(ctx); err != nil {
return fmt.Errorf("failed to start leader election: %w", err)
}
// Create slot clock adapter for the forger
slotClock := &slotClockAdapter{ledgerState: n.ledgerState}
// Wire Leios EB forging when the pipeline manager is available
// (i.e. Dijkstra era is enabled). Relay nodes and pre-Dijkstra
// block producers leave these nil and skip EB production.
var leiosChecker forging.LeiosProduceChecker
var leiosCerts forging.LeiosCertificateProvider
var leiosParent forging.LeiosParentAnnouncementProvider
var leiosEBCaster forging.EndorserBlockBroadcaster
var leiosMempool forging.MempoolProvider
if n.leiosPipelineManager != nil && n.ouroboros() != nil {
adapter := &leiosPipelineAdapter{
mgr: n.leiosPipelineManager,
chain: n.chainManager.PrimaryChain(),
endorserBlockTxHashes: n.ouroboros().EndorserBlockTxHashesByHash,
}
leiosChecker = adapter
leiosCerts = adapter
leiosParent = adapter
leiosEBCaster = n.ouroboros()
leiosMempool = mempoolAdapter
}
blockForged := n.ledgerState.RecordForgedBlock
if n.ouroboros() != nil {
blockForged = func(block gledger.Block, blockCbor []byte, latency time.Duration) {
n.ledgerState.RecordForgedBlock(block, blockCbor, latency)
if header, ok := block.Header().(*gdijkstra.DijkstraBlockHeader); ok {
if _, _, announces := header.LeiosAnnouncement(); announces {
n.ouroboros().EnqueueLeiosBlockAnnouncement(header.Cbor())
}
}
}
}
// Wire the durable last-forged-slot fence. A block producer must not
// start without it: the in-memory fallback cannot survive a restart,
// which is precisely the case the fence exists for. The forging
// package still tolerates a nil store for embedders and dev-mode
// wiring, so refuse here rather than there.
var forgeFence forging.ForgeFenceStore
if n.db != nil {
forgeFence = forging.NewSyncStateForgeFenceStore(
n.db.Metadata(),
poolKeyHash,
)
}
if forgeFence == nil {
_ = election.Stop()
return errors.New(
"block producer requires a metadata store for the forge fence",
)
}
// Always enforce aggregate reference-script limits before AddBlock.
// Full self-validation (header crypto, body-hash, per-tx ledger checks)
// runs too unless the operator explicitly opts out (fail closed by
// default).
blockValidator := newForgedBlockValidator(
n.ledgerState,
n.config.validateForgedBlock,
)
// Create the block forger with the real leader election
forgerCfg := forging.ForgerConfig{
Mode: forging.ModeProduction,
Logger: n.config.logger,
Credentials: creds,
LeaderChecker: election,
BlockBuilder: builder,
BlockBroadcaster: broadcaster,
ConfirmedTxs: mempoolAdapter,
BlockForged: blockForged,
SlotClock: slotClock,
// Equal-slot alternative forging. When a rival block already
// occupies the slot this node leads, the forger builds an
// alternative on the rival's predecessor and offers it to chain
// selection instead of conceding the slot -- ouroboros-consensus
// mkCurrentBlockContext's EQ case. The primary chain supplies the
// fork context; LedgerState arbitrates with the same Praos
// comparison a peer's competing block goes through.
ChainContext: n.chainManager.PrimaryChain(),
SiblingAdopter: n.ledgerState,
// Closure, not a method value: n.ouroboros is rebuilt live, so this
// resolves the current instance when the forge loop asks.
LeiosVerifiedEbSlot: func() uint64 {
return n.ouroboros().MaxVerifiedEndorserBlockSlot()
},
BlockValidator: blockValidator,
ForgeFence: forgeFence,
PromRegistry: n.config.promRegistry,
LeiosProduceChecker: leiosChecker,
LeiosEBBroadcaster: leiosEBCaster,
LeiosMempool: leiosMempool,
LeiosTxValidator: n.ledgerState,
LeiosCertificateProvider: leiosCerts,
LeiosParentAnnouncementProvider: leiosParent,
OpCertLedgerView: blockProducerLedgerView{
ls: n.ledgerState,
},
EraParams: n.ledgerState,
}
applyForgeTuning(&forgerCfg, &n.config)
forger, err := forging.NewBlockForger(forgerCfg)
if err != nil {
// Stop election to prevent goroutine leak
_ = election.Stop()
return fmt.Errorf("failed to create block forger: %w", err)
}
// Start the forger with the passed context
if err := forger.Start(ctx); err != nil {
// Stop election to prevent goroutine leak
_ = election.Stop()
return fmt.Errorf("failed to start block forger: %w", err)
}
// Store election for cleanup during shutdown only after the forger is
// fully created and running.
n.leaderElection = election
n.blockForger = forger
n.config.logger.Info(
"block forger started in production mode with leader election",
"pool_id", poolID.String(),
)
return nil
}
type mempoolTxView struct {
Hash string
Cbor []byte
Type uint
}
type mempoolTransactionSource interface {
Transactions() []mempool.MempoolTransaction
RemoveTxsByHash(hashes []string)
}
func mempoolTransactions(source mempoolTransactionSource) []mempoolTxView {
txs := source.Transactions()
result := make([]mempoolTxView, len(txs))
for i, tx := range txs {
result[i] = mempoolTxView{
Hash: tx.Hash,
Cbor: tx.Cbor,
Type: tx.Type,
}
}
return result
}
// ledgerMempoolAdapter adapts mempool.Mempool to ledger.MempoolProvider.