-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.go
More file actions
572 lines (501 loc) · 15.3 KB
/
cli.go
File metadata and controls
572 lines (501 loc) · 15.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
package main
import (
"context"
"encoding/hex"
"fmt"
"log"
"os"
"strconv"
"strings"
"time"
koios "github.com/cardano-community/koios-go-client/v3"
"github.com/spf13/viper"
)
// cliContext holds the shared state needed by CLI subcommands.
type cliContext struct {
networkMagic int
poolId string
bech32PoolId string
poolName string
vrfKey *VRFKey
store Store
koios *koios.Client
nonceTracker *NonceTracker
leaderlogTZ string
timeFormat string
slotToTime func(uint64) time.Time
}
// runCLI dispatches CLI subcommands. Returns an exit code.
func runCLI(args []string) int {
switch args[0] {
case "version":
return cmdVersion()
case "leaderlog":
return cmdCLILeaderlog(args[1:])
case "nonce":
return cmdCLINonce(args[1:])
case "history":
return cmdCLIHistory(args[1:])
case "help", "--help", "-h":
printCLIHelp()
return 0
default:
fmt.Fprintf(os.Stderr, "Unknown command %q\n\nRun 'goduckbot help' for usage.\n", args[0])
return 1
}
}
func printCLIHelp() {
fmt.Printf(`goduckbot - Cardano stake pool companion
Usage:
goduckbot Start the daemon (default)
goduckbot version Show version information
goduckbot leaderlog <epoch> Calculate leaderlog for a single epoch
goduckbot leaderlog <N>-<M> Calculate leaderlog for epoch range (max 10)
goduckbot nonce <epoch> Show epoch nonce
goduckbot history Build complete leaderlog history with slot classification
goduckbot history --force Re-classify already-processed epochs
goduckbot history --from N Start from epoch N (overrides auto-detect)
goduckbot help Show this help
Config is loaded from config.yaml in the current directory.
`)
}
func cmdVersion() int {
sha := commitSHA
if len(sha) > 8 {
sha = sha[:8]
}
fmt.Printf("goduckbot %s (%s) built %s\n", version, sha, buildDate)
return 0
}
// cliInit sets up the minimal state needed by CLI subcommands.
func cliInit() (*cliContext, func(), error) {
viper.SetConfigName("config")
viper.AddConfigPath(".")
if err := viper.ReadInConfig(); err != nil {
return nil, nil, fmt.Errorf("config: %w", err)
}
cc := &cliContext{
networkMagic: viper.GetInt("networkMagic"),
poolId: viper.GetString("poolId"),
poolName: viper.GetString("poolName"),
leaderlogTZ: viper.GetString("leaderlog.timezone"),
timeFormat: viper.GetString("leaderlog.timeFormat"),
}
if cc.leaderlogTZ == "" {
cc.leaderlogTZ = "UTC"
}
if cc.timeFormat != "24h" {
cc.timeFormat = "12h"
}
// VRF key
if v := viper.GetString("leaderlog.vrfKeyValue"); v != "" {
key, err := ParseVRFKeyCborHex(v)
if err != nil {
return nil, nil, fmt.Errorf("vrfKeyValue: %w", err)
}
cc.vrfKey = key
} else if p := viper.GetString("leaderlog.vrfKeyPath"); p != "" {
key, err := ParseVRFKeyFile(p)
if err != nil {
return nil, nil, fmt.Errorf("vrfKeyPath %s: %w", p, err)
}
cc.vrfKey = key
}
// Store
store, err := initStore()
if err != nil {
if cc.vrfKey != nil {
cc.vrfKey.Close()
}
return nil, nil, fmt.Errorf("database: %w", err)
}
cc.store = store
// Koios client; host defaults to public koios.rest, overridable via koios.url config
cc.koios, err = koios.New(koios.Host(koiosClientHost(cc.networkMagic)), koios.APIVersion("v1"))
if err != nil {
store.Close()
if cc.vrfKey != nil {
cc.vrfKey.Close()
}
return nil, nil, fmt.Errorf("koios: %w", err)
}
// Bech32 pool ID
bech32, err := convertToBech32(cc.poolId)
if err != nil {
store.Close()
if cc.vrfKey != nil {
cc.vrfKey.Close()
}
return nil, nil, fmt.Errorf("pool ID to bech32: %w", err)
}
cc.bech32PoolId = bech32
// Nonce tracker (lite mode — uses DB cache + Koios fallback)
currentEpoch := calcCurrentEpoch(cc.networkMagic)
cc.nonceTracker = NewNonceTracker(store, cc.koios, currentEpoch, cc.networkMagic, false)
cc.slotToTime = makeSlotToTime(cc.networkMagic)
cleanup := func() {
store.Close()
if cc.vrfKey != nil {
cc.vrfKey.Close()
}
}
return cc, cleanup, nil
}
// parseEpochArg parses "612" into [612] or "500-510" into [500..510].
func parseEpochArg(arg string) ([]int, error) {
if idx := strings.Index(arg, "-"); idx > 0 {
start, err1 := strconv.Atoi(arg[:idx])
end, err2 := strconv.Atoi(arg[idx+1:])
if err1 != nil || err2 != nil {
return nil, fmt.Errorf("invalid epoch range %q", arg)
}
if start > end {
return nil, fmt.Errorf("start epoch must be <= end epoch")
}
if end-start+1 > 10 {
return nil, fmt.Errorf("max 10 epochs at once (got %d)", end-start+1)
}
epochs := make([]int, 0, end-start+1)
for e := start; e <= end; e++ {
epochs = append(epochs, e)
}
return epochs, nil
}
n, err := strconv.Atoi(arg)
if err != nil {
return nil, fmt.Errorf("invalid epoch %q", arg)
}
if n < 0 {
return nil, fmt.Errorf("epoch must be non-negative, got %d", n)
}
return []int{n}, nil
}
func cmdCLILeaderlog(args []string) int {
if len(args) == 0 {
fmt.Fprintln(os.Stderr, "Usage: goduckbot leaderlog <epoch>|<start>-<end>")
return 1
}
epochs, err := parseEpochArg(args[0])
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
return 1
}
cc, cleanup, err := cliInit()
if err != nil {
fmt.Fprintf(os.Stderr, "Init failed: %v\n", err)
return 1
}
defer cleanup()
if cc.vrfKey == nil {
fmt.Fprintln(os.Stderr, "No VRF key configured (set leaderlog.vrfKeyValue or leaderlog.vrfKeyPath)")
return 1
}
exitCode := 0
for _, epoch := range epochs {
if err := runLeaderlogForEpoch(cc, epoch); err != nil {
fmt.Fprintf(os.Stderr, "Epoch %d: %v\n", epoch, err)
exitCode = 1
}
}
return exitCode
}
func runLeaderlogForEpoch(cc *cliContext, epoch int) error {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
defer cancel()
// Check DB cache first
stored, err := cc.store.GetLeaderSchedule(ctx, epoch)
if err == nil && stored != nil {
fmt.Println(formatScheduleForCLI(stored, cc.poolName, cc.leaderlogTZ, cc.timeFormat))
return nil
}
log.Printf("Fetching nonce for epoch %d...", epoch)
epochNonce, err := cc.nonceTracker.GetNonceForEpoch(epoch)
if err != nil {
return fmt.Errorf("nonce: %w", err)
}
// Get stake data from Koios (same fallback pattern as commands.go)
var poolStake, totalStake uint64
curEpoch := calcCurrentEpoch(cc.networkMagic)
for _, tryEpoch := range []int{epoch, curEpoch, curEpoch - 1, curEpoch - 2} {
epochNo := koios.EpochNo(tryEpoch)
poolHist, histErr := cc.koios.GetPoolHistory(ctx, koios.PoolID(cc.bech32PoolId), &epochNo, nil)
if histErr != nil || len(poolHist.Data) == 0 {
continue
}
poolStake = uint64(poolHist.Data[0].ActiveStake.IntPart())
epochInfo, infoErr := cc.koios.GetEpochInfo(ctx, &epochNo, nil)
if infoErr != nil || len(epochInfo.Data) == 0 {
poolStake = 0
continue
}
totalStake = uint64(epochInfo.Data[0].ActiveStake.IntPart())
if tryEpoch != epoch {
log.Printf("Using stake from epoch %d for epoch %d calculation", tryEpoch, epoch)
}
break
}
if poolStake == 0 || totalStake == 0 {
return fmt.Errorf("could not get stake data from Koios")
}
epochLength := GetEpochLength(cc.networkMagic)
epochStartSlot := GetEpochStartSlot(epoch, cc.networkMagic)
log.Printf("Calculating leader schedule for epoch %d...", epoch)
schedule, err := CalculateLeaderSchedule(
epoch, epochNonce, cc.vrfKey,
poolStake, totalStake,
epochLength, epochStartSlot, cc.slotToTime,
)
if err != nil {
return fmt.Errorf("calculation: %w", err)
}
// Store in DB
if storeErr := cc.store.InsertLeaderSchedule(ctx, schedule); storeErr != nil {
log.Printf("Warning: failed to store schedule: %v", storeErr)
}
fmt.Println(formatScheduleForCLI(schedule, cc.poolName, cc.leaderlogTZ, cc.timeFormat))
return nil
}
func cmdCLINonce(args []string) int {
if len(args) == 0 {
fmt.Fprintln(os.Stderr, "Usage: goduckbot nonce <epoch>")
return 1
}
epoch, err := strconv.Atoi(args[0])
if err != nil {
fmt.Fprintf(os.Stderr, "Invalid epoch %q\n", args[0])
return 1
}
cc, cleanup, err := cliInit()
if err != nil {
fmt.Fprintf(os.Stderr, "Init failed: %v\n", err)
return 1
}
defer cleanup()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
// Try DB first
nonce, dbErr := cc.store.GetFinalNonce(ctx, epoch)
source := "db"
if dbErr != nil || nonce == nil {
nonce, err = cc.nonceTracker.GetNonceForEpoch(epoch)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
return 1
}
source = "computed"
}
fmt.Printf("Epoch: %d\nNonce: %s\nSource: %s\n", epoch, hex.EncodeToString(nonce), source)
return 0
}
func cmdCLIHistory(args []string) int {
cc, cleanup, err := cliInit()
if err != nil {
fmt.Fprintf(os.Stderr, "Init failed: %v\n", err)
return 1
}
defer cleanup()
// Parse flags
force := false
fromEpoch := 0
for i := 0; i < len(args); i++ {
switch args[i] {
case "--force":
force = true
case "--from":
if i+1 < len(args) {
i++
n, e := strconv.Atoi(args[i])
if e != nil {
fmt.Fprintf(os.Stderr, "Invalid epoch %q\n", args[i])
return 1
}
fromEpoch = n
}
}
}
ctx := context.Background()
// Determine start epoch — CPraos only (Babbage+)
babbageStart := BabbageStartEpoch
if cc.networkMagic == PreprodNetworkMagic {
babbageStart = PreprodBabbageStartEpoch
}
var startEpoch int
if fromEpoch > 0 {
startEpoch = fromEpoch
} else {
regEpoch, regErr := fetchPoolRegistrationEpoch(ctx, koiosRESTBase(cc.networkMagic), cc.bech32PoolId)
if regErr != nil {
fmt.Fprintf(os.Stderr, "Error fetching pool registration: %v\n", regErr)
return 1
}
startEpoch = max(regEpoch+2, babbageStart)
}
curEpoch := calcCurrentEpoch(cc.networkMagic)
endEpoch := curEpoch - 1
// Count how many epochs need processing
totalEpochs := endEpoch - startEpoch + 1
needWork := totalEpochs
if !force {
for e := startEpoch; e <= endEpoch; e++ {
if cc.store.IsEpochClassified(ctx, e) {
needWork--
}
}
}
if needWork == 0 {
fmt.Printf("All %d epochs (%d-%d) already classified. Use --force to reclassify.\n",
totalEpochs, startEpoch, endEpoch)
return 0
}
// ~5s per epoch (Koios API calls + rate limit sleeps)
estDuration := time.Duration(needWork) * 5 * time.Second
fmt.Printf("History classification: %d epochs to process (%d-%d), %d already done\n",
needWork, startEpoch, endEpoch, totalEpochs-needWork)
fmt.Printf("Estimated time: %v\n\n", estDuration.Round(time.Second))
epochLength := GetEpochLength(cc.networkMagic)
slotToTimeFn := makeSlotToTime(cc.networkMagic)
start := time.Now()
var computed, skipped, failed int
var totalForged, totalBattles, totalMissed int
for epoch := startEpoch; epoch <= endEpoch; epoch++ {
if !force && cc.store.IsEpochClassified(ctx, epoch) {
skipped++
continue
}
// Get or compute schedule
schedule, _ := cc.store.GetLeaderSchedule(ctx, epoch)
if schedule == nil {
nonce, nErr := cc.nonceTracker.GetNonceForEpoch(epoch)
if nErr != nil {
failed++
continue
}
var poolStake, totalStake uint64
epochNo := koios.EpochNo(epoch)
poolHist, histErr := cc.koios.GetPoolHistory(ctx, koios.PoolID(cc.bech32PoolId), &epochNo, nil)
if histErr == nil && len(poolHist.Data) > 0 {
poolStake = uint64(poolHist.Data[0].ActiveStake.IntPart())
}
time.Sleep(time.Second)
if poolStake == 0 {
failed++
continue
}
epochInfo, infoErr := cc.koios.GetEpochInfo(ctx, &epochNo, nil)
if infoErr == nil && len(epochInfo.Data) > 0 {
totalStake = uint64(epochInfo.Data[0].ActiveStake.IntPart())
}
time.Sleep(time.Second)
if totalStake == 0 {
failed++
continue
}
epochStartSlot := GetEpochStartSlot(epoch, cc.networkMagic)
schedule, err = CalculateLeaderSchedule(
epoch, nonce, cc.vrfKey,
poolStake, totalStake,
epochLength, epochStartSlot, slotToTimeFn,
)
if err != nil {
log.Printf("[history] epoch %d: calc failed: %v", epoch, err)
failed++
continue
}
cc.store.InsertLeaderSchedule(ctx, schedule)
}
if len(schedule.AssignedSlots) == 0 {
cc.store.MarkEpochClassified(ctx, epoch)
computed++
continue
}
// Get OUR pool's forged slots from Koios
forgedSet, fErr := fetchPoolForgedSlots(ctx, koiosRESTBase(cc.networkMagic), cc.bech32PoolId, epoch)
if fErr != nil {
log.Printf("[history] epoch %d: pool forged slots failed: %v", epoch, fErr)
forgedSet = make(map[uint64]bool)
}
time.Sleep(time.Second)
// Classify slots
outcomes := make([]SlotOutcome, 0, len(schedule.AssignedSlots))
epochForged, epochBattles, epochMissed := 0, 0, 0
for _, slot := range schedule.AssignedSlots {
if forgedSet[slot.Slot] {
outcomes = append(outcomes, SlotOutcome{
Epoch: epoch, Slot: slot.Slot, Outcome: "forged",
})
epochForged++
continue
}
hasBlock, _ := cc.store.HasBlockAtSlot(ctx, slot.Slot)
if hasBlock {
outcomes = append(outcomes, SlotOutcome{
Epoch: epoch, Slot: slot.Slot, Outcome: "battle",
})
epochBattles++
} else {
outcomes = append(outcomes, SlotOutcome{
Epoch: epoch, Slot: slot.Slot, Outcome: "missed",
})
epochMissed++
}
}
if storeErr := cc.store.UpsertSlotOutcomes(ctx, epoch, outcomes); storeErr != nil {
log.Printf("[history] epoch %d: store failed: %v", epoch, storeErr)
failed++
continue
}
cc.store.MarkEpochClassified(ctx, epoch)
totalForged += epochForged
totalBattles += epochBattles
totalMissed += epochMissed
computed++
if computed%10 == 0 {
log.Printf("[history] progress: %d epochs classified", computed)
}
}
totalAssigned := totalForged + totalBattles + totalMissed
fmt.Printf("\nLeaderlog History Complete (%v)\n", time.Since(start).Round(time.Second))
fmt.Printf("Epochs: %d-%d (%d computed, %d skipped, %d failed)\n",
startEpoch, endEpoch, computed, skipped, failed)
fmt.Printf("Slots: %d assigned, %d forged (%.1f%%), %d battles (%.1f%%), %d missed (%.1f%%)\n",
totalAssigned, totalForged, pct(totalForged, totalAssigned),
totalBattles, pct(totalBattles, totalAssigned),
totalMissed, pct(totalMissed, totalAssigned))
return 0
}
// formatScheduleForCLI formats a leader schedule for terminal output.
func formatScheduleForCLI(schedule *LeaderSchedule, poolName, timezone, timeFormat string) string {
loc, err := time.LoadLocation(timezone)
if err != nil {
loc = time.UTC
}
timeFmt := "01/02/2006 03:04:05 PM"
fmtLabel := "12-hour"
if timeFormat == "24h" {
timeFmt = "01/02/2006 15:04:05"
fmtLabel = "24-hour"
}
performance := 0.0
if schedule.IdealSlots > 0 {
performance = float64(len(schedule.AssignedSlots)) / schedule.IdealSlots * 100
}
var sb strings.Builder
fmt.Fprintf(&sb, "Epoch: %d\n", schedule.Epoch)
fmt.Fprintf(&sb, "Nonce: %s\n", schedule.EpochNonce)
fmt.Fprintf(&sb, "Pool Active Stake: %s\u20B3\n", formatADA(schedule.PoolStake))
fmt.Fprintf(&sb, "Network Active Stake: %s\u20B3\n", formatADA(schedule.TotalStake))
fmt.Fprintf(&sb, "Ideal Blocks: %.2f\n", schedule.IdealSlots)
if len(schedule.AssignedSlots) > 0 {
fmt.Fprintf(&sb, "\nAssigned Slots (%s, %s):\n", fmtLabel, timezone)
for _, slot := range schedule.AssignedSlots {
localTime := slot.At.In(loc)
fmt.Fprintf(&sb, " %s - Slot: %-6d - B: %d\n",
localTime.Format(timeFmt), slot.SlotInEpoch, slot.No)
}
} else {
sb.WriteString("\nNo slots assigned this epoch.\n")
}
fmt.Fprintf(&sb, "\nTotal Scheduled Blocks: %d\n", len(schedule.AssignedSlots))
fmt.Fprintf(&sb, "Performance: %.2f%%\n", performance)
return sb.String()
}