-
Notifications
You must be signed in to change notification settings - Fork 0
/
chainregistry.go
1047 lines (904 loc) · 31.6 KB
/
chainregistry.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
package chainreg
import (
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net"
"net/url"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/brsuite/brond/bronutil"
"github.com/brsuite/brond/chaincfg/chainhash"
"github.com/brsuite/brond/rpcclient"
"github.com/btcsuite/btcwallet/chain"
"github.com/lightninglabs/neutrino"
"github.com/brolightningnetwork/broln/blockcache"
"github.com/brolightningnetwork/broln/chainntnfs"
"github.com/brolightningnetwork/broln/chainntnfs/bitcoindnotify"
"github.com/brolightningnetwork/broln/chainntnfs/brondnotify"
"github.com/brolightningnetwork/broln/chainntnfs/neutrinonotify"
"github.com/brolightningnetwork/broln/channeldb"
"github.com/brolightningnetwork/broln/htlcswitch"
"github.com/brolightningnetwork/broln/input"
"github.com/brolightningnetwork/broln/keychain"
"github.com/brolightningnetwork/broln/kvdb"
"github.com/brolightningnetwork/broln/lncfg"
"github.com/brolightningnetwork/broln/lnwallet"
"github.com/brolightningnetwork/broln/lnwallet/chainfee"
"github.com/brolightningnetwork/broln/lnwire"
"github.com/brolightningnetwork/broln/routing/chainview"
"github.com/brolightningnetwork/broln/walletunlocker"
)
// Config houses necessary fields that a chainControl instance needs to
// function.
type Config struct {
// Bitcoin defines settings for the Bitcoin chain.
Bitcoin *lncfg.Chain
// Litecoin defines settings for the Litecoin chain.
Litecoin *lncfg.Chain
// PrimaryChain is a function that returns our primary chain via its
// ChainCode.
PrimaryChain func() ChainCode
// HeightHintCacheQueryDisable is a boolean that disables height hint
// queries if true.
HeightHintCacheQueryDisable bool
// NeutrinoMode defines settings for connecting to a neutrino
// light-client.
NeutrinoMode *lncfg.Neutrino
// BitcoindMode defines settings for connecting to a bitcoind node.
BitcoindMode *lncfg.Bitcoind
// LitecoindMode defines settings for connecting to a litecoind node.
LitecoindMode *lncfg.Bitcoind
// brondMode defines settings for connecting to a brond node.
brondMode *lncfg.brond
// LtcdMode defines settings for connecting to an ltcd node.
LtcdMode *lncfg.brond
// HeightHintDB is a pointer to the database that stores the height
// hints.
HeightHintDB kvdb.Backend
// ChanStateDB is a pointer to the database that stores the channel
// state.
ChanStateDB *channeldb.ChannelStateDB
// BlockCache is the main cache for storing block information.
BlockCache *blockcache.BlockCache
// WalletUnlockParams are the parameters that were used for unlocking
// the main wallet.
WalletUnlockParams *walletunlocker.WalletUnlockParams
// NeutrinoCS is a pointer to a neutrino ChainService. Must be non-nil
// if using neutrino.
NeutrinoCS *neutrino.ChainService
// ActiveNetParams details the current chain we are on.
ActiveNetParams BitcoinNetParams
// FeeURL defines the URL for fee estimation we will use. This field is
// optional.
FeeURL string
// Dialer is a function closure that will be used to establish outbound
// TCP connections to Bitcoin peers in the event of a pruned block being
// requested.
Dialer chain.Dialer
}
const (
// DefaultBitcoinMinHTLCInMSat is the default smallest value htlc this
// node will accept. This value is proposed in the channel open sequence
// and cannot be changed during the life of the channel. It is 1 msat by
// default to allow maximum flexibility in deciding what size payments
// to forward.
//
// All forwarded payments are subjected to the min htlc constraint of
// the routing policy of the outgoing channel. This implicitly controls
// the minimum htlc value on the incoming channel too.
DefaultBitcoinMinHTLCInMSat = lnwire.MilliSatoshi(1)
// DefaultBitcoinMinHTLCOutMSat is the default minimum htlc value that
// we require for sending out htlcs. Our channel peer may have a lower
// min htlc channel parameter, but we - by default - don't forward
// anything under the value defined here.
DefaultBitcoinMinHTLCOutMSat = lnwire.MilliSatoshi(1000)
// DefaultBitcoinBaseFeeMSat is the default forwarding base fee.
DefaultBitcoinBaseFeeMSat = lnwire.MilliSatoshi(1000)
// DefaultBitcoinFeeRate is the default forwarding fee rate.
DefaultBitcoinFeeRate = lnwire.MilliSatoshi(1)
// DefaultBitcoinTimeLockDelta is the default forwarding time lock
// delta.
DefaultBitcoinTimeLockDelta = 40
DefaultLitecoinMinHTLCInMSat = lnwire.MilliSatoshi(1)
DefaultLitecoinMinHTLCOutMSat = lnwire.MilliSatoshi(1000)
DefaultLitecoinBaseFeeMSat = lnwire.MilliSatoshi(1000)
DefaultLitecoinFeeRate = lnwire.MilliSatoshi(1)
DefaultLitecoinTimeLockDelta = 576
DefaultLitecoinDustLimit = bronutil.Amount(54600)
// DefaultBitcoinStaticFeePerKW is the fee rate of 50 sat/vbyte
// expressed in sat/kw.
DefaultBitcoinStaticFeePerKW = chainfee.SatPerKWeight(12500)
// DefaultBitcoinStaticMinRelayFeeRate is the min relay fee used for
// static estimators.
DefaultBitcoinStaticMinRelayFeeRate = chainfee.FeePerKwFloor
// DefaultLitecoinStaticFeePerKW is the fee rate of 200 sat/vbyte
// expressed in sat/kw.
DefaultLitecoinStaticFeePerKW = chainfee.SatPerKWeight(50000)
// BtcToLtcConversionRate is a fixed ratio used in order to scale up
// payments when running on the Litecoin chain.
BtcToLtcConversionRate = 60
)
// DefaultLtcChannelConstraints is the default set of channel constraints that
// are meant to be used when initially funding a Litecoin channel.
var DefaultLtcChannelConstraints = channeldb.ChannelConstraints{
DustLimit: DefaultLitecoinDustLimit,
MaxAcceptedHtlcs: input.MaxHTLCNumber / 2,
}
// PartialChainControl contains all the primary interfaces of the chain control
// that can be purely constructed from the global configuration. No wallet
// instance is required for constructing this partial state.
type PartialChainControl struct {
// Cfg is the configuration that was used to create the partial chain
// control.
Cfg *Config
// HealthCheck is a function which can be used to send a low-cost, fast
// query to the chain backend to ensure we still have access to our
// node.
HealthCheck func() error
// FeeEstimator is used to estimate an optimal fee for transactions
// important to us.
FeeEstimator chainfee.Estimator
// ChainNotifier is used to receive blockchain events that we are
// interested in.
ChainNotifier chainntnfs.ChainNotifier
// ChainView is used in the router for maintaining an up-to-date graph.
ChainView chainview.FilteredChainView
// ChainSource is the primary chain interface. This is used to operate
// the wallet and do things such as rescanning, sending transactions,
// notifications for received funds, etc.
ChainSource chain.Interface
// RoutingPolicy is the routing policy we have decided to use.
RoutingPolicy htlcswitch.ForwardingPolicy
// MinHtlcIn is the minimum HTLC we will accept.
MinHtlcIn lnwire.MilliSatoshi
// ChannelConstraints is the set of default constraints that will be
// used for any incoming or outgoing channel reservation requests.
ChannelConstraints channeldb.ChannelConstraints
}
// ChainControl couples the three primary interfaces broln utilizes for a
// particular chain together. A single ChainControl instance will exist for all
// the chains broln is currently active on.
type ChainControl struct {
// PartialChainControl is the part of the chain control that was
// initialized purely from the configuration and doesn't contain any
// wallet related elements.
*PartialChainControl
// ChainIO represents an abstraction over a source that can query the
// blockchain.
ChainIO lnwallet.BlockChainIO
// Signer is used to provide signatures over things like transactions.
Signer input.Signer
// KeyRing represents a set of keys that we have the private keys to.
KeyRing keychain.SecretKeyRing
// Wc is an abstraction over some basic wallet commands. This base set
// of commands will be provided to the Wallet *LightningWallet raw
// pointer below.
Wc lnwallet.WalletController
// MsgSigner is used to sign arbitrary messages.
MsgSigner lnwallet.MessageSigner
// Wallet is our LightningWallet that also contains the abstract Wc
// above. This wallet handles all of the lightning operations.
Wallet *lnwallet.LightningWallet
}
// GenDefaultBtcConstraints generates the default set of channel constraints
// that are to be used when funding a Bitcoin channel.
func GenDefaultBtcConstraints() channeldb.ChannelConstraints {
// We use the dust limit for the maximally sized witness program with
// a 40-byte data push.
dustLimit := lnwallet.DustLimitForSize(input.UnknownWitnessSize)
return channeldb.ChannelConstraints{
DustLimit: dustLimit,
MaxAcceptedHtlcs: input.MaxHTLCNumber / 2,
}
}
// NewPartialChainControl creates a new partial chain control that contains all
// the parts that can be purely constructed from the passed in global
// configuration and doesn't need any wallet instance yet.
func NewPartialChainControl(cfg *Config) (*PartialChainControl, func(), error) {
// Set the RPC config from the "home" chain. Multi-chain isn't yet
// active, so we'll restrict usage to a particular chain for now.
homeChainConfig := cfg.Bitcoin
if cfg.PrimaryChain() == LitecoinChain {
homeChainConfig = cfg.Litecoin
}
log.Infof("Primary chain is set to: %v", cfg.PrimaryChain())
cc := &PartialChainControl{
Cfg: cfg,
}
switch cfg.PrimaryChain() {
case BitcoinChain:
cc.RoutingPolicy = htlcswitch.ForwardingPolicy{
MinHTLCOut: cfg.Bitcoin.MinHTLCOut,
BaseFee: cfg.Bitcoin.BaseFee,
FeeRate: cfg.Bitcoin.FeeRate,
TimeLockDelta: cfg.Bitcoin.TimeLockDelta,
}
cc.MinHtlcIn = cfg.Bitcoin.MinHTLCIn
cc.FeeEstimator = chainfee.NewStaticEstimator(
DefaultBitcoinStaticFeePerKW,
DefaultBitcoinStaticMinRelayFeeRate,
)
case LitecoinChain:
cc.RoutingPolicy = htlcswitch.ForwardingPolicy{
MinHTLCOut: cfg.Litecoin.MinHTLCOut,
BaseFee: cfg.Litecoin.BaseFee,
FeeRate: cfg.Litecoin.FeeRate,
TimeLockDelta: cfg.Litecoin.TimeLockDelta,
}
cc.MinHtlcIn = cfg.Litecoin.MinHTLCIn
cc.FeeEstimator = chainfee.NewStaticEstimator(
DefaultLitecoinStaticFeePerKW, 0,
)
default:
return nil, nil, fmt.Errorf("default routing policy for chain "+
"%v is unknown", cfg.PrimaryChain())
}
var err error
heightHintCacheConfig := chainntnfs.CacheConfig{
QueryDisable: cfg.HeightHintCacheQueryDisable,
}
if cfg.HeightHintCacheQueryDisable {
log.Infof("Height Hint Cache Queries disabled")
}
// Initialize the height hint cache within the chain directory.
hintCache, err := chainntnfs.NewHeightHintCache(
heightHintCacheConfig, cfg.HeightHintDB,
)
if err != nil {
return nil, nil, fmt.Errorf("unable to initialize height hint "+
"cache: %v", err)
}
// If spv mode is active, then we'll be using a distinct set of
// chainControl interfaces that interface directly with the p2p network
// of the selected chain.
switch homeChainConfig.Node {
case "neutrino":
// We'll create ChainNotifier and FilteredChainView instances,
// along with the wallet's ChainSource, which are all backed by
// the neutrino light client.
cc.ChainNotifier = neutrinonotify.New(
cfg.NeutrinoCS, hintCache, hintCache, cfg.BlockCache,
)
cc.ChainView, err = chainview.NewCfFilteredChainView(
cfg.NeutrinoCS, cfg.BlockCache,
)
if err != nil {
return nil, nil, err
}
// Map the deprecated neutrino feeurl flag to the general fee
// url.
if cfg.NeutrinoMode.FeeURL != "" {
if cfg.FeeURL != "" {
return nil, nil, errors.New("feeurl and " +
"neutrino.feeurl are mutually " +
"exclusive")
}
cfg.FeeURL = cfg.NeutrinoMode.FeeURL
}
cc.ChainSource = chain.NewNeutrinoClient(
cfg.ActiveNetParams.Params, cfg.NeutrinoCS,
)
// Get our best block as a health check.
cc.HealthCheck = func() error {
_, _, err := cc.ChainSource.GetBestBlock()
return err
}
case "bitcoind", "litecoind":
var bitcoindMode *lncfg.Bitcoind
switch {
case cfg.Bitcoin.Active:
bitcoindMode = cfg.BitcoindMode
case cfg.Litecoin.Active:
bitcoindMode = cfg.LitecoindMode
}
// Otherwise, we'll be speaking directly via RPC and ZMQ to a
// bitcoind node. If the specified host for the brond/ltcd RPC
// server already has a port specified, then we use that
// directly. Otherwise, we assume the default port according to
// the selected chain parameters.
var bitcoindHost string
if strings.Contains(bitcoindMode.RPCHost, ":") {
bitcoindHost = bitcoindMode.RPCHost
} else {
// The RPC ports specified in chainparams.go assume
// brond, which picks a different port so that btcwallet
// can use the same RPC port as bitcoind. We convert
// this back to the btcwallet/bitcoind port.
rpcPort, err := strconv.Atoi(cfg.ActiveNetParams.RPCPort)
if err != nil {
return nil, nil, err
}
rpcPort -= 2
bitcoindHost = fmt.Sprintf("%v:%d",
bitcoindMode.RPCHost, rpcPort)
if (cfg.Bitcoin.Active &&
(cfg.Bitcoin.RegTest || cfg.Bitcoin.SigNet)) ||
(cfg.Litecoin.Active && cfg.Litecoin.RegTest) {
conn, err := net.Dial("tcp", bitcoindHost)
if err != nil || conn == nil {
switch {
case cfg.Bitcoin.Active && cfg.Bitcoin.RegTest:
rpcPort = 18443
case cfg.Litecoin.Active && cfg.Litecoin.RegTest:
rpcPort = 19443
case cfg.Bitcoin.Active && cfg.Bitcoin.SigNet:
rpcPort = 38332
}
bitcoindHost = fmt.Sprintf("%v:%d",
bitcoindMode.RPCHost,
rpcPort)
} else {
conn.Close()
}
}
}
bitcoindCfg := &chain.BitcoindConfig{
ChainParams: cfg.ActiveNetParams.Params,
Host: bitcoindHost,
User: bitcoindMode.RPCUser,
Pass: bitcoindMode.RPCPass,
Dialer: cfg.Dialer,
PrunedModeMaxPeers: bitcoindMode.PrunedNodeMaxPeers,
}
if bitcoindMode.RPCPolling {
bitcoindCfg.PollingConfig = &chain.PollingConfig{
BlockPollingInterval: bitcoindMode.BlockPollingInterval,
TxPollingInterval: bitcoindMode.TxPollingInterval,
}
} else {
bitcoindCfg.ZMQConfig = &chain.ZMQConfig{
ZMQBlockHost: bitcoindMode.ZMQPubRawBlock,
ZMQTxHost: bitcoindMode.ZMQPubRawTx,
ZMQReadDeadline: bitcoindMode.ZMQReadDeadline,
}
}
// Establish the connection to bitcoind and create the clients
// required for our relevant subsystems.
bitcoindConn, err := chain.NewBitcoindConn(bitcoindCfg)
if err != nil {
return nil, nil, err
}
if err := bitcoindConn.Start(); err != nil {
return nil, nil, fmt.Errorf("unable to connect to "+
"bitcoind: %v", err)
}
cc.ChainNotifier = bitcoindnotify.New(
bitcoindConn, cfg.ActiveNetParams.Params, hintCache,
hintCache, cfg.BlockCache,
)
cc.ChainView = chainview.NewBitcoindFilteredChainView(
bitcoindConn, cfg.BlockCache,
)
cc.ChainSource = bitcoindConn.NewBitcoindClient()
// If we're not in regtest mode, then we'll attempt to use a
// proper fee estimator for testnet.
rpcConfig := &rpcclient.ConnConfig{
Host: bitcoindHost,
User: bitcoindMode.RPCUser,
Pass: bitcoindMode.RPCPass,
DisableConnectOnNew: true,
DisableAutoReconnect: false,
DisableTLS: true,
HTTPPostMode: true,
}
if cfg.Bitcoin.Active && !cfg.Bitcoin.RegTest {
log.Infof("Initializing bitcoind backed fee estimator "+
"in %s mode", bitcoindMode.EstimateMode)
// Finally, we'll re-initialize the fee estimator, as
// if we're using bitcoind as a backend, then we can
// use live fee estimates, rather than a statically
// coded value.
fallBackFeeRate := chainfee.SatPerKVByte(25 * 1000)
cc.FeeEstimator, err = chainfee.NewBitcoindEstimator(
*rpcConfig, bitcoindMode.EstimateMode,
fallBackFeeRate.FeePerKWeight(),
)
if err != nil {
return nil, nil, err
}
} else if cfg.Litecoin.Active && !cfg.Litecoin.RegTest {
log.Infof("Initializing litecoind backed fee "+
"estimator in %s mode",
bitcoindMode.EstimateMode)
// Finally, we'll re-initialize the fee estimator, as
// if we're using litecoind as a backend, then we can
// use live fee estimates, rather than a statically
// coded value.
fallBackFeeRate := chainfee.SatPerKVByte(25 * 1000)
cc.FeeEstimator, err = chainfee.NewBitcoindEstimator(
*rpcConfig, bitcoindMode.EstimateMode,
fallBackFeeRate.FeePerKWeight(),
)
if err != nil {
return nil, nil, err
}
}
// We need to use some apis that are not exposed by btcwallet,
// for a health check function so we create an ad-hoc bitcoind
// connection.
chainConn, err := rpcclient.New(rpcConfig, nil)
if err != nil {
return nil, nil, err
}
// The api we will use for our health check depends on the
// bitcoind version.
cmd, ver, err := getBitcoindHealthCheckCmd(chainConn)
if err != nil {
return nil, nil, err
}
// If the getzmqnotifications api is available (was added in
// version 0.17.0) we make sure broln subscribes to the correct
// zmq events. We do this to avoid a situation in which we are
// not notified of new transactions or blocks.
if ver >= 170000 && !bitcoindMode.RPCPolling {
zmqPubRawBlockURL, err := url.Parse(bitcoindMode.ZMQPubRawBlock)
if err != nil {
return nil, nil, err
}
zmqPubRawTxURL, err := url.Parse(bitcoindMode.ZMQPubRawTx)
if err != nil {
return nil, nil, err
}
// Fetch all active zmq notifications from the bitcoind client.
resp, err := chainConn.RawRequest("getzmqnotifications", nil)
if err != nil {
return nil, nil, err
}
zmq := []struct {
Type string `json:"type"`
Address string `json:"address"`
}{}
if err = json.Unmarshal([]byte(resp), &zmq); err != nil {
return nil, nil, err
}
pubRawBlockActive := false
pubRawTxActive := false
for i := range zmq {
if zmq[i].Type == "pubrawblock" {
url, err := url.Parse(zmq[i].Address)
if err != nil {
return nil, nil, err
}
if url.Port() != zmqPubRawBlockURL.Port() {
log.Warnf(
"unable to subscribe to zmq block events on "+
"%s (bitcoind is running on %s)",
zmqPubRawBlockURL.Host,
url.Host,
)
}
pubRawBlockActive = true
}
if zmq[i].Type == "pubrawtx" {
url, err := url.Parse(zmq[i].Address)
if err != nil {
return nil, nil, err
}
if url.Port() != zmqPubRawTxURL.Port() {
log.Warnf(
"unable to subscribe to zmq tx events on "+
"%s (bitcoind is running on %s)",
zmqPubRawTxURL.Host,
url.Host,
)
}
pubRawTxActive = true
}
}
// Return an error if raw tx or raw block notification over
// zmq is inactive.
if !pubRawBlockActive {
return nil, nil, errors.New(
"block notification over zmq is inactive on " +
"bitcoind",
)
}
if !pubRawTxActive {
return nil, nil, errors.New(
"tx notification over zmq is inactive on " +
"bitcoind",
)
}
}
cc.HealthCheck = func() error {
_, err := chainConn.RawRequest(cmd, nil)
return err
}
case "brond", "ltcd":
// Otherwise, we'll be speaking directly via RPC to a node.
//
// So first we'll load brond/ltcd's TLS cert for the RPC
// connection. If a raw cert was specified in the config, then
// we'll set that directly. Otherwise, we attempt to read the
// cert from the path specified in the config.
var brondMode *lncfg.brond
switch {
case cfg.Bitcoin.Active:
brondMode = cfg.brondMode
case cfg.Litecoin.Active:
brondMode = cfg.LtcdMode
}
var rpcCert []byte
if brondMode.RawRPCCert != "" {
rpcCert, err = hex.DecodeString(brondMode.RawRPCCert)
if err != nil {
return nil, nil, err
}
} else {
certFile, err := os.Open(brondMode.RPCCert)
if err != nil {
return nil, nil, err
}
rpcCert, err = ioutil.ReadAll(certFile)
if err != nil {
return nil, nil, err
}
if err := certFile.Close(); err != nil {
return nil, nil, err
}
}
// If the specified host for the brond/ltcd RPC server already
// has a port specified, then we use that directly. Otherwise,
// we assume the default port according to the selected chain
// parameters.
var brondHost string
if strings.Contains(brondMode.RPCHost, ":") {
brondHost = brondMode.RPCHost
} else {
brondHost = fmt.Sprintf("%v:%v", brondMode.RPCHost,
cfg.ActiveNetParams.RPCPort)
}
brondUser := brondMode.RPCUser
brondPass := brondMode.RPCPass
rpcConfig := &rpcclient.ConnConfig{
Host: brondHost,
Endpoint: "ws",
User: brondUser,
Pass: brondPass,
Certificates: rpcCert,
DisableTLS: false,
DisableConnectOnNew: true,
DisableAutoReconnect: false,
}
cc.ChainNotifier, err = brondnotify.New(
rpcConfig, cfg.ActiveNetParams.Params, hintCache,
hintCache, cfg.BlockCache,
)
if err != nil {
return nil, nil, err
}
// Finally, we'll create an instance of the default chain view
// to be used within the routing layer.
cc.ChainView, err = chainview.NewbrondFilteredChainView(
*rpcConfig, cfg.BlockCache,
)
if err != nil {
log.Errorf("unable to create chain view: %v", err)
return nil, nil, err
}
// Create a special websockets rpc client for brond which will be
// used by the wallet for notifications, calls, etc.
chainRPC, err := chain.NewRPCClient(
cfg.ActiveNetParams.Params, brondHost, brondUser,
brondPass, rpcCert, false, 20,
)
if err != nil {
return nil, nil, err
}
cc.ChainSource = chainRPC
// Use a query for our best block as a health check.
cc.HealthCheck = func() error {
_, _, err := cc.ChainSource.GetBestBlock()
return err
}
// If we're not in simnet or regtest mode, then we'll attempt
// to use a proper fee estimator for testnet.
if !cfg.Bitcoin.SimNet && !cfg.Litecoin.SimNet &&
!cfg.Bitcoin.RegTest && !cfg.Litecoin.RegTest {
log.Info("Initializing brond backed fee estimator")
// Finally, we'll re-initialize the fee estimator, as
// if we're using brond as a backend, then we can use
// live fee estimates, rather than a statically coded
// value.
fallBackFeeRate := chainfee.SatPerKVByte(25 * 1000)
cc.FeeEstimator, err = chainfee.NewbrondEstimator(
*rpcConfig, fallBackFeeRate.FeePerKWeight(),
)
if err != nil {
return nil, nil, err
}
}
case "nochainbackend":
backend := &NoChainBackend{}
source := &NoChainSource{
BestBlockTime: time.Now(),
}
cc.ChainNotifier = backend
cc.ChainView = backend
cc.FeeEstimator = backend
cc.ChainSource = source
cc.HealthCheck = func() error {
return nil
}
default:
return nil, nil, fmt.Errorf("unknown node type: %s",
homeChainConfig.Node)
}
switch {
// If the fee URL isn't set, and the user is running mainnet, then
// we'll return an error to instruct them to set a proper fee
// estimator.
case cfg.FeeURL == "" && cfg.Bitcoin.MainNet &&
homeChainConfig.Node == "neutrino":
return nil, nil, fmt.Errorf("--feeurl parameter required " +
"when running neutrino on mainnet")
// Override default fee estimator if an external service is specified.
case cfg.FeeURL != "":
// Do not cache fees on regtest to make it easier to execute
// manual or automated test cases.
cacheFees := !cfg.Bitcoin.RegTest
log.Infof("Using external fee estimator %v: cached=%v",
cfg.FeeURL, cacheFees)
cc.FeeEstimator = chainfee.NewWebAPIEstimator(
chainfee.SparseConfFeeSource{
URL: cfg.FeeURL,
},
!cacheFees,
)
}
ccCleanup := func() {
if cc.FeeEstimator != nil {
if err := cc.FeeEstimator.Stop(); err != nil {
log.Errorf("Failed to stop feeEstimator: %v",
err)
}
}
}
// Start fee estimator.
if err := cc.FeeEstimator.Start(); err != nil {
return nil, nil, err
}
// Select the default channel constraints for the primary chain.
cc.ChannelConstraints = GenDefaultBtcConstraints()
if cfg.PrimaryChain() == LitecoinChain {
cc.ChannelConstraints = DefaultLtcChannelConstraints
}
return cc, ccCleanup, nil
}
// NewChainControl attempts to create a ChainControl instance according
// to the parameters in the passed configuration. Currently three
// branches of ChainControl instances exist: one backed by a running brond
// full-node, another backed by a running bitcoind full-node, and the other
// backed by a running neutrino light client instance. When running with a
// neutrino light client instance, `neutrinoCS` must be non-nil.
func NewChainControl(walletConfig lnwallet.Config,
msgSigner lnwallet.MessageSigner,
pcc *PartialChainControl) (*ChainControl, func(), error) {
cc := &ChainControl{
PartialChainControl: pcc,
MsgSigner: msgSigner,
Signer: walletConfig.Signer,
ChainIO: walletConfig.ChainIO,
Wc: walletConfig.WalletController,
KeyRing: walletConfig.SecretKeyRing,
}
ccCleanup := func() {
if cc.Wallet != nil {
if err := cc.Wallet.Shutdown(); err != nil {
log.Errorf("Failed to shutdown wallet: %v", err)
}
}
}
lnWallet, err := lnwallet.NewLightningWallet(walletConfig)
if err != nil {
return nil, ccCleanup, fmt.Errorf("unable to create wallet: %v",
err)
}
if err := lnWallet.Startup(); err != nil {
return nil, ccCleanup, fmt.Errorf("unable to create wallet: %v",
err)
}
log.Info("LightningWallet opened")
cc.Wallet = lnWallet
return cc, ccCleanup, nil
}
// getBitcoindHealthCheckCmd queries bitcoind for its version to decide which
// api we should use for our health check. We prefer to use the uptime
// command, because it has no locking and is an inexpensive call, which was
// added in version 0.15. If we are on an earlier version, we fallback to using
// getblockchaininfo.
func getBitcoindHealthCheckCmd(client *rpcclient.Client) (string, int64, error) {
// Query bitcoind to get our current version.
resp, err := client.RawRequest("getnetworkinfo", nil)
if err != nil {
return "", 0, err
}
// Parse the response to retrieve bitcoind's version.
info := struct {
Version int64 `json:"version"`
}{}
if err := json.Unmarshal(resp, &info); err != nil {
return "", 0, err
}
// Bitcoind returns a single value representing the semantic version:
// 1000000 * CLIENT_VERSION_MAJOR + 10000 * CLIENT_VERSION_MINOR
// + 100 * CLIENT_VERSION_REVISION + 1 * CLIENT_VERSION_BUILD
//
// The uptime call was added in version 0.15.0, so we return it for
// any version value >= 150000, as per the above calculation.
if info.Version >= 150000 {
return "uptime", info.Version, nil
}
return "getblockchaininfo", info.Version, nil
}
var (
// BitcoinTestnetGenesis is the genesis hash of Bitcoin's testnet
// chain.
BitcoinTestnetGenesis = chainhash.Hash([chainhash.HashSize]byte{
0x18,0x17,0xc7,0x92,0xed,0xd3,0xea,
0x1c,0x48,0xf4,0x1d,0x4f,0xa3,0x8c,
0xef,0x98,0xca,0x9e,0xa2,0x3f,0xd4,
0xb5,0x9a,0x46,0xc2,0x50,0x2f,0x7a,
0x22,0x09,0x00,0x00,
})
// BitcoinSignetGenesis is the genesis hash of Bitcoin's signet chain.
BitcoinSignetGenesis = chainhash.Hash([chainhash.HashSize]byte{
0xf6, 0x1e, 0xee, 0x3b, 0x63, 0xa3, 0x80, 0xa4,
0x77, 0xa0, 0x63, 0xaf, 0x32, 0xb2, 0xbb, 0xc9,
0x7c, 0x9f, 0xf9, 0xf0, 0x1f, 0x2c, 0x42, 0x25,
0xe9, 0x73, 0x98, 0x81, 0x08, 0x00, 0x00, 0x00,
})
// BitcoinMainnetGenesis is the genesis hash of Bitcoin's main chain.
BitcoinMainnetGenesis = chainhash.Hash([chainhash.HashSize]byte{
0x65,0xfd,0x03,0xb3,0x63,0x6e,0x55,
0xc4,0xe3,0x6d,0xca,0x9c,0x4c,0xe6,
0x2d,0xc6,0x6e,0x03,0x75,0x20,0xc3,
0x19,0x4b,0xe7,0xe6,0xe2,0xb0,0x6a,
0x9a,0x08,0x00,0x00,
})
// LitecoinTestnetGenesis is the genesis hash of Litecoin's testnet4
// chain.
LitecoinTestnetGenesis = chainhash.Hash([chainhash.HashSize]byte{
0xa0, 0x29, 0x3e, 0x4e, 0xeb, 0x3d, 0xa6, 0xe6,
0xf5, 0x6f, 0x81, 0xed, 0x59, 0x5f, 0x57, 0x88,
0x0d, 0x1a, 0x21, 0x56, 0x9e, 0x13, 0xee, 0xfd,
0xd9, 0x51, 0x28, 0x4b, 0x5a, 0x62, 0x66, 0x49,
})
// LitecoinMainnetGenesis is the genesis hash of Litecoin's main chain.
LitecoinMainnetGenesis = chainhash.Hash([chainhash.HashSize]byte{
0xe2, 0xbf, 0x04, 0x7e, 0x7e, 0x5a, 0x19, 0x1a,
0xa4, 0xef, 0x34, 0xd3, 0x14, 0x97, 0x9d, 0xc9,
0x98, 0x6e, 0x0f, 0x19, 0x25, 0x1e, 0xda, 0xba,
0x59, 0x40, 0xfd, 0x1f, 0xe3, 0x65, 0xa7, 0x12,
})
// chainMap is a simple index that maps a chain's genesis hash to the
// ChainCode enum for that chain.
chainMap = map[chainhash.Hash]ChainCode{
BitcoinTestnetGenesis: BitcoinChain,
LitecoinTestnetGenesis: LitecoinChain,
BitcoinMainnetGenesis: BitcoinChain,
LitecoinMainnetGenesis: LitecoinChain,
}
// ChainDNSSeeds is a map of a chain's hash to the set of DNS seeds
// that will be use to bootstrap peers upon first startup.
//
// The first item in the array is the primary host we'll use to attempt
// the SRV lookup we require. If we're unable to receive a response
// over UDP, then we'll fall back to manual TCP resolution. The second
// item in the array is a special A record that we'll query in order to
// receive the IP address of the current authoritative DNS server for
// the network seed.
//
// TODO(roasbeef): extend and collapse these and chainparams.go into
// struct like chaincfg.Params.
ChainDNSSeeds = map[chainhash.Hash][][2]string{
BitcoinMainnetGenesis: {
{
"207.180.196.129",
//"nodes.lightning.directory",
//"soa.nodes.lightning.directory",
},
{
"lseed.bitcoinstats.com",
},
},
BitcoinTestnetGenesis: {
{
"207.180.196.129",
//"test.nodes.lightning.directory",
//"soa.nodes.lightning.directory",
},
},
BitcoinSignetGenesis: {
{
"ln.signet.secp.tech",
},
},
LitecoinMainnetGenesis: {
{
"ltc.nodes.lightning.directory",
"soa.nodes.lightning.directory",
},
},
}
)
// ChainRegistry keeps track of the current chains.
type ChainRegistry struct {
sync.RWMutex
activeChains map[ChainCode]*ChainControl
netParams map[ChainCode]*BitcoinNetParams
primaryChain ChainCode
}
// NewChainRegistry creates a new ChainRegistry.
func NewChainRegistry() *ChainRegistry {
return &ChainRegistry{
activeChains: make(map[ChainCode]*ChainControl),
netParams: make(map[ChainCode]*BitcoinNetParams),
}
}
// RegisterChain assigns an active ChainControl instance to a target chain
// identified by its ChainCode.
func (c *ChainRegistry) RegisterChain(newChain ChainCode,
cc *ChainControl) {
c.Lock()
c.activeChains[newChain] = cc
c.Unlock()
}
// LookupChain attempts to lookup an active ChainControl instance for the
// target chain.
func (c *ChainRegistry) LookupChain(targetChain ChainCode) (
*ChainControl, bool) {
c.RLock()
cc, ok := c.activeChains[targetChain]
c.RUnlock()
return cc, ok
}
// LookupChainByHash attempts to look up an active ChainControl which
// corresponds to the passed genesis hash.
func (c *ChainRegistry) LookupChainByHash(
chainHash chainhash.Hash) (*ChainControl, bool) {
c.RLock()
defer c.RUnlock()