-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1682 lines (1493 loc) · 52.6 KB
/
main.go
File metadata and controls
1682 lines (1493 loc) · 52.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
package main
import (
"bytes"
"context"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/blinklabs-io/adder/event"
filter_event "github.com/blinklabs-io/adder/filter/event"
"github.com/blinklabs-io/adder/input/chainsync"
output_embedded "github.com/blinklabs-io/adder/output/embedded"
"github.com/blinklabs-io/adder/pipeline"
"github.com/blinklabs-io/gouroboros/ledger"
"github.com/blinklabs-io/gouroboros/ledger/allegra"
"github.com/blinklabs-io/gouroboros/ledger/alonzo"
"github.com/blinklabs-io/gouroboros/ledger/babbage"
"github.com/blinklabs-io/gouroboros/ledger/conway"
"github.com/blinklabs-io/gouroboros/ledger/mary"
"github.com/blinklabs-io/gouroboros/ledger/shelley"
koios "github.com/cardano-community/koios-go-client/v3"
"github.com/cenkalti/backoff/v4"
"github.com/gorilla/websocket"
"github.com/michimani/gotwi"
"github.com/michimani/gotwi/media/upload"
upload_types "github.com/michimani/gotwi/media/upload/types"
"github.com/michimani/gotwi/tweet/managetweet"
"github.com/michimani/gotwi/tweet/managetweet/types"
"github.com/spf13/viper"
telebot "gopkg.in/tucnak/telebot.v2"
)
// Build-time version metadata (set via -ldflags)
var (
version = "dev"
commitSHA = "unknown"
buildDate = "unknown"
)
const (
fullBlockSize = 87.97
EpochDurationInDays = 5
SecondsInDay = 24 * 60 * 60
ShelleyEpochStart = "2020-07-29T21:44:51Z"
StartingEpoch = 208
maxRetryDuration = time.Minute
)
// Channel to broadcast block events to connected clients
var clients = make(map[*websocket.Conn]bool) // connected clients
var clientsMutex sync.RWMutex // protects clients map
var broadcast = make(chan interface{}, 100) // broadcast channel (buffered to prevent deadlock)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
// Singleton instance of the Indexer
var globalIndexer = &Indexer{}
// Block interval tracking for adder live tail
var prevBlockTimestamp time.Time
var timeDiffString string
// Tracks goroutines leaked when pipeline.Stop() times out
var abandonedPipelines int64 // atomic
// Indexer struct to manage the adder pipeline and block events
type Indexer struct {
pipeline *pipeline.Pipeline
bot *telebot.Bot
poolId string
telegramChannel string
telegramToken string
image string
ticker string
koios *koios.Client
bech32PoolId string
epochBlocks int
nodeAddresses []string
totalBlocks uint64
poolName string
epoch int
networkMagic int
wg sync.WaitGroup
// Mode: "lite" (adder tail + Koios) or "full" (historical sync + adder tail)
mode string
// Duck media settings
duckMedia string // "gif", "image", or "both" (default)
duckCustomUrl string // custom override URL
// Social network toggles
telegramEnabled bool
twitterEnabled bool
twitterClient *gotwi.Client
// Bot command access control
allowedUsers map[int64]bool
allowedGroups map[int64]bool
nodeQuery *NodeQueryClient
// Leaderlog fields
vrfKey *VRFKey
leaderlogEnabled bool
leaderlogTZ string
leaderlogTimeFormat string
store Store
nonceTracker *NonceTracker
leaderlogMu sync.Mutex
leaderlogCalcing map[int]bool // epochs currently being calculated
leaderlogFailed map[int]time.Time // cooldown: epoch -> last failure time
scheduleExists map[int]bool // cached: epoch -> schedule already in DB
syncer *ChainSyncer // nil in lite mode
lastBlockTime int64 // atomic: unix timestamp of last block received
historicalSyncDone int32 // atomic: 0 = syncing, 1 = done (lite mode starts at 1)
leaderlogArmedAt time.Time // don't auto-trigger leaderlog before this time
}
// isSynced returns true when historical sync is complete (or in lite mode).
func (i *Indexer) isSynced() bool {
return atomic.LoadInt32(&i.historicalSyncDone) == 1
}
type BlockEvent struct {
Type string `json:"type"`
Timestamp string `json:"timestamp"`
Context event.BlockContext `json:"context"`
Payload event.BlockEvent `json:"payload"`
}
// calcCurrentEpoch calculates the current epoch for a network using wall clock time.
func calcCurrentEpoch(networkMagic int) int {
now := time.Now().UTC()
switch networkMagic {
case PreprodNetworkMagic:
genesis, _ := time.Parse(time.RFC3339, "2022-06-01T00:00:00Z")
elapsed := now.Sub(genesis).Seconds()
byronDuration := float64(PreprodShelleyStartEpoch) * float64(ByronEpochLength) * 20 // 20s Byron slots
if elapsed < byronDuration {
return int(elapsed / (float64(ByronEpochLength) * 20))
}
shelleySeconds := elapsed - byronDuration
return PreprodShelleyStartEpoch + int(shelleySeconds/float64(MainnetEpochLength))
case PreviewNetworkMagic:
genesis, _ := time.Parse(time.RFC3339, "2022-11-01T00:00:00Z")
elapsed := now.Sub(genesis).Seconds()
return int(elapsed / float64(PreviewEpochLength))
default: // mainnet
shelleyStartTime, _ := time.Parse(time.RFC3339, ShelleyEpochStart)
elapsedSeconds := now.Sub(shelleyStartTime).Seconds()
epochsElapsed := int(elapsedSeconds / (EpochDurationInDays * SecondsInDay))
return StartingEpoch + epochsElapsed
}
}
func (i *Indexer) getCurrentEpoch() int {
return calcCurrentEpoch(i.networkMagic)
}
// initStore creates the appropriate Store based on config.
func initStore() (Store, error) {
driver := viper.GetString("database.driver")
if driver == "" {
driver = "sqlite"
}
switch driver {
case "sqlite":
path := viper.GetString("database.path")
if path == "" {
path = "./goduckbot.db"
}
return NewSqliteStore(path)
case "postgres":
dbHost := viper.GetString("database.host")
dbPort := viper.GetInt("database.port")
dbName := viper.GetString("database.name")
dbUser := viper.GetString("database.user")
dbPassword := envOrConfig("GODUCKBOT_DB_PASSWORD", "database.password")
connURL := &url.URL{
Scheme: "postgres",
User: url.UserPassword(dbUser, dbPassword),
Host: fmt.Sprintf("%s:%d", dbHost, dbPort),
Path: dbName,
RawQuery: "sslmode=disable",
}
return NewPgStore(connURL.String())
default:
return nil, fmt.Errorf("unsupported database driver: %s (use 'sqlite' or 'postgres')", driver)
}
}
// Start initializes config, connections, and begins chain sync.
func (i *Indexer) Start() error {
// Increment the WaitGroup counter
i.wg.Add(1)
defer func() {
// Decrement the WaitGroup counter when the function exits
i.wg.Done()
if r := recover(); r != nil {
log.Println("Recovered in Start:", r)
}
}()
viper.SetConfigName("config") // name of config file (without extension)
viper.AddConfigPath(".") // look for config in the working directory
e := viper.ReadInConfig() // Find and read the config file
if e != nil { // Handle errors reading the config file
log.Fatalf("Error while reading config file %s", e)
}
// Set the configuration values
i.poolId = viper.GetString("poolId")
i.ticker = viper.GetString("ticker")
i.poolName = viper.GetString("poolName")
i.telegramChannel = viper.GetString("telegram.channel")
i.telegramToken = os.Getenv("TELEGRAM_TOKEN")
if i.telegramToken == "" {
i.telegramToken = viper.GetString("telegram.token")
}
i.image = viper.GetString("image")
i.networkMagic = viper.GetInt("networkMagic")
i.duckMedia = viper.GetString("duck.media")
if i.duckMedia == "" {
i.duckMedia = "both"
}
i.duckCustomUrl = viper.GetString("duck.customUrl")
// Store the node addresses hosts into the array nodeAddresses in the Indexer
i.nodeAddresses = viper.GetStringSlice("nodeAddress.host1")
i.nodeAddresses = append(i.nodeAddresses, viper.GetStringSlice("nodeAddress.host2")...)
// Mode: "lite" (default) or "full"
i.mode = viper.GetString("mode")
if i.mode == "" {
i.mode = "lite"
}
log.Printf("Running in %s mode", i.mode)
// Lite mode is always "synced" — no historical sync needed
if i.mode != "full" {
atomic.StoreInt32(&i.historicalSyncDone, 1)
}
// Social network toggles
i.telegramEnabled = viper.GetBool("telegram.enabled")
// Default to true if not explicitly set (backward compatibility)
if !viper.IsSet("telegram.enabled") {
i.telegramEnabled = true
}
// Initialize Telegram bot if enabled
if i.telegramEnabled {
var err error
i.bot, err = telebot.NewBot(telebot.Settings{
Token: i.telegramToken,
Poller: &telebot.LongPoller{Timeout: 10 * time.Second},
})
if err != nil {
log.Fatalf("failed to start bot: %s", err)
}
log.Println("Telegram bot initialized")
// Load allowed user IDs for bot commands (admin: all commands)
i.allowedUsers = make(map[int64]bool)
for _, id := range viper.GetIntSlice("telegram.allowedUsers") {
i.allowedUsers[int64(id)] = true
}
if len(i.allowedUsers) > 0 {
log.Printf("Bot commands enabled for %d admin user(s)", len(i.allowedUsers))
}
// Load allowed group IDs (group members: safe commands only)
i.allowedGroups = make(map[int64]bool)
for _, id := range viper.GetIntSlice("telegram.allowedGroups") {
i.allowedGroups[int64(id)] = true
}
if len(i.allowedGroups) > 0 {
log.Printf("Group commands enabled for %d group(s)", len(i.allowedGroups))
}
} else {
log.Println("Telegram notifications disabled")
}
// Initialize node query client (NtC local state query via gouroboros).
// Supports both TCP (socat bridge) and UNIX socket (direct) connections.
ntcHost := viper.GetString("nodeAddress.ntcHost")
if ntcHost == "" && len(i.nodeAddresses) > 0 {
ntcHost = i.nodeAddresses[0] // fallback to NtN address
}
if ntcHost != "" {
network, address := parseNodeAddress(ntcHost)
ntcQueryTimeout := viper.GetDuration("leaderlog.ntcQueryTimeout")
i.nodeQuery = NewNodeQueryClient(ntcHost, i.networkMagic, ntcQueryTimeout)
log.Printf("Node query client initialized (NtC): %s://%s (timeout: %v)", network, address, i.nodeQuery.queryTimeout)
}
// Twitter toggle
twitterConfigEnabled := viper.GetBool("twitter.enabled")
if !viper.IsSet("twitter.enabled") {
// Backward compatibility: enable if env vars are present
twitterConfigEnabled = true
}
if twitterConfigEnabled {
twitterAPIKey := envOrConfig("TWITTER_API_KEY", "twitter.apiKey")
twitterAPISecret := envOrConfig("TWITTER_API_KEY_SECRET", "twitter.apiKeySecret")
twitterAccessToken := envOrConfig("TWITTER_ACCESS_TOKEN", "twitter.accessToken")
twitterAccessTokenSecret := envOrConfig("TWITTER_ACCESS_TOKEN_SECRET", "twitter.accessTokenSecret")
if twitterAPIKey != "" && twitterAPISecret != "" &&
twitterAccessToken != "" && twitterAccessTokenSecret != "" {
var err error
in := &gotwi.NewClientInput{
AuthenticationMethod: gotwi.AuthenMethodOAuth1UserContext,
OAuthToken: twitterAccessToken,
OAuthTokenSecret: twitterAccessTokenSecret,
APIKey: twitterAPIKey,
APIKeySecret: twitterAPISecret,
}
i.twitterClient, err = gotwi.NewClient(in)
if err != nil {
log.Printf("failed to initialize Twitter client: %s", err)
} else {
i.twitterEnabled = true
log.Println("Twitter client initialized successfully")
}
} else {
log.Println("Twitter credentials not provided, Twitter notifications disabled")
}
} else {
log.Println("Twitter notifications disabled via config")
}
/// Initialize the koios client based on networkMagic number
if i.networkMagic == PreprodNetworkMagic {
i.koios, e = koios.New(
koios.Host(koios.PreProdHost),
koios.APIVersion("v1"),
)
if e != nil {
log.Fatal(e)
}
} else if i.networkMagic == PreviewNetworkMagic {
i.koios, e = koios.New(
koios.Host(koios.PreviewHost),
koios.APIVersion("v1"),
)
if e != nil {
log.Fatal(e)
}
} else {
i.koios, e = koios.New(
koios.Host(koios.MainnetHost),
koios.APIVersion("v1"),
)
if e != nil {
log.Fatal(e)
}
}
i.epoch = i.getCurrentEpoch()
log.Printf("Epoch: %d", i.epoch)
// Initialize leaderlog
i.leaderlogEnabled = viper.GetBool("leaderlog.enabled")
i.leaderlogTZ = viper.GetString("leaderlog.timezone")
if i.leaderlogTZ == "" {
i.leaderlogTZ = "UTC"
}
i.leaderlogTimeFormat = viper.GetString("leaderlog.timeFormat")
if i.leaderlogTimeFormat != "24h" {
i.leaderlogTimeFormat = "12h"
}
// Load VRF key: prefer vrfKeyValue (inline CBOR hex), fall back to vrfKeyPath (file)
vrfKeyValue := viper.GetString("leaderlog.vrfKeyValue")
if vrfKeyValue != "" {
vrfKey, vrfErr := ParseVRFKeyCborHex(vrfKeyValue)
if vrfErr != nil {
log.Fatalf("failed to parse leaderlog.vrfKeyValue: %s", vrfErr)
}
i.vrfKey = vrfKey
i.leaderlogEnabled = true
log.Println("Leaderlog enabled, VRF key loaded from vrfKeyValue")
} else if i.leaderlogEnabled {
vrfKeyPath := viper.GetString("leaderlog.vrfKeyPath")
vrfKey, vrfErr := ParseVRFKeyFile(vrfKeyPath)
if vrfErr != nil {
log.Fatalf("failed to parse VRF key from %s: %s", vrfKeyPath, vrfErr)
}
i.vrfKey = vrfKey
log.Printf("Leaderlog enabled, VRF key loaded from %s", vrfKeyPath)
}
if i.leaderlogEnabled {
// Initialize Store (SQLite or PostgreSQL)
store, dbErr := initStore()
if dbErr != nil {
log.Fatalf("failed to initialize database: %s", dbErr)
}
i.store = store
// Initialize nonce tracker
fullMode := i.mode == "full"
i.nonceTracker = NewNonceTracker(i.store, i.koios, i.epoch, i.networkMagic, fullMode)
i.leaderlogCalcing = make(map[int]bool)
i.leaderlogFailed = make(map[int]time.Time)
i.scheduleExists = make(map[int]bool)
i.leaderlogArmedAt = time.Now().Add(5 * time.Minute) // don't auto-post on startup
log.Println("Nonce tracker initialized")
// Nonce backfill runs after historical sync (see runChainTail)
}
// Convert the poolId to Bech32
bech32PoolId, err := convertToBech32(i.poolId)
if err != nil {
log.Printf("failed to convert pool id to Bech32: %s", err)
}
// Set the bech32PoolId field in the Indexer
i.bech32PoolId = bech32PoolId
// Get lifetime blocks
lifetimeBlocks, err := i.koios.GetPoolInfo(context.Background(), koios.PoolID(i.bech32PoolId), nil)
if err != nil {
log.Fatalf("failed to get pool lifetime blocks: %s", err)
}
// Get epoch blocks
epoch := koios.EpochNo(i.epoch)
epochBlocks, err := i.koios.GetPoolBlocks(context.Background(), koios.PoolID(i.bech32PoolId), &epoch, nil)
if epochBlocks.Data != nil {
i.epochBlocks = len(epochBlocks.Data)
} else {
log.Fatalf("failed to get pool epoch blocks: %s", err)
}
if lifetimeBlocks.Data != nil {
i.totalBlocks = lifetimeBlocks.Data.BlockCount
} else {
log.Fatalf("failed to get pool lifetime blocks: %s", err)
}
log.Println("quack(duckBot initialized)")
log.Printf("duckBot started: %s | Epoch: %d | Epoch Blocks: %d | Lifetime Blocks: %d | Mode: %s",
i.poolName, i.epoch, i.epochBlocks, i.totalBlocks, i.mode)
// Register bot commands and start polling
if i.telegramEnabled && i.bot != nil && len(i.allowedUsers) > 0 {
i.registerCommands()
go i.bot.Start()
}
// Run unified chain sync (historical + live tail) with auto-reconnect
return i.runChainTail()
}
// flushBlockBatch bulk-inserts blocks via CopyFrom and evolves nonce in-memory.
// Small batches (live tail) use individual ProcessBlock to avoid CopyFrom failures on rollbacks.
// Large batches (historical sync) use CopyFrom for throughput, with fallback on duplicate keys.
func (i *Indexer) flushBlockBatch(batch []BlockData) {
// Small batches (live tail after rollback) — use individual inserts with dedup
if len(batch) < 100 {
for _, b := range batch {
i.nonceTracker.ProcessBlock(b.Slot, b.Epoch, b.BlockHash, b.VrfOutput)
}
return
}
// Large batches (historical sync) — bulk insert via CopyFrom
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
err := i.store.InsertBlockBatch(ctx, batch)
cancel()
if err != nil {
// CopyFrom fails on duplicate keys — fall back to individual inserts
log.Printf("Batch insert failed (resume duplicates), falling back: %v", err)
for _, b := range batch {
i.nonceTracker.ProcessBlock(b.Slot, b.Epoch, b.BlockHash, b.VrfOutput)
}
return
}
// Blocks inserted via CopyFrom, evolve nonce in-memory with single DB persist
i.nonceTracker.ProcessBatch(batch)
}
// runChainTail runs historical sync (full mode) then starts adder pipeline for live tail.
// Full mode: gouroboros historical sync → caught up → adder pipeline (live tail)
// Lite mode: adder pipeline only (intersect at tip)
func (i *Indexer) runChainTail() error {
fullMode := i.mode == "full" && i.leaderlogEnabled
if i.mode == "full" && !i.leaderlogEnabled {
log.Println("WARNING: full mode requires leaderlog.enabled; falling back to lite mode")
}
// DB integrity check (full mode only) — validates that stored blocks exist
// on the canonical chain and that nonce state is consistent with block data.
// Catches data loss from CNPG async replication failover.
if fullMode && len(i.nodeAddresses) > 0 {
valCtx, valCancel := context.WithTimeout(context.Background(), 30*time.Second)
result, valErr := ValidateDBIntegrity(valCtx, i.store, i.nonceTracker, i.nodeAddresses[0], i.networkMagic)
valCancel()
if valErr != nil {
log.Printf("WARNING: DB integrity check failed: %v (proceeding with caution)", valErr)
} else if result.Truncated {
// DB was corrupt and wiped — reinitialize nonce tracker with genesis seed
i.nonceTracker = NewNonceTracker(i.store, i.koios, i.epoch, i.networkMagic, true)
}
}
// Full mode: run historical sync before starting adder pipeline
if fullMode && len(i.nodeAddresses) > 0 {
log.Println("Starting historical chain sync...")
syncCtx, syncCancel := context.WithCancel(context.Background())
defer syncCancel()
// Buffered channel decouples fast chain sync from slower DB writes
blockCh := make(chan BlockData, 10000)
onCaughtUp := func() {
log.Println("Historical sync caught up, stopping ChainSyncer...")
syncCancel() // stop ChainSyncer so Start() returns and adder takes over
}
// DB writer goroutine — drains channel in batches for throughput
writerDone := make(chan struct{})
go func() {
defer close(writerDone)
batch := make([]BlockData, 0, 1000)
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case b, ok := <-blockCh:
if !ok {
// Channel closed — flush remaining
if len(batch) > 0 {
i.flushBlockBatch(batch)
}
return
}
batch = append(batch, b)
if len(batch) >= 1000 {
i.flushBlockBatch(batch)
batch = batch[:0]
}
case <-ticker.C:
if len(batch) > 0 {
i.flushBlockBatch(batch)
batch = batch[:0]
}
}
}
}()
// Retry loop — on keep-alive timeout, reconnect and resume from GetLastSyncedSlot.
// No retry limit: keep going until caught up, with capped backoff.
for attempt := 1; ; attempt++ {
i.syncer = NewChainSyncer(
i.store,
i.networkMagic,
i.nodeAddresses[0],
func(slot uint64, epoch int, blockHash string, vrfOutput []byte) {
blockCh <- BlockData{Slot: slot, Epoch: epoch, BlockHash: blockHash, VrfOutput: vrfOutput, NetworkMagic: i.networkMagic}
},
onCaughtUp,
)
if err := i.syncer.Start(syncCtx); err != nil {
if syncCtx.Err() != nil {
// Context canceled by onCaughtUp — sync is done
break
}
log.Printf("Historical sync error (attempt %d): %s", attempt, err)
// Drain channel buffer — old syncer is dead so no new sends.
// Wait for writer goroutine to flush all buffered blocks to DB.
for len(blockCh) > 0 {
time.Sleep(100 * time.Millisecond)
}
// Give writer time to finish flushing the current in-flight batch
time.Sleep(3 * time.Second)
// Resync NonceTracker from DB so in-memory state matches persisted state.
// Without this, the evolving nonce diverges when buffered blocks from
// the dead connection overlap with blocks from the new connection.
i.nonceTracker.ResyncFromDB()
// Capped backoff: 5s, 10s, 15s, ... max 30s
backoff := time.Duration(attempt) * 5 * time.Second
if backoff > 30*time.Second {
backoff = 30 * time.Second
}
time.Sleep(backoff)
continue
}
break
}
close(blockCh)
<-writerDone // wait for DB writer to flush
atomic.StoreInt32(&i.historicalSyncDone, 1)
log.Println("Historical sync complete, transitioning to live tail...")
// Run nonce backfill after sync so blocks table has data
go func() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Hour)
defer cancel()
if err := i.nonceTracker.BackfillNonces(ctx); err != nil {
log.Printf("Nonce backfill failed: %v", err)
return
}
if viper.GetBool("leaderlog.nonceIntegrityCheck") {
report, err := i.nonceTracker.NonceIntegrityCheck(ctx)
if err != nil {
log.Printf("Nonce integrity check failed: %v", err)
} else if report.KoiosMismatched > 0 {
log.Printf("WARNING: %d epoch nonce mismatches detected!", report.KoiosMismatched)
}
}
if viper.GetBool("leaderlog.backfillSchedules") {
if err := i.backfillSchedules(ctx); err != nil {
log.Printf("Schedule backfill failed: %v", err)
}
}
}()
}
// Start adder pipeline for live chain tail (both full and lite mode)
return i.startAdderPipeline()
}
// startAdderPipeline starts the adder pipeline for live chain tail.
// It runs an infinite restart loop: on pipeline error or stall, it stops, waits, and reconnects.
// Auto-reconnect is disabled because adder orphans the event channel after reconnect.
// A stall detector goroutine monitors lastBlockTime and forces a restart if no blocks
// arrive for 2 minutes (catches zombie state where pipeline.Stop() previously hung).
func (i *Indexer) startAdderPipeline() error {
hosts := i.nodeAddresses
for {
connected := false
for _, host := range hosts {
bo := backoff.NewExponentialBackOff()
bo.MaxElapsedTime = maxRetryDuration
startPipelineFunc := func() error {
node := chainsync.WithAddress(host)
inputOpts := []chainsync.ChainSyncOptionFunc{
node,
chainsync.WithNetworkMagic(uint32(i.networkMagic)),
chainsync.WithIntersectTip(true),
chainsync.WithAutoReconnect(false),
chainsync.WithIncludeCbor(false),
}
i.pipeline = pipeline.New()
input_chainsync := chainsync.New(inputOpts...)
i.pipeline.AddInput(input_chainsync)
filterEvent := filter_event.New(filter_event.WithTypes([]string{"chainsync.block"}))
i.pipeline.AddFilter(filterEvent)
output := output_embedded.New(output_embedded.WithCallbackFunc(i.handleEvent))
i.pipeline.AddOutput(output)
// Reset interval tracking before Start() spawns event goroutines
prevBlockTimestamp = time.Time{}
err := i.pipeline.Start()
if err != nil {
log.Printf("Failed to start pipeline on %s: %s. Retrying...", host, err)
return err
}
return nil
}
err := backoff.Retry(startPipelineFunc, bo)
if err != nil {
log.Printf("Failed to connect to node at %s after retries: %s", host, err)
continue
}
log.Printf("Pipeline connected to node at %s", host)
connected = true
atomic.StoreInt64(&i.lastBlockTime, time.Now().Unix())
// Start stall detector — forces restart if no blocks for 2 minutes.
// This catches the zombie state where pipeline.Stop() hangs or the
// pipeline silently stops delivering blocks after a reconnect.
stallCh := make(chan struct{})
stallDone := make(chan struct{})
go func() {
defer close(stallDone)
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
lastSeen := atomic.LoadInt64(&i.lastBlockTime)
if lastSeen > 0 {
stale := time.Since(time.Unix(lastSeen, 0))
if stale > 2*time.Minute {
log.Printf("Pipeline stall detected (no blocks for %s), forcing restart",
stale.Round(time.Second))
close(stallCh)
return
}
}
case <-stallCh:
return
}
}
}()
// Block until pipeline error OR stall detected
select {
case pipelineErr := <-i.pipeline.ErrorChan():
log.Printf("Pipeline error: %s", pipelineErr)
case <-stallCh:
// Stall detector already logged
}
// Signal stall detector to stop (no-op if it already closed stallCh)
select {
case <-stallCh:
// Already closed
default:
close(stallCh)
}
<-stallDone
// Stop the dead pipeline with timeout to prevent hanging forever.
// pipeline.Stop() can block indefinitely if the underlying connection
// is in a broken state (the root cause of the zombie bug).
stopDone := make(chan struct{})
go func() {
if stopErr := i.pipeline.Stop(); stopErr != nil {
log.Printf("Pipeline stop error: %s", stopErr)
}
close(stopDone)
}()
select {
case <-stopDone:
// Clean shutdown
case <-time.After(5 * time.Second):
n := atomic.AddInt64(&abandonedPipelines, 1)
log.Printf("Pipeline stop timed out, abandoning old pipeline (leaked: %d)", n)
}
break // break inner host loop, restart from outer loop
}
if !connected {
log.Println("Failed to connect to any host, retrying all in 30s...")
time.Sleep(30 * time.Second)
} else {
log.Println("Pipeline died, restarting in 5s...")
time.Sleep(5 * time.Second)
}
}
}
// handleEvent processes a block event from the adder pipeline (live tail).
func (i *Indexer) handleEvent(evt event.Event) error {
// Update liveness tracker for stall detection
atomic.StoreInt64(&i.lastBlockTime, time.Now().Unix())
// Extract VRF output before JSON marshal (Block field is json:"-")
var vrfOutput []byte
if i.leaderlogEnabled {
if be, ok := evt.Payload.(event.BlockEvent); ok && be.Block != nil {
vrfOutput = extractVrfOutput(be.Block.Header())
}
}
// Marshal the event to JSON
data, err := json.Marshal(evt)
if err != nil {
log.Printf("error marshalling event, skipping: %v", err)
return nil
}
// Unmarshal the event to get the block event details
var blockEvent BlockEvent
err = json.Unmarshal(data, &blockEvent)
if err != nil {
log.Printf("error unmarshalling block event, skipping: %v", err)
return nil
}
// Convert the block event timestamp to time.Time
blockEventTime, err := time.Parse(time.RFC3339, blockEvent.Timestamp)
if err != nil {
log.Printf("error parsing block event timestamp, skipping: %v", err)
return nil
}
// Calculate the time difference between the current block event and the previous one
if prevBlockTimestamp.IsZero() {
timeDiffString = "first"
} else {
timeDiff := blockEventTime.Sub(prevBlockTimestamp)
if timeDiff.Seconds() < 60 {
timeDiffString = fmt.Sprintf("%.0fs", timeDiff.Seconds())
} else {
minutes := int(timeDiff.Minutes())
seconds := int(timeDiff.Seconds()) - (minutes * 60)
timeDiffString = fmt.Sprintf("%dm%02ds", minutes, seconds)
}
}
// Update the previous block event timestamp with the current one
prevBlockTimestamp = blockEventTime
// Log clean block line: slot, hash, nonce (VRF output)
vrfHex := ""
if vrfOutput != nil {
vrfHex = hex.EncodeToString(vrfOutput)
}
log.Printf("[block] slot %d | hash %s | nonce %s | interval %s",
blockEvent.Context.SlotNumber,
blockEvent.Payload.BlockHash,
vrfHex, timeDiffString)
// Customize links based on the network magic number
var cexplorerLink string
switch i.networkMagic {
case PreprodNetworkMagic:
cexplorerLink = "https://preprod.cexplorer.io/block/"
case PreviewNetworkMagic:
cexplorerLink = "https://preview.cexplorer.io/block/"
default:
cexplorerLink = "https://cexplorer.io/block/"
}
// Derive epoch from block slot (not wall clock) for correct nonce tracking.
// Wall clock can disagree at epoch boundaries if a late block arrives after
// the boundary time, which would misattribute the block's epoch and corrupt
// nonce evolution and TICKN η_ph (last block hash per epoch).
blockEpoch := SlotToEpoch(blockEvent.Context.SlotNumber, i.networkMagic)
if blockEpoch != i.epoch {
i.epoch = blockEpoch
i.epochBlocks = 0
}
// Track VRF data for nonce evolution
if i.leaderlogEnabled && vrfOutput != nil {
i.nonceTracker.ProcessBlock(
blockEvent.Context.SlotNumber,
blockEpoch,
blockEvent.Payload.BlockHash,
vrfOutput,
)
i.checkLeaderlogTrigger(blockEvent.Context.SlotNumber)
}
// If the block event is from the pool, process it
if blockEvent.Payload.IssuerVkey == i.poolId {
i.epochBlocks++
i.totalBlocks++
blockSizeKB := float64(blockEvent.Payload.BlockBodySize) / 1024
sizePercentage := (blockSizeKB / fullBlockSize) * 100
log.Printf("[MINTED] slot %d | hash %s | txs %d | %.1fKB (%.0f%%) | epoch %d | lifetime %d",
blockEvent.Context.SlotNumber,
truncHash(blockEvent.Payload.BlockHash, 16),
blockEvent.Payload.TransactionCount,
blockSizeKB, sizePercentage,
i.epochBlocks, i.totalBlocks)
msg := fmt.Sprintf(
"Quack!(attention) \U0001F986\nduckBot notification!\n\n"+
"%s\n"+"\U0001F4A5 New Block!\n\n"+
"Tx Count: %d\n"+
"Block Size: %.2f KB\n"+
"%.2f%% Full\n"+
"Interval: %s\n\n"+
"Epoch Blocks: %d\n"+
"Lifetime Blocks: %d\n\n"+
"Pooltool: https://pooltool.io/realtime/%d\n\n"+
"Cexplorer: "+cexplorerLink+"%s",
i.poolName, blockEvent.Payload.TransactionCount, blockSizeKB, sizePercentage,
timeDiffString, i.epochBlocks, i.totalBlocks,
blockEvent.Context.BlockNumber, blockEvent.Payload.BlockHash)
// Get duck media for notifications
mediaURL, isGif, mediaErr := i.getDuckMedia()
if mediaErr != nil {
log.Printf("failed to fetch duck media: %v", mediaErr)
}
// Send Telegram notification if enabled
if i.telegramEnabled && i.bot != nil {
channelID, err := strconv.ParseInt(i.telegramChannel, 10, 64)
if err != nil {
log.Printf("failed to parse telegram channel ID: %s", err)
} else {
chat := &telebot.Chat{ID: channelID}
sent := false
if mediaURL != "" {
if isGif {
animation := &telebot.Animation{File: telebot.FromURL(mediaURL), Caption: msg}
if _, err = i.bot.Send(chat, animation); err != nil {
log.Printf("failed to send Telegram GIF: %s", err)
} else {
sent = true
}
} else {
photo := &telebot.Photo{File: telebot.FromURL(mediaURL), Caption: msg}
if _, err = i.bot.Send(chat, photo); err != nil {
log.Printf("failed to send Telegram photo: %s", err)
} else {
sent = true
}
}
}
if !sent {
i.bot.Send(chat, msg)
}
}
}
// Send tweet if Twitter is enabled (same format as Telegram minus links)
if i.twitterEnabled {
tweetMsg := fmt.Sprintf(
"Quack!(attention) \U0001F986\nduckBot notification!\n\n"+
"%s\n"+"\U0001F4A5 New Block!\n\n"+
"Tx Count: %d\n"+
"Block Size: %.2f KB\n"+
"%.2f%% Full\n"+
"Interval: %s\n\n"+
"Epoch Blocks: %d\n"+
"Lifetime Blocks: %d",
i.poolName, blockEvent.Payload.TransactionCount, blockSizeKB, sizePercentage,
timeDiffString, i.epochBlocks, i.totalBlocks)
if err := i.sendTweet(tweetMsg, mediaURL, isGif); err != nil {
log.Printf("failed to send tweet: %s", err)
}
}
}
// Send the block event to the WebSocket clients (non-blocking)
select {
case broadcast <- blockEvent:
default:
}
return nil
}
// extractVrfOutput extracts VRF output from a ledger.BlockHeader (adder live tail).
func extractVrfOutput(header ledger.BlockHeader) []byte {
switch h := header.(type) {
case *conway.ConwayBlockHeader:
return h.Body.VrfResult.Output
case *babbage.BabbageBlockHeader:
return h.Body.VrfResult.Output
case *alonzo.AlonzoBlockHeader:
return h.Body.NonceVrf.Output
case *mary.MaryBlockHeader:
return h.Body.NonceVrf.Output
case *allegra.AllegraBlockHeader:
return h.Body.NonceVrf.Output
case *shelley.ShelleyBlockHeader:
return h.Body.NonceVrf.Output
default:
log.Printf("Could not extract VRF from header type %T", header)
return nil
}
}
func handleConnections(w http.ResponseWriter, r *http.Request) {
// Upgrade initial GET request to a websocket
ws, err := upgrader.Upgrade(w, r, nil)