-
Notifications
You must be signed in to change notification settings - Fork 6
/
bfg.go
1518 lines (1282 loc) · 43 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 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"
"sync"
"time"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
btcwire "github.com/btcsuite/btcd/wire"
"github.com/davecgh/go-spew/spew"
"github.com/juju/loggo"
"github.com/prometheus/client_golang/prometheus"
"nhooyr.io/websocket"
"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/electrumx"
"github.com/hemilabs/heminetwork/hemi/pop"
"github.com/hemilabs/heminetwork/service/deucalion"
"github.com/hemilabs/heminetwork/service/pprof"
)
// XXX this code needs to be a bit smarter when syncing bitcoin. We should
// return a "not ready" error whe that is the case.
type notificationId string
const (
logLevel = "INFO"
promSubsystem = "bfg_service" // Prometheus
btcFinalityDelay = 9
notifyBtcBlocks notificationId = "btc_blocks"
notifyBtcFinalities notificationId = "btc_finalities"
notifyL2Keystones notificationId = "l2_keystones"
)
var log = loggo.GetLogger("bfg")
func init() {
loggo.ConfigureLoggers(logLevel)
}
func NewDefaultConfig() *Config {
return &Config{
EXBTCAddress: "localhost:18001",
PrivateListenAddress: ":8080",
PublicListenAddress: ":8383",
}
}
// XXX this needs documenting. It isn't obvious if this needs tags or not
// because of lack of documentation.
type popTX struct {
btcHeight uint64
keystone *hemi.Header
merkleHashes [][]byte
popMinerPublicKey []byte
rawBlockHeader []byte
rawTransaction []byte
txHash []byte
txIndex uint32
}
// XXX figure out if this needs to be moved out into the electrumx package.
type btcClient interface {
Balance(ctx context.Context, scriptHash []byte) (*electrumx.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) ([]*electrumx.UTXO, error)
Close() error
}
type Config struct {
BTCStartHeight uint64
EXBTCAddress string
PrivateListenAddress string
PublicListenAddress string
LogLevel string
PgURI string
PrometheusListenAddress string
PprofListenAddress string
PublicKeyAuth bool
}
type Server struct {
mtx sync.RWMutex
wg sync.WaitGroup
cfg *Config
// requests
requestLimit int // Request limiter queue depth
requestLimiter chan bool // Maximum in progress websocket commands
requestTimeout time.Duration
btcHeight uint64
hemiHeight uint32
// PoP transactions by BTC finality block height.
popTXFinality map[uint64][]*popTX // XXX does this need to go away? either because of persistence (thus read from disk every time) or because bitcoin finality notifications are going away
// PoP transactions that have reached finality, sorted
// by HEMI keystone block height. PoP transactions will
// be added to this slice if they reach BTC finality,
// however we're missing a HEMI keystone.
popTXAtFinality []*popTX // XXX see previous XXX
keystonesLock sync.RWMutex // XXX this probably needs to be an sql query
keystones []*hemi.Header
server *http.ServeMux
publicServer *http.ServeMux
btcClient btcClient // XXX evaluate if this is ok
db bfgd.Database
// Prometheus
cmdsProcessed prometheus.Counter
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
}
func NewServer(cfg *Config) (*Server, error) {
if cfg == nil {
cfg = NewDefaultConfig()
}
defaultRequestTimeout := 9 * time.Second // XXX
requestLimit := 1000 // XXX
s := &Server{
cfg: cfg,
requestLimiter: make(chan bool, requestLimit),
requestLimit: requestLimit,
requestTimeout: defaultRequestTimeout,
popTXFinality: make(map[uint64][]*popTX),
btcHeight: cfg.BTCStartHeight,
server: http.NewServeMux(),
publicServer: http.NewServeMux(),
cmdsProcessed: prometheus.NewCounter(prometheus.CounterOpts{
Subsystem: promSubsystem,
Name: "rpc_calls_total",
Help: "The total number of succesful RPC commands",
}),
sessions: make(map[string]*bfgWs),
}
for range requestLimit {
s.requestLimiter <- true
}
var err error
s.btcClient, err = electrumx.NewClient(cfg.EXBTCAddress)
if err != nil {
return nil, fmt.Errorf("create electrumx 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(parrentCtx context.Context, bws *bfgWs, wsid string, requestType string, 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(parrentCtx, s.requestTimeout)
defer cancel()
select {
case <-s.requestLimiter:
default:
log.Infof("Request limiter hit %v: %v", bws.addr, requestType)
<-s.requestLimiter
}
defer func() { s.requestLimiter <- true }()
log.Tracef("Handling request %v: %v", bws.addr, requestType)
response, err := handler(ctx)
if err != nil {
log.Errorf("Failed to handle %v request %v: %v",
requestType, bws.addr, err)
}
if response == nil {
return
}
log.Debugf("Responding to %v request with %v", requestType, 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",
requestType, 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) 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
}
publicKeyUncompressed, err := pop.ParsePublicKeyFromSignatureScript(mb.TxIn[0].SignatureScript)
if err != nil {
return &bfgapi.BitcoinBroadcastResponse{
Error: protocol.RequestErrorf("could not parse signature script: %v", err),
}, nil
}
txHash, err := s.btcClient.Broadcast(ctx, bbr.Transaction)
if err != nil {
// This may not alwyas be an internal error.
e := protocol.NewInternalErrorf("broadcast tx: %w", err)
return &bfgapi.BitcoinBroadcastResponse{
Error: e.ProtocolError(),
}, e
}
if err := s.db.PopBasisInsertPopMFields(ctx, &bfgd.PopBasis{
BtcTxId: txHash,
BtcRawTx: database.ByteArray(bbr.Transaction),
PopMinerPublicKey: publicKeyUncompressed,
L2KeystoneAbrevHash: tl2.L2Keystone.Hash(),
}); err != nil {
if errors.Is(err, database.ErrDuplicate) {
return &bfgapi.BitcoinBroadcastResponse{
Error: protocol.RequestErrorf("pop basis already exists"),
}, nil
}
if errors.Is(err, database.ErrValidation) {
e := protocol.NewInternalErrorf("invalid pop basis: %w", err)
return &bfgapi.BitcoinBroadcastResponse{
Error: e.ProtocolError(),
}, e
}
e := protocol.NewInternalErrorf("insert pop basis: %w", err)
return &bfgapi.BitcoinBroadcastResponse{
Error: e.ProtocolError(),
}, e
}
return &bfgapi.BitcoinBroadcastResponse{TXID: txHash}, nil
}
func (s *Server) handleBitcoinInfo(ctx context.Context, bir *bfgapi.BitcoinInfoRequest) (any, error) {
log.Tracef("handleBitcoinInfo")
defer log.Tracef("handleBitcoinInfo exit")
height, err := s.btcClient.Height(ctx)
if err != nil {
e := protocol.NewInternalErrorf("bitcoin height: %w", err)
return &bfgapi.BitcoinInfoResponse{
Error: e.ProtocolError(),
}, e
}
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
}
func (s *Server) handleAccessPublicKeyCreateRequest(ctx context.Context, acpkc *bfgapi.AccessPublicKeyCreateRequest) (any, error) {
log.Tracef("handleAccessPublicKeyCreateRequest")
defer log.Tracef("handleAccessPublicKeyCreateRequest exit")
publicKey, err := hex.DecodeString(acpkc.PublicKey)
if err != nil {
return &bfgapi.AccessPublicKeyCreateResponse{
Error: protocol.RequestErrorf("public key decode: %v", err),
}, nil
}
if err := s.db.AccessPublicKeyInsert(ctx, &bfgd.AccessPublicKey{
PublicKey: publicKey,
}); err != nil {
if errors.Is(err, database.ErrDuplicate) {
return &bfgapi.AccessPublicKeyCreateResponse{
Error: protocol.RequestErrorf("public key already exists"),
}, nil
}
if errors.Is(err, database.ErrValidation) {
return &bfgapi.AccessPublicKeyCreateResponse{
Error: protocol.RequestErrorf("invalid access public key"),
}, nil
}
e := protocol.NewInternalErrorf("insert public key: %w", err)
return &bfgapi.AccessPublicKeyCreateResponse{
Error: protocol.RequestErrorf("invalid access public key"),
}, e
}
return &bfgapi.AccessPublicKeyCreateResponse{}, nil
}
func (s *Server) handleAccessPublicKeyDelete(ctx context.Context, payload any) (any, error) {
log.Tracef("handleAccessPublicKeyDelete")
defer log.Tracef("handleAccessPublicKeyDelete exit")
accessPublicKeyDeleteRequest, ok := payload.(*bfgapi.AccessPublicKeyDeleteRequest)
if !ok {
return nil, fmt.Errorf("incorrect type %T", payload)
}
b, err := hex.DecodeString(accessPublicKeyDeleteRequest.PublicKey)
if err != nil {
return &bfgapi.AccessPublicKeyDeleteResponse{
Error: protocol.RequestErrorf("public key decode: %v", err),
}, nil
}
if err := s.db.AccessPublicKeyDelete(ctx, &bfgd.AccessPublicKey{
PublicKey: b,
}); err != nil {
if errors.Is(err, database.ErrNotFound) {
// XXX not sure I like giving this information away.
return &bfgapi.AccessPublicKeyDeleteResponse{
Error: protocol.RequestErrorf("public key not found"),
}, nil
}
e := protocol.NewInternalErrorf("error deleting access public key: %w",
err)
return &bfgapi.AccessPublicKeyDeleteResponse{
Error: e.ProtocolError(),
}, e
}
return &bfgapi.AccessPublicKeyDeleteResponse{}, nil
}
func (s *Server) processBitcoinBlock(ctx context.Context, height uint64) error {
log.Tracef("Processing Bitcoin block at height %d...", height)
rbh, err := s.btcClient.RawBlockHeader(ctx, height)
if err != nil {
return fmt.Errorf("get block header at height %v: %v",
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
btcBlock := bfgd.BtcBlock{
Hash: btcHeaderHash,
Header: btcHeader[:],
Height: btcHeight,
}
err = s.db.BtcBlockInsert(ctx, &btcBlock)
if err != nil {
// XXX don't return err here so we keep counting up, need to be smarter
if errors.Is(err, database.ErrDuplicate) {
log.Errorf("could not insert btc block: %s", err)
return nil
}
}
for index := uint64(0); ; index++ {
txHash, merkleHashes, err := s.btcClient.TransactionAtPosition(ctx,
height, index)
if err != nil {
if errors.Is(err, electrumx.ErrNoTxAtPosition) {
// There is no way to tell how many transactions are
// in a block, so hopefully we've got them all...
return nil
}
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)
}
rtx, err := s.btcClient.RawTransaction(ctx, txHash)
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 := &btcwire.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)
publicKeyUncompressed, err := pop.ParsePublicKeyFromSignatureScript(mtx.TxIn[0].SignatureScript)
if err != nil {
return fmt.Errorf("could not parse signature script: %s", err)
}
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.Hash(),
BtcRawTx: rtx,
PopMinerPublicKey: publicKeyUncompressed,
BtcMerklePath: merkleHashes,
}
// 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(database.ErrDuplicate, err) == false {
return err
}
}
}
}
func (s *Server) processBitcoinBlocks(ctx context.Context, start, end uint64) error {
for i := start; i <= end; i++ {
if err := s.processBitcoinBlock(ctx, i); err != nil {
return fmt.Errorf("process bitcoin block at height %d: %w", i, err)
}
s.btcHeight = i
}
return nil
}
func (s *Server) trackBitcoin(ctx context.Context) {
defer s.wg.Done()
log.Tracef("trackBitcoin")
defer log.Tracef("trackBitcoin exit")
btcInterval := 5 * time.Second
ticker := time.NewTicker(btcInterval)
printMsg := true
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
log.Tracef("Checking BTC height...")
btcHeight, err := s.btcClient.Height(ctx)
if err != nil {
if printMsg {
// XXX add this to prometheus
log.Errorf("Failed to get Bitcoin height: %v", err)
printMsg = false
}
continue
}
printMsg = true
if s.btcHeight > btcHeight {
// XXX do we need this check?
log.Errorf("invalid height: current %v > requested %v",
btcHeight, s.btcHeight)
continue
}
if btcHeight <= s.btcHeight {
continue
}
log.Infof("Bitcoin block height increased to %v", btcHeight)
if err := s.processBitcoinBlocks(ctx, s.btcHeight+1, btcHeight); err != nil {
log.Errorf("Failed to process Bitcoin blocks: %v", err)
continue
}
}
}
}
type bfgWs struct {
wg sync.WaitGroup
addr string
conn *protocol.WSConn
sessionId string
requestContext context.Context
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:
err = s.handlePingRequest(ctx, bws, payload, id)
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, "handle pop for l2 block request", 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, "handle new l2 keystones request", 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, "handle finality recent keystones request", 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, "handle finality keystones request", handler)
case bfgapi.CmdAccessPublicKeyCreateRequest:
handler := func(c context.Context) (any, error) {
msg := payload.(*bfgapi.AccessPublicKeyCreateRequest)
return s.handleAccessPublicKeyCreateRequest(c, msg)
}
go s.handleRequest(ctx, bws, id, "handle access key create request", handler)
case bfgapi.CmdAccessPublicKeyDeleteRequest:
handler := func(c context.Context) (any, error) {
msg := payload.(*bfgapi.AccessPublicKeyDeleteRequest)
return s.handleAccessPublicKeyDelete(c, msg)
}
go s.handleRequest(ctx, bws, id, "handle access key delete request", handler)
default:
err = errors.New("unknown command")
}
// If set, it is a terminal error.
if err != nil {
log.Errorf("handleWebsocketRead %v %v %v: %v",
bws.addr, cmd, id, err)
return
}
s.cmdsProcessed.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:
// quick call
err = s.handlePingRequest(ctx, bws, payload, id)
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, "handle l2 keystones request", 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, "handle bitcoin balance request", 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, "handle bitcoin broadcast request", 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, "handle bitcoin broadcast request", 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, "handle bitcoin utxos request", handler)
default:
err = errors.New("unknown command")
}
// If set, it is a terminal error.
if err != nil {
log.Errorf("handleWebsocketRead %v %v %v: %v",
bws.addr, cmd, id, err)
return
}
s.cmdsProcessed.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)
// does this random value exist? if so try again
s.mtx.Lock()
if _, ok := s.sessions[id]; ok {
s.mtx.Unlock()
continue
}
s.sessions[id] = bws
s.mtx.Unlock()
return id, nil
}
}
func (s *Server) deleteSession(id string) {
log.Tracef("deleteSession")
defer log.Tracef("deleteSession exit")
s.mtx.Lock()
_, ok := s.sessions[id]
if ok {
delete(s.sessions, id)
}
s.mtx.Unlock()
if !ok {
log.Errorf("deleteSession: id not found in sessions %s", id)
}
}
func (s *Server) handleWebsocketPrivate(w http.ResponseWriter, r *http.Request) {
log.Tracef("handleWebsocketPrivate: %v", r.RemoteAddr)
defer log.Tracef("handleWebsocketPrivate exit: %v", r.RemoteAddr)
wao := &websocket.AcceptOptions{
CompressionMode: websocket.CompressionContextTakeover,
OriginPatterns: []string{"localhost"},
}
conn, err := websocket.Accept(w, r, wao)
if err != nil {
log.Errorf("Failed to accept websocket connection for %v: %v",
r.RemoteAddr, err)
return
}
defer conn.Close(websocket.StatusProtocolError, "")
bws := &bfgWs{
addr: r.RemoteAddr,
conn: protocol.NewWSConn(conn),
notify: map[notificationId]struct{}{
notifyBtcBlocks: {},
notifyBtcFinalities: {},
},
requestContext: r.Context(),
}
if bws.sessionId, err = s.newSession(bws); err != nil {
log.Errorf("error occurred creating key: %s", err)
return
}
defer func() {
s.deleteSession(bws.sessionId)
}()
bws.wg.Add(1)
go s.handleWebsocketPrivateRead(r.Context(), bws)
// Always ping, required by protocol.
ping := &bfgapi.PingRequest{
Timestamp: time.Now().Unix(),
}
log.Tracef("responding with %s", spew.Sdump(ping))
if err := bfgapi.Write(r.Context(), bws.conn, "0", ping); err != nil {
log.Errorf("Write: %v", err)
}
log.Infof("Unauthenticated connection from %v", r.RemoteAddr)
bws.wg.Wait()
log.Infof("Unauthenticated connection terminated from %v", r.RemoteAddr)
}
func (s *Server) handleWebsocketPublic(w http.ResponseWriter, r *http.Request) {
log.Tracef("handleWebsocketPublic: %v", r.RemoteAddr)
defer log.Tracef("handleWebsocketPublic exit: %v", r.RemoteAddr)
wao := &websocket.AcceptOptions{
CompressionMode: websocket.CompressionContextTakeover,
OriginPatterns: []string{"localhost:43111"},
InsecureSkipVerify: true, // XXX sucks but we don't want to whitelist every locahost port
}
conn, err := websocket.Accept(w, r, wao)
if err != nil {
log.Errorf("Failed to accept websocket connection for %v: %v",
r.RemoteAddr, err)
return
}
defer conn.Close(websocket.StatusNormalClosure, "")
bws := &bfgWs{
addr: r.RemoteAddr,
conn: protocol.NewWSConn(conn),
requestContext: r.Context(),
notify: map[notificationId]struct{}{
notifyL2Keystones: {},
},
}
// Must complete handshake in WSHandshakeTimeout.
hsCtx, hsCancel := context.WithTimeout(context.Background(),
protocol.WSHandshakeTimeout)
defer hsCancel()
authenticator, err := auth.NewSecp256k1AuthServer()
if err != nil {
log.Errorf("Handshake failed for %v: %s", bws.addr, err)
return
}
if err := authenticator.HandshakeServer(hsCtx, bws.conn); err != nil {
log.Errorf("Handshake Server failed for %v: %s", bws.addr, err)
return
}
publicKey := authenticator.RemotePublicKey().SerializeCompressed()
publicKeyEncoded := hex.EncodeToString(publicKey)
log.Tracef("successful handshake with public key: %s", publicKeyEncoded)
if s.cfg.PublicKeyAuth {
log.Tracef("will enforce auth")
// XXX this code should be a function that returns just true
// and false; that function logs errors.
exists, err := s.db.AccessPublicKeyExists(hsCtx, &bfgd.AccessPublicKey{
PublicKey: publicKey,
})
if err != nil {
log.Errorf("error occurred checking if public key exists: %s", err)
return
}
if !exists {
log.Errorf("unauthorized public key: %s", publicKeyEncoded)
conn.Close(protocol.PublicKeyAuthError.Code, protocol.PublicKeyAuthError.Reason)
return
}
}
bws.publicKey = publicKey
if bws.sessionId, err = s.newSession(bws); err != nil {
log.Errorf("error occurred creating key: %s", err)
return
}
defer func() {
s.deleteSession(bws.sessionId)
}()
// Always ping, required by protocol.
ping := &bfgapi.PingRequest{
Timestamp: time.Now().Unix(),
}
if err := bfgapi.Write(r.Context(), bws.conn, "0", ping); err != nil {
log.Errorf("Write: %v", err)
}
bws.wg.Add(1)
go s.handleWebsocketPublicRead(r.Context(), bws)
log.Infof("Authenticated session %s from %s public key %x",
bws.sessionId, r.RemoteAddr, bws.publicKey)
bws.wg.Wait()
log.Infof("Terminated session %s from %s public key %x",
bws.sessionId, r.RemoteAddr, bws.publicKey)
}
func (s *Server) handlePingRequest(ctx context.Context, bws *bfgWs, payload any, id string) error {
log.Tracef("handlePingRequest: %v", bws.addr)
defer log.Tracef("handlePingRequest exit: %v", bws.addr)
p, ok := payload.(*bfgapi.PingRequest)
if !ok {
return fmt.Errorf("handlePingRequest invalid payload type: %T", payload)
}
response := &bfgapi.PingResponse{
OriginTimestamp: p.Timestamp,
Timestamp: time.Now().Unix(),
}
log.Tracef("responding with %v", spew.Sdump(response))
if err := bfgapi.Write(ctx, bws.conn, id, response); err != nil {
return fmt.Errorf("handlePingRequest write: %v %v",
bws.addr, err)
}
return nil