-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathbfg.go
2124 lines (1789 loc) · 57.2 KB
/
bfg.go
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 (c) 2024-2025 Hemi Labs, Inc.
// Use of this source code is governed by the MIT License,
// which can be found in the LICENSE file.
package bfg
import (
"bytes"
"context"
"crypto/rand"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"net"
"net/http"
"strings"
"sync"
"time"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/coder/websocket"
"github.com/davecgh/go-spew/spew"
"github.com/decred/dcrd/dcrec/secp256k1/v4"
"github.com/juju/loggo"
"github.com/prometheus/client_golang/prometheus"
"github.com/hemilabs/heminetwork/api"
"github.com/hemilabs/heminetwork/api/auth"
"github.com/hemilabs/heminetwork/api/bfgapi"
"github.com/hemilabs/heminetwork/api/protocol"
"github.com/hemilabs/heminetwork/bitcoin"
"github.com/hemilabs/heminetwork/database"
"github.com/hemilabs/heminetwork/database/bfgd"
"github.com/hemilabs/heminetwork/database/bfgd/postgres"
"github.com/hemilabs/heminetwork/hemi"
"github.com/hemilabs/heminetwork/hemi/electrs"
"github.com/hemilabs/heminetwork/hemi/pop"
"github.com/hemilabs/heminetwork/service/deucalion"
"github.com/hemilabs/heminetwork/service/pprof"
"github.com/hemilabs/heminetwork/version"
)
// XXX this code needs to be a bit smarter when syncing bitcoin. We should
// return a "not ready" error when that is the case.
type notificationId string
const (
logLevel = "INFO"
appName = "bfg" // Prometheus
notifyBtcBlocks notificationId = "btc_blocks"
notifyBtcFinalities notificationId = "btc_finalities"
notifyL2Keystones notificationId = "l2_keystones"
)
var (
log = loggo.GetLogger(appName)
ErrBTCPrivateKeyMissing = errors.New("you must specify a BTC private key")
)
func init() {
if err := loggo.ConfigureLoggers(logLevel); err != nil {
panic(err)
}
}
func NewDefaultConfig() *Config {
return &Config{
EXBTCAddress: "localhost:18001",
EXBTCInitialConns: 5,
EXBTCMaxConns: 100,
PrivateListenAddress: ":8080",
PrometheusNamespace: appName,
PublicListenAddress: ":8383",
RequestLimit: bfgapi.DefaultRequestLimit,
RequestTimeout: bfgapi.DefaultRequestTimeout,
BFGURL: "",
}
}
// XXX figure out if this needs to be moved out into the electrs package.
type btcClient interface {
Metrics() []prometheus.Collector
Balance(ctx context.Context, scriptHash []byte) (*electrs.Balance, error)
Broadcast(ctx context.Context, rtx []byte) ([]byte, error)
Height(ctx context.Context) (uint64, error)
RawBlockHeader(ctx context.Context, height uint64) (*bitcoin.BlockHeader, error)
RawTransaction(ctx context.Context, txHash []byte) ([]byte, error)
Transaction(ctx context.Context, txHash []byte) ([]byte, error)
TransactionAtPosition(ctx context.Context, height, index uint64) ([]byte, []string, error)
UTXOs(ctx context.Context, scriptHash []byte) ([]*electrs.UTXO, error)
Close() error
}
// Wrap for calling bfg commands
type bfgCmd struct {
msg any
ch chan any
}
type Config struct {
BTCStartHeight uint64
EXBTCAddress string
EXBTCInitialConns int
EXBTCMaxConns int
PrivateListenAddress string
PublicListenAddress string
LogLevel string
PgURI string
PrometheusListenAddress string
PrometheusNamespace string
PprofListenAddress string
RequestLimit int
RequestTimeout int // in seconds
RemoteIPHeaders []string
TrustedProxies []string
BFGURL string
BTCPrivateKey string
}
type Server struct {
mtx sync.RWMutex
wg sync.WaitGroup
cfg *Config
// requests
requestLimiter chan bool // Maximum in progress websocket commands
// requestTimeout time.Duration
remoteIPHeaders []string
trustedProxies []*net.IPNet
btcHeight uint64
server *http.ServeMux
publicServer *http.ServeMux
btcClient btcClient // XXX evaluate if this is ok
db bfgd.Database
// Prometheus
metrics *metrics
isRunning bool
// sessions is a record of websocket connections and their
// respective request contexts
sessions map[string]*bfgWs
// record the last known canonical chain height,
// if this grows we need to notify subscribers
canonicalChainHeight uint64
l2keystonesCache []hemi.L2Keystone
btcHeightCache uint64
bfgWG sync.WaitGroup // wait group for connecting to other bfgs
holdoffTimeout time.Duration // Time in between connections attempt to BFG
bfgCallTimeout time.Duration
bfgCmdCh chan bfgCmd // commands to send to bfg
btcPrivateKey *secp256k1.PrivateKey
}
// metrics stores prometheus metrics.
type metrics struct {
canonicalHeight prometheus.Gauge // Total number of PoP transaction broadcasts
popBroadcasts prometheus.Counter // Total number of PoP transaction broadcasts
rpcCallsTotal *prometheus.CounterVec // Total number of successful RPC commands
rpcCallsDuration *prometheus.HistogramVec // RPC calls duration in seconds
rpcConnections *prometheus.GaugeVec // Number of active RPC WebSocket connections
}
// newMetrics returns a new metrics struct containing prometheus collectors.
func newMetrics(cfg *Config) *metrics {
// When adding a metric here, remember to add it to metrics.collectors().
return &metrics{
canonicalHeight: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: cfg.PrometheusNamespace,
Name: "canonical_height",
Help: "Last measured canonical height.",
}),
popBroadcasts: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: cfg.PrometheusNamespace,
Name: "pop_broadcasts_total",
Help: "Total number of PoP transaction broadcasts",
}),
rpcCallsTotal: prometheus.NewCounterVec(
prometheus.CounterOpts{
Namespace: cfg.PrometheusNamespace,
Name: "rpc_calls_total",
Help: "Total number of successful RPC commands",
},
[]string{"listener", "command"},
),
rpcCallsDuration: prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Namespace: cfg.PrometheusNamespace,
Name: "rpc_calls_duration_seconds",
Help: "RPC call durations in seconds",
Buckets: prometheus.DefBuckets,
},
[]string{"listener", "command"},
),
rpcConnections: prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Namespace: cfg.PrometheusNamespace,
Name: "rpc_connections",
Help: "Number of active RPC WebSocket connections",
},
[]string{"listener"},
),
}
}
// collectors returns all prometheus collectors.
func (m *metrics) collectors() []prometheus.Collector {
return []prometheus.Collector{
m.canonicalHeight,
m.popBroadcasts,
m.rpcCallsTotal,
m.rpcCallsDuration,
m.rpcConnections,
}
}
func NewServer(cfg *Config) (*Server, error) {
if cfg == nil {
cfg = NewDefaultConfig()
}
if cfg.RequestLimit <= 0 {
return nil, fmt.Errorf("invalid request limit: %v", cfg.RequestLimit)
}
minRequestTimeout := 3
if cfg.RequestTimeout <= minRequestTimeout {
return nil, fmt.Errorf("invalid request timeout (minimum %v): %v",
minRequestTimeout, cfg.RequestTimeout)
}
if cfg.BTCPrivateKey == "" && cfg.BFGURL != "" {
return nil, errors.Join(
ErrBTCPrivateKeyMissing,
errors.New("btc private key required when connecting to another BFG"),
)
}
s := &Server{
cfg: cfg,
requestLimiter: make(chan bool, cfg.RequestLimit),
btcHeight: cfg.BTCStartHeight,
server: http.NewServeMux(),
publicServer: http.NewServeMux(),
metrics: newMetrics(cfg),
sessions: make(map[string]*bfgWs),
holdoffTimeout: 6 * time.Second,
bfgCallTimeout: 20 * time.Second,
bfgCmdCh: make(chan bfgCmd),
}
for range cfg.RequestLimit {
s.requestLimiter <- true
}
var err error
if cfg.BTCPrivateKey != "" {
s.btcPrivateKey, err = bitcoin.PrivKeyFromHexString(cfg.BTCPrivateKey)
if err != nil {
return nil, err
}
}
// XXX this is not right. NewServer should always return. The call to
// electrs.NewClient should be in Run. Or, electrs should be a service
// so that we can mirror the New/Run paradigm, the New/Run paradigm,
s.btcClient, err = electrs.NewClient(cfg.EXBTCAddress, &electrs.ClientOptions{
InitialConnections: cfg.EXBTCInitialConns,
MaxConnections: cfg.EXBTCMaxConns,
PrometheusNamespace: cfg.PrometheusNamespace,
})
if err != nil {
return nil, fmt.Errorf("create electrs client: %w", err)
}
// We could use a PGURI verification here.
return s, nil
}
// handleRequest is called as a go routine to handle a long-lived command.
func (s *Server) handleRequest(pctx context.Context, bws *bfgWs, wsid string, cmd protocol.Command, handler func(ctx context.Context) (any, error)) {
log.Tracef("handleRequest: %v", bws.addr)
defer log.Tracef("handleRequest exit: %v", bws.addr)
ctx, cancel := context.WithTimeout(pctx, time.Duration(s.cfg.RequestTimeout)*time.Second)
defer cancel()
select {
case <-s.requestLimiter:
default:
log.Tracef("Request limiter hit %v: %v", bws.addr, cmd)
select {
case <-s.requestLimiter:
case <-ctx.Done():
log.Debugf("request context done %v: %v", bws.addr, cmd)
return
}
}
defer func() { s.requestLimiter <- true }()
start := time.Now()
defer func() {
s.metrics.rpcCallsDuration.With(prometheus.Labels{
"listener": bws.listenerName,
"command": string(cmd),
}).Observe(time.Since(start).Seconds())
}()
log.Tracef("Handling request %v: %v", bws.addr, cmd)
response, err := handler(ctx)
if err != nil {
log.Errorf("Failed to handle %v request %v: %v", cmd, bws.addr, err)
}
if response == nil {
return
}
log.Debugf("Responding to %v request with %v", cmd, spew.Sdump(response))
if err := bfgapi.Write(ctx, bws.conn, wsid, response); err != nil {
log.Errorf("Failed to handle %v request: protocol write failed: %v",
cmd, err)
}
}
func (s *Server) handleBitcoinBalance(ctx context.Context, bbr *bfgapi.BitcoinBalanceRequest) (any, error) {
log.Tracef("handleBitcoinBalance")
defer log.Tracef("handleBitcoinBalance exit")
balance, err := s.btcClient.Balance(ctx, bbr.ScriptHash)
if err != nil {
e := protocol.NewInternalErrorf("bitcoin balance: %w", err)
return &bfgapi.BitcoinBalanceResponse{
Error: e.ProtocolError(),
}, e
}
return &bfgapi.BitcoinBalanceResponse{
Confirmed: balance.Confirmed,
Unconfirmed: balance.Unconfirmed,
}, nil
}
func (s *Server) handleOneBroadcastRequest(pctx context.Context, highPriority bool) {
ctx, cancel := context.WithTimeout(pctx, 5*time.Second)
defer cancel()
serializedTx, err := s.db.BtcTransactionBroadcastRequestGetNext(ctx, highPriority)
if err != nil {
log.Errorf("error getting next broadcast request: %v", err)
// if there is a communication error, backoff a bit
select {
case <-time.After(1 * time.Second):
return
case <-ctx.Done():
return
}
}
// if there are no new serialized txs, backoff a bit
if serializedTx == nil {
select {
case <-time.After(1 * time.Second):
return
case <-ctx.Done():
return
}
}
rr := bytes.NewReader(serializedTx)
mb := wire.MsgTx{}
if err := mb.Deserialize(rr); err != nil {
log.Errorf("failed to deserialize tx: %v", err)
return
}
var tl2 *pop.TransactionL2
for _, v := range mb.TxOut {
tl2, err = pop.ParseTransactionL2FromOpReturn(v.PkScript)
if err == nil {
break // Found the pop transaction.
}
}
if tl2 == nil {
log.Errorf("could not find pop tx")
return
}
// attempt to insert the abbreviated keystone, this is in case we have
// not heard of this keystone from op node yet
if err := s.db.L2KeystonesInsert(ctx, []bfgd.L2Keystone{
hemiL2KeystoneAbrevToDb(*tl2.L2Keystone),
}); err != nil {
log.Infof("could not insert l2 keystone: %s", err)
}
_, err = pop.ParsePublicKeyFromSignatureScript(mb.TxIn[0].SignatureScript)
if err != nil {
log.Errorf("could not parse public key from signature script: %v", err)
return
}
hash := mb.TxHash()
_, err = s.btcClient.Broadcast(ctx, serializedTx)
if err != nil {
log.Errorf("broadcast tx %s: %s", mb.TxID(), err)
err = s.db.BtcTransactionBroadcastRequestSetLastError(ctx, mb.TxID(), err.Error())
if err != nil {
log.Errorf("could not delete %v", err)
}
return
}
s.metrics.popBroadcasts.Inc()
log.Tracef("hash is %s", hex.EncodeToString(hash[:]))
err = s.db.BtcTransactionBroadcastRequestConfirmBroadcast(ctx, mb.TxID())
if err != nil {
log.Errorf("could not confirm broadcast: %v", err)
return
}
log.Infof("successfully broadcast tx %s, for l2 keystone %s", mb.TxID(), tl2.L2Keystone.Hash())
}
func (s *Server) bitcoinBroadcastWorker(ctx context.Context, highPriority bool) {
log.Tracef("bitcoinBroadcastWorker")
defer log.Tracef("bitcoinBroadcastWorker exit")
defer s.wg.Done()
for {
select {
case <-ctx.Done():
return
default:
s.handleOneBroadcastRequest(ctx, highPriority)
}
}
}
func (s *Server) handleBitcoinBroadcast(ctx context.Context, bbr *bfgapi.BitcoinBroadcastRequest) (any, error) {
log.Tracef("handleBitcoinBroadcast")
defer log.Tracef("handleBitcoinBroadcast exit")
rr := bytes.NewReader(bbr.Transaction)
mb := wire.MsgTx{}
if err := mb.Deserialize(rr); err != nil {
return &bfgapi.BitcoinBroadcastResponse{Error: protocol.RequestErrorf(
"failed to deserialize tx: %s", err,
)}, nil
}
var (
tl2 *pop.TransactionL2
err error
)
for _, v := range mb.TxOut {
tl2, err = pop.ParseTransactionL2FromOpReturn(v.PkScript)
if err == nil {
break // Found the pop transaction.
}
}
if tl2 == nil {
return &bfgapi.BitcoinBroadcastResponse{
Error: protocol.RequestErrorf("could not find l2 keystone abbrev in btc tx"),
}, nil
}
_, err = pop.ParsePublicKeyFromSignatureScript(mb.TxIn[0].SignatureScript)
if err != nil {
return &bfgapi.BitcoinBroadcastResponse{
Error: protocol.RequestErrorf("could not parse signature script: %v", err),
}, nil
}
err = s.db.BtcTransactionBroadcastRequestInsert(ctx, bbr.Transaction, mb.TxID())
if err != nil && !errors.Is(err, database.ErrDuplicate) {
e := protocol.NewInternalErrorf("insert broadcast request : %w", err)
return &bfgapi.BitcoinBroadcastResponse{
Error: e.ProtocolError(),
}, e
}
hash := mb.TxHash()
return &bfgapi.BitcoinBroadcastResponse{TXID: hash[:]}, nil
}
func (s *Server) updateBtcHeightCache(height uint64) {
log.Tracef("updateBtcHeightCache")
defer log.Tracef("updateBtcHeightCache exit")
s.mtx.Lock()
defer s.mtx.Unlock()
s.btcHeightCache = height
}
func (s *Server) getBtcHeightCache() uint64 {
log.Tracef("getBtcHeightCache")
defer log.Tracef("getBtcHeightCache exit")
s.mtx.Lock()
defer s.mtx.Unlock()
return s.btcHeightCache
}
func (s *Server) handleBitcoinInfo(ctx context.Context, bir *bfgapi.BitcoinInfoRequest) (any, error) {
log.Tracef("handleBitcoinInfo")
defer log.Tracef("handleBitcoinInfo exit")
height := s.getBtcHeightCache()
return &bfgapi.BitcoinInfoResponse{
Height: height,
}, nil
}
func (s *Server) handleBitcoinUTXOs(ctx context.Context, bur *bfgapi.BitcoinUTXOsRequest) (any, error) {
log.Tracef("handleBitcoinUTXOs")
defer log.Tracef("handleBitcoinUTXOs exit")
utxos, err := s.btcClient.UTXOs(ctx, bur.ScriptHash)
if err != nil {
e := protocol.NewInternalErrorf("bitcoin utxos: %w", err)
return &bfgapi.BitcoinUTXOsResponse{
Error: e.ProtocolError(),
}, e
}
buResp := bfgapi.BitcoinUTXOsResponse{}
for _, utxo := range utxos {
buResp.UTXOs = append(buResp.UTXOs, &bfgapi.BitcoinUTXO{
Hash: utxo.Hash,
Index: utxo.Index,
Value: utxo.Value,
})
}
return buResp, nil
}
var ErrAlreadyProcessed error = fmt.Errorf("Already Processed BTC Block")
func (s *Server) processBitcoinBlock(ctx context.Context, height uint64) error {
log.Tracef("Processing Bitcoin block at height %d...", height)
netCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
rbh, err := s.btcClient.RawBlockHeader(netCtx, height)
cancel()
if err != nil {
return fmt.Errorf("get block header at height %v: %w", height, err)
}
// grab the merkle root from the header, I am not sure if there is a
// better way to do this, I couldn't find one and this works
merkleRoot := bitcoin.MerkleRootFromBlockHeader(rbh)
merkleRootEncoded := hex.EncodeToString(merkleRoot)
btcHeaderHash := chainhash.DoubleHashB(rbh[:])
btcHeight := height
btcHeader := rbh
btcBlockTmpChk, err := s.db.BtcBlockByHash(ctx, [32]byte(btcHeaderHash))
if err != nil && !errors.Is(err, database.ErrNotFound) {
return err
}
// block with hash is already at height, no-reorg
if btcBlockTmpChk != nil && btcBlockTmpChk.Height == btcHeight {
return fmt.Errorf("already processed block block: %w", ErrAlreadyProcessed)
}
btcBlock := bfgd.BtcBlock{
Hash: btcHeaderHash,
Header: btcHeader[:],
Height: btcHeight,
}
// these might get quite large; we store all found keystones and
// pop bases here to insert at the end
// we will likely find many of the same keystones so store them in a map
// to remove duplicates
l2Keystones := map[string]bfgd.L2Keystone{}
popBases := []bfgd.PopBasis{}
for index := uint64(0); ; index++ {
log.Tracef("calling tx at pos")
netCtx, cancel = context.WithTimeout(ctx, 5*time.Second)
txHash, merkleHashes, err := s.btcClient.TransactionAtPosition(netCtx,
height, index)
cancel()
log.Tracef("done calling tx as pos")
if err != nil {
if errors.Is(err, electrs.ErrNoTxAtPosition) || strings.HasSuffix(err.Error(), "no tx at position") {
// There is no way to tell how many transactions are
// in a block, so hopefully we've got them all...
break
}
return fmt.Errorf("get transaction at position (height %v, index %v): %w", height, index, err)
}
txHashEncoded := hex.EncodeToString(txHash)
log.Tracef("the raw block header is: %v", rbh)
log.Tracef("the txhash is: %v", txHashEncoded)
log.Tracef("the merkle root is: %v", merkleRootEncoded)
log.Tracef("the merkle hashes are: %v", merkleHashes)
log.Tracef("Processing Bitcoin block %d, transaction %d...",
height, index)
log.Tracef("validating bitcoin tx")
err = bitcoin.ValidateMerkleRoot(txHashEncoded, merkleHashes,
uint32(index), merkleRootEncoded)
if err != nil {
log.Errorf("merkle root validation failed for tx %s: %s",
txHashEncoded, err)
} else {
log.Infof("btc tx is valid with hash %s", txHashEncoded)
}
netCtx, cancel = context.WithTimeout(ctx, 5*time.Second)
rtx, err := s.btcClient.RawTransaction(netCtx, txHash)
cancel()
if err != nil {
return fmt.Errorf("get raw transaction with txid %x: %w", txHash, err)
}
log.Infof("got raw transaction with txid %x", txHash)
mtx := &wire.MsgTx{}
if err := mtx.Deserialize(bytes.NewReader(rtx)); err != nil {
log.Tracef("Failed to deserialize transaction: %v", err)
continue
}
var tl2 *pop.TransactionL2
for _, txo := range mtx.TxOut {
tl2, err = pop.ParseTransactionL2FromOpReturn(txo.PkScript)
if err == nil {
break
}
}
if tl2 == nil {
log.Infof("not pop tx found")
continue
}
btcTxIndex := index
log.Infof("found tl2: %v at position %d", tl2, btcTxIndex)
l2kdb := hemiL2KeystoneAbrevToDb(*tl2.L2Keystone)
l2Keystones[hex.EncodeToString(l2kdb.Hash)] = l2kdb
publicKeyUncompressed, err := pop.ParsePublicKeyFromSignatureScript(mtx.TxIn[0].SignatureScript)
if err != nil {
log.Errorf("could not parse signature script: %w", err)
continue
}
popTxIdFull := []byte{}
popTxIdFull = append(popTxIdFull, txHash...)
popTxIdFull = append(popTxIdFull, btcHeader[:]...)
popTxIdFull = binary.AppendUvarint(popTxIdFull, btcTxIndex) // is this correct?
popTxId := chainhash.DoubleHashB(popTxIdFull)
log.Infof("hashed pop transaction id: %v from %v", popTxId, popTxIdFull)
log.Infof("with merkle hashes %v", merkleHashes)
popBasis := bfgd.PopBasis{
BtcTxId: txHash,
BtcHeaderHash: btcHeaderHash,
BtcTxIndex: &btcTxIndex,
PopTxId: popTxId,
L2KeystoneAbrevHash: tl2.L2Keystone.HashB(),
BtcRawTx: rtx,
PopMinerPublicKey: publicKeyUncompressed,
BtcMerklePath: merkleHashes,
}
popBases = append(popBases, popBasis)
}
// XXX: these database inserts should be in a transaction, or simply be atomic
// but they never have been. in the future, let's make sure they are with the
// next solution
// we need to AT LEAST try to insert them here, in case there are network timeouts
// with the above and electrs.
rowsAffected, err := s.db.BtcBlockReplace(ctx, &btcBlock)
if err != nil {
return fmt.Errorf("error replacing bitcoin block: %w", err)
}
if rowsAffected == 0 {
return fmt.Errorf("no rows affected: %w", ErrAlreadyProcessed)
}
// this for loop seems weird but its used to check errors per keystone
for _, l2Keystone := range l2Keystones {
// attempt to insert the abbreviated keystone, this is in case we have
// not heard of this keystone from op node yet
if err := s.db.L2KeystonesInsert(ctx, []bfgd.L2Keystone{l2Keystone}); err != nil {
// this is not necessarily an error, should it be trace?
log.Infof("could not insert l2 keystone: %s", err)
}
}
for _, popBasis := range popBases {
// first, try to update a pop_basis row with NULL btc fields
rowsAffected, err := s.db.PopBasisUpdateBTCFields(ctx, &popBasis)
if err != nil {
return err
}
// if we didn't find any, then we will attempt an insert
if rowsAffected == 0 {
err = s.db.PopBasisInsertFull(ctx, &popBasis)
// if the insert fails due to a duplicate, this means
// that something else has inserted the row before us
// (i.e. a race condition), this is ok, as it should
// have the same values, so we no-op
if err != nil && !errors.Is(err, database.ErrDuplicate) {
return err
}
}
}
return nil
}
func (s *Server) trackBitcoin(ctx context.Context) {
defer s.wg.Done()
log.Tracef("trackBitcoin")
defer log.Tracef("trackBitcoin exit")
// upon startup we walk every block between the tip and our
// configured start block. IMPORTANT NOTE: we ONLY process
// transactions in blocks that we have not seen, so whilst we
// walk quite a few blocks, most will be essentially no-ops
// except for when you have an empty database table
initialWalk := true
btcInterval := 5 * time.Second
ticker := time.NewTicker(btcInterval)
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
log.Tracef("Checking BTC height...")
netCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
btcHeight, err := s.btcClient.Height(netCtx)
cancel()
if err != nil {
// XXX add this to prometheus
log.Errorf("Failed to get Bitcoin height: %v", err)
continue
}
s.updateBtcHeightCache(btcHeight)
err = s.walkChain(ctx, btcHeight, !initialWalk)
if err != nil {
log.Errorf("could not walk chain: %s", err)
continue
}
// after we have done the initial walk with no errors,
// in the future we only walk back until a block that we've seen
initialWalk = false
}
}
}
func (s *Server) walkChain(ctx context.Context, tip uint64, exitFast bool) error {
log.Tracef("walkChain")
defer log.Tracef("walkChain exit")
log.Tracef("starting to walk chain; tip=%d, s.cfg.BTCStartHeight=%d, exitFast=%b", tip, s.cfg.BTCStartHeight, exitFast)
for tip >= s.cfg.BTCStartHeight {
log.Tracef("walkChain progress; processing block at height %d", tip)
err := s.processBitcoinBlock(ctx, tip)
if errors.Is(err, ErrAlreadyProcessed) {
log.Tracef("block known at height %d", tip)
// if we have already seen the block, and the caller wishes
// to exit on first known block, do so
if exitFast {
return nil
}
} else if err != nil {
return err
}
tip--
}
return nil
}
type bfgWs struct {
wg sync.WaitGroup
addr string
conn *protocol.WSConn
sessionId string
listenerName string // "public" or "private"
requestContext context.Context // XXX get rid of this
notify map[notificationId]struct{}
publicKey []byte
}
func (s *Server) handleWebsocketPrivateRead(ctx context.Context, bws *bfgWs) {
defer bws.wg.Done()
log.Tracef("handleWebsocketPrivateRead: %v", bws.addr)
defer log.Tracef("handleWebsocketPrivateRead exit: %v", bws.addr)
for {
cmd, id, payload, err := bfgapi.Read(ctx, bws.conn)
if err != nil {
// Don't log normal close errors.
var ce websocket.CloseError
if !errors.As(err, &ce) {
log.Errorf("handleWebsocketPrivateRead: %v", err)
} else {
log.Tracef("handleWebsocketPrivateRead: %v", err)
}
return
}
// May be too loud.
log.Tracef("handleWebsocketRead read %v: %v %v %v",
bws.addr, cmd, id, spew.Sdump(payload))
switch cmd {
case bfgapi.CmdPingRequest:
if err := s.handlePingRequest(ctx, bws, payload, id); err != nil {
// Terminal error, exit.
log.Errorf("handleWebsocketRead %v %v %v: %v",
bws.addr, cmd, id, err)
return
}
case bfgapi.CmdPopTxForL2BlockRequest:
handler := func(c context.Context) (any, error) {
msg := payload.(*bfgapi.PopTxsForL2BlockRequest)
return s.handlePopTxsForL2Block(c, msg)
}
go s.handleRequest(ctx, bws, id, cmd, handler)
case bfgapi.CmdNewL2KeystonesRequest:
handler := func(c context.Context) (any, error) {
msg := payload.(*bfgapi.NewL2KeystonesRequest)
return s.handleNewL2Keystones(c, msg)
}
go s.handleRequest(ctx, bws, id, cmd, handler)
case bfgapi.CmdBTCFinalityByRecentKeystonesRequest:
handler := func(c context.Context) (any, error) {
msg := payload.(*bfgapi.BTCFinalityByRecentKeystonesRequest)
return s.handleBtcFinalityByRecentKeystonesRequest(c, msg)
}
go s.handleRequest(ctx, bws, id, cmd, handler)
case bfgapi.CmdBTCFinalityByKeystonesRequest:
handler := func(c context.Context) (any, error) {
msg := payload.(*bfgapi.BTCFinalityByKeystonesRequest)
return s.handleBtcFinalityByKeystonesRequest(c, msg)
}
go s.handleRequest(ctx, bws, id, cmd, handler)
default:
// Terminal error, exit.
log.Errorf("handleWebsocketRead %v %v %v: unknown command",
bws.addr, cmd, id)
return
}
s.metrics.rpcCallsTotal.With(prometheus.Labels{
"listener": "private",
"command": string(cmd),
}).Inc()
}
}
func (s *Server) handleWebsocketPublicRead(ctx context.Context, bws *bfgWs) {
defer bws.wg.Done()
log.Tracef("handleWebsocketPublicRead: %v", bws.addr)
defer log.Tracef("handleWebsocketPublicRead exit: %v", bws.addr)
for {
cmd, id, payload, err := bfgapi.Read(ctx, bws.conn)
if err != nil {
// Don't log normal close errors.
var ce websocket.CloseError
if !errors.As(err, &ce) {
log.Debugf("handleWebsocketPublicRead: %v", err)
} else {
log.Tracef("handleWebsocketPublicRead: %v", err)
}
return
}
switch cmd {
case bfgapi.CmdPingRequest:
if err := s.handlePingRequest(ctx, bws, payload, id); err != nil {
// Terminal error, exit.
log.Errorf("handleWebsocketRead %v %v %v: %v",
bws.addr, cmd, id, err)
return
}
case bfgapi.CmdL2KeystonesRequest:
handler := func(c context.Context) (any, error) {
msg := payload.(*bfgapi.L2KeystonesRequest)
return s.handleL2KeystonesRequest(c, msg)
}
go s.handleRequest(ctx, bws, id, cmd, handler)
case bfgapi.CmdBitcoinBalanceRequest:
handler := func(c context.Context) (any, error) {
msg := payload.(*bfgapi.BitcoinBalanceRequest)
return s.handleBitcoinBalance(c, msg)
}
go s.handleRequest(ctx, bws, id, cmd, handler)
case bfgapi.CmdBitcoinBroadcastRequest:
handler := func(c context.Context) (any, error) {
msg := payload.(*bfgapi.BitcoinBroadcastRequest)
return s.handleBitcoinBroadcast(c, msg)
}
go s.handleRequest(ctx, bws, id, cmd, handler)
case bfgapi.CmdBitcoinInfoRequest:
handler := func(c context.Context) (any, error) {
msg := payload.(*bfgapi.BitcoinInfoRequest)
return s.handleBitcoinInfo(c, msg)
}
go s.handleRequest(ctx, bws, id, cmd, handler)
case bfgapi.CmdBitcoinUTXOsRequest:
handler := func(c context.Context) (any, error) {
msg := payload.(*bfgapi.BitcoinUTXOsRequest)
return s.handleBitcoinUTXOs(c, msg)
}
go s.handleRequest(ctx, bws, id, cmd, handler)
default:
// Terminal error, exit.
log.Errorf("handleWebsocketRead %v %v %v: unknown command",
bws.addr, cmd, id)
return
}
s.metrics.rpcCallsTotal.With(prometheus.Labels{
"listener": "public",
"command": string(cmd),
}).Inc()
}
}
func (s *Server) newSession(bws *bfgWs) (string, error) {
b := make([]byte, 16)
for {
// create random value and encode to string
_, err := rand.Read(b)
if err != nil {
return "", err
}
id := hex.EncodeToString(b)