-
Notifications
You must be signed in to change notification settings - Fork 43
/
lightning_client.go
4314 lines (3460 loc) · 119 KB
/
lightning_client.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 lndclient
import (
"bytes"
"context"
"encoding/hex"
"errors"
"fmt"
"io"
"sync"
"time"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/lightningnetwork/lnd/channeldb"
invpkg "github.com/lightningnetwork/lnd/invoices"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lnrpc/invoicesrpc"
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwallet"
"github.com/lightningnetwork/lnd/lnwallet/chainfee"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/routing/route"
"github.com/lightningnetwork/lnd/zpay32"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
// OpenChannelOption is a functional type for an option that modifies an
// OpenChannelRequest.
type OpenChannelOption func(r *lnrpc.OpenChannelRequest)
// WithZeroConf is an option for setting the zero confirmation flag on an
// OpenChannelRequest.
func WithZeroConf() OpenChannelOption {
return func(r *lnrpc.OpenChannelRequest) {
r.ZeroConf = true
}
}
// WithFundingShim is an option for attaching a funding shim to an open channel
// request.
func WithFundingShim(shim *lnrpc.FundingShim) OpenChannelOption {
return func(r *lnrpc.OpenChannelRequest) {
r.FundingShim = shim
}
}
// WithCommitmentType is an option for specifying a commitment type for the open
// channel request.
func WithCommitmentType(t *lnrpc.CommitmentType) OpenChannelOption {
return func(r *lnrpc.OpenChannelRequest) {
r.CommitmentType = *t
}
}
// WithScid signals that the channel open should be an option-scid-alias one.
func WithScid() OpenChannelOption {
return func(r *lnrpc.OpenChannelRequest) {
r.ScidAlias = true
}
}
// LightningClient exposes base lightning functionality.
type LightningClient interface {
PayInvoice(ctx context.Context, invoice string,
maxFee btcutil.Amount,
outgoingChannel *uint64) chan PaymentResult
GetInfo(ctx context.Context) (*Info, error)
// EstimateFee estimates the total fees for a transaction that pays the
// given amount to the passed address.
EstimateFee(ctx context.Context, address btcutil.Address,
amt btcutil.Amount, confTarget int32) (btcutil.Amount, error)
// EstimateFeeToP2WSH estimates the total chain fees in satoshis to send
// the given amount to a single P2WSH output with the given target
// confirmation.
EstimateFeeToP2WSH(ctx context.Context, amt btcutil.Amount,
confTarget int32) (btcutil.Amount, error)
// WalletBalance returns a summary of the node's wallet balance.
WalletBalance(ctx context.Context) (*WalletBalance, error)
AddInvoice(ctx context.Context, in *invoicesrpc.AddInvoiceData) (
lntypes.Hash, string, error)
// LookupInvoice looks up an invoice by hash.
LookupInvoice(ctx context.Context, hash lntypes.Hash) (*Invoice, error)
// ListTransactions returns all known transactions of the backing lnd
// node. It takes a start and end block height which can be used to
// limit the block range that we query over. These values can be left
// as zero to include all blocks. To include unconfirmed transactions
// in the query, endHeight must be set to -1.
ListTransactions(ctx context.Context, startHeight, endHeight int32,
opts ...ListTransactionsOption) ([]Transaction, error)
// ListChannels retrieves all channels of the backing lnd node.
ListChannels(ctx context.Context, activeOnly, publicOnly bool) ([]ChannelInfo, error)
// PendingChannels returns a list of lnd's pending channels.
PendingChannels(ctx context.Context) (*PendingChannels, error)
// ClosedChannels returns all closed channels of the backing lnd node.
ClosedChannels(ctx context.Context) ([]ClosedChannel, error)
// ForwardingHistory makes a paginated call to our forwarding history
// endpoint.
ForwardingHistory(ctx context.Context,
req ForwardingHistoryRequest) (*ForwardingHistoryResponse, error)
// ListInvoices makes a paginated call to our list invoices endpoint.
ListInvoices(ctx context.Context, req ListInvoicesRequest) (
*ListInvoicesResponse, error)
// ListPayments makes a paginated call to our list payments endpoint.
ListPayments(ctx context.Context,
req ListPaymentsRequest) (*ListPaymentsResponse, error)
// ChannelBackup retrieves the backup for a particular channel. The
// backup is returned as an encrypted chanbackup.Single payload.
ChannelBackup(context.Context, wire.OutPoint) ([]byte, error)
// ChannelBackups retrieves backups for all existing pending open and
// open channels. The backups are returned as an encrypted
// chanbackup.Multi payload.
ChannelBackups(ctx context.Context) ([]byte, error)
// SubscribeChannelBackups allows a client to subscribe to the
// most up to date information concerning the state of all channel
// backups.
SubscribeChannelBackups(ctx context.Context) (
<-chan lnrpc.ChanBackupSnapshot, <-chan error, error)
// SubscribeChannelEvents allows a client to subscribe to updates
// relevant to the state of channels. Events include new active
// channels, inactive channels, and closed channels.
SubscribeChannelEvents(ctx context.Context) (
<-chan *ChannelEventUpdate, <-chan error, error)
// DecodePaymentRequest decodes a payment request.
DecodePaymentRequest(ctx context.Context,
payReq string) (*PaymentRequest, error)
// OpenChannel opens a channel to the peer provided with the amounts
// specified.
OpenChannel(ctx context.Context, peer route.Vertex,
localSat, pushSat btcutil.Amount, private bool,
opts ...OpenChannelOption) (
*wire.OutPoint, error)
// OpenChannelStream opens a channel to the specified peer and with the
// specified arguments and options. This function returns a stream of
// updates.
OpenChannelStream(ctx context.Context, peer route.Vertex,
localSat, pushSat btcutil.Amount, private bool,
opts ...OpenChannelOption) (<-chan *OpenStatusUpdate,
<-chan error, error)
// CloseChannel closes the channel provided.
CloseChannel(ctx context.Context, channel *wire.OutPoint,
force bool, confTarget int32, deliveryAddr btcutil.Address) (
chan CloseChannelUpdate, chan error, error)
// UpdateChanPolicy updates the channel policy for the passed chanPoint.
// If the chanPoint is nil, then the policy is applied for all existing
// channels.
UpdateChanPolicy(ctx context.Context, req PolicyUpdateRequest,
chanPoint *wire.OutPoint) error
// GetChanInfo returns the channel info for the passed channel,
// including the routing policy for both end.
GetChanInfo(ctx context.Context, chanID uint64) (*ChannelEdge, error)
// ListPeers gets a list the peers we are currently connected to.
ListPeers(ctx context.Context) ([]Peer, error)
// Connect attempts to connect to a peer at the host specified. If
// permanent is true then we'll attempt to connect to the peer
// permanently, meaning that the connection is maintained even if no
// channels exist between us and the peer.
Connect(ctx context.Context, peer route.Vertex, host string,
permanent bool) error
// SendCoins sends the passed amount of (or all) coins to the passed
// address. Either amount or sendAll must be specified, while
// confTarget, satsPerByte are optional and may be set to zero in which
// case automatic conf target and fee will be used. Returns the tx id
// upon success.
SendCoins(ctx context.Context, addr btcutil.Address,
amount btcutil.Amount, sendAll bool, confTarget int32,
satsPerByte int64, label string) (string, error)
// ChannelBalance returns a summary of our channel balances.
ChannelBalance(ctx context.Context) (*ChannelBalance, error)
// GetNodeInfo looks up information for a specific node.
GetNodeInfo(ctx context.Context, pubkey route.Vertex,
includeChannels bool) (*NodeInfo, error)
// DescribeGraph returns our view of the graph.
DescribeGraph(ctx context.Context, includeUnannounced bool) (*Graph, error)
// SubscribeGraph allows a client to subscribe to gaph topology updates.
SubscribeGraph(ctx context.Context) (<-chan *GraphTopologyUpdate,
<-chan error, error)
// NetworkInfo returns stats regarding our view of the network.
NetworkInfo(ctx context.Context) (*NetworkInfo, error)
// SubscribeInvoices allows a client to subscribe to updates
// of newly added/settled invoices.
SubscribeInvoices(ctx context.Context, req InvoiceSubscriptionRequest) (
<-chan *Invoice, <-chan error, error)
// ListPermissions returns a list of all RPC method URIs and the
// macaroon permissions that are required to access them.
ListPermissions(ctx context.Context) (map[string][]MacaroonPermission,
error)
// ChannelAcceptor create a channel acceptor using the accept function
// passed in. The timeout provided will be used to timeout the passed
// accept closure when it exceeds the amount of time we allow. Note that
// this amount should be strictly less than lnd's chanacceptor timeout
// parameter.
ChannelAcceptor(ctx context.Context, timeout time.Duration,
accept AcceptorFunction) (chan error, error)
// FundingStateStep is a funding related call that allows the execution
// of some preparatory steps for a funding workflow or manual
// progression of a funding workflow.
FundingStateStep(ctx context.Context, req *lnrpc.FundingTransitionMsg) (
*lnrpc.FundingStateStepResp, error)
// QueryRoutes can query LND to return a route (with fees) between two
// vertices.
QueryRoutes(ctx context.Context, req QueryRoutesRequest) (
*QueryRoutesResponse, error)
// CheckMacaroonPermissions allows a client to check the validity of a
// macaroon.
CheckMacaroonPermissions(ctx context.Context, macaroon []byte,
permissions []MacaroonPermission, fullMethod string) (bool,
error)
// RegisterRPCMiddleware adds a new gRPC middleware to the interceptor
// chain. A gRPC middleware is software component external to lnd that
// aims to add additional business logic to lnd by observing/
// intercepting/validating incoming gRPC client requests and (if needed)
// replacing/overwriting outgoing messages before they're sent to the
// client.
RegisterRPCMiddleware(ctx context.Context, middlewareName,
customCaveatName string, readOnly bool, timeout time.Duration,
intercept InterceptFunction) (chan error, error)
// SendCustomMessage sends a custom message to a peer.
SendCustomMessage(ctx context.Context, msg CustomMessage) error
// SubscribeCustomMessages creates a subscription to custom messages
// received from our peers.
SubscribeCustomMessages(ctx context.Context) (<-chan CustomMessage,
<-chan error, error)
// SubscribeTransactions creates a uni-directional stream from the
// server to the client in which any newly discovered transactions
// relevant to the wallet are sent over.
SubscribeTransactions(ctx context.Context) (<-chan Transaction,
<-chan error, error)
// SignMessage signs a message with this node's private key.
// The returned signature string is zbase32 encoded and pubkey
// recoverable, meaning that only the message digest and signature
// are needed for verification.
SignMessage(ctx context.Context, data []byte) (string,
error)
// VerifyMessage verifies a signature over a msg. The signature must
// be zbase32 encoded and signed by an active node in the resident
// node's channel database. In addition to returning the validity of
// the signature, VerifyMessage also returns the recovered pubkey
// from the signature.
VerifyMessage(ctx context.Context, data []byte, signature string) (bool,
string, error)
}
// Info contains info about the connected lnd node.
type Info struct {
// Version is the version that lnd is running.
Version string
// BlockHeight is the best block height that lnd has knowledge of.
BlockHeight uint32
// IdentityPubkey is our node's pubkey.
IdentityPubkey [33]byte
// Alias is our node's alias.
Alias string
// Network is the network we are currently operating on.
Network string
// Uris is the set of our node's advertised uris.
Uris []string
// SyncedToChain is true if the wallet's view is synced to the main
// chain.
SyncedToChain bool
// SyncedToGraph is true if we consider ourselves to be synced with the
// public channel graph.
SyncedToGraph bool
// BestHeaderTimeStamp is the best block timestamp known to the wallet.
BestHeaderTimeStamp time.Time
// ActiveChannels is the number of active channels we have.
ActiveChannels uint32
// InactiveChannels is the number of inactive channels we have.
InactiveChannels uint32
// PendingChannels is the number of pending channels we have.
PendingChannels uint32
}
// ChannelInfo stores unpacked per-channel info.
type ChannelInfo struct {
// ChannelPoint is the funding outpoint of the channel.
ChannelPoint string
// Active indicates whether the channel is active.
Active bool
// ChannelID holds the unique channel ID for the channel. The first 3 bytes
// are the block height, the next 3 the index within the block, and the last
// 2 bytes are the /output index for the channel.
ChannelID uint64
// PubKeyBytes is the raw bytes of the public key of the remote node.
PubKeyBytes route.Vertex
// Capacity is the total amount of funds held in this channel.
Capacity btcutil.Amount
// LocalBalance is the current balance of this node in this channel.
LocalBalance btcutil.Amount
// RemoteBalance is the counterparty's current balance in this channel.
RemoteBalance btcutil.Amount
// UnsettledBalance is the total amount on this channel that is
// unsettled.
UnsettledBalance btcutil.Amount
// Initiator indicates whether we opened the channel or not.
Initiator bool
// Private indicates that the channel is private.
Private bool
// LifeTime is the total amount of time we have monitored the peer's
// online status for.
LifeTime time.Duration
// Uptime is the total amount of time the peer has been observed as
// online over its lifetime.
Uptime time.Duration
// ChanStatusFlags is a set of flags showing the current state of the
// channel.
ChanStatusFlags string
// TotalSent is the total amount sent over this channel for our own
// payments.
TotalSent btcutil.Amount
// TotalReceived is the total amount received over this channel for our
// own receipts.
TotalReceived btcutil.Amount
// NumUpdates is the number of updates we have had on this channel.
NumUpdates uint64
// NumPendingHtlcs is the count of pending htlcs on this channel.
NumPendingHtlcs int
// PendingHtlcs stores the pending HTLCs (amount and direction).
PendingHtlcs []PendingHtlc
// CSVDelay is the csv delay for our funds.
CSVDelay uint64
// FeePerKw is the current fee per kweight of the commit fee.
FeePerKw chainfee.SatPerKWeight
// CommitWeight is the weight of the commit.
CommitWeight int64
// CommitFee is the current commitment's fee.
CommitFee btcutil.Amount
// LocalConstraints is the set of constraints for the local node.
LocalConstraints *ChannelConstraints
// RemoteConstraints is the set of constraints for the remote node.
RemoteConstraints *ChannelConstraints
// CloseAddr is the optional upfront shutdown address set for a
// channel.
CloseAddr btcutil.Address
// ZeroConf indicates whether the channel is a zero conf channel or not.
ZeroConf bool
// ZeroConfScid is the confirmed on-chain zero-conf SCID.
ZeroConfScid uint64
// AliasScids contains a list of alias short channel identifiers that
// may be used for this channel. This array can be empty.
AliasScids []uint64
}
func (s *lightningClient) newChannelInfo(channel *lnrpc.Channel) (*ChannelInfo,
error) {
remoteVertex, err := route.NewVertexFromStr(channel.RemotePubkey)
if err != nil {
return nil, err
}
chanInfo := &ChannelInfo{
ChannelPoint: channel.ChannelPoint,
Active: channel.Active,
ChannelID: channel.ChanId,
PubKeyBytes: remoteVertex,
Capacity: btcutil.Amount(channel.Capacity),
LocalBalance: btcutil.Amount(channel.LocalBalance),
RemoteBalance: btcutil.Amount(channel.RemoteBalance),
UnsettledBalance: btcutil.Amount(channel.UnsettledBalance),
Initiator: channel.Initiator,
Private: channel.Private,
ChanStatusFlags: channel.ChanStatusFlags,
NumPendingHtlcs: len(channel.PendingHtlcs),
TotalSent: btcutil.Amount(channel.TotalSatoshisSent),
TotalReceived: btcutil.Amount(channel.TotalSatoshisReceived),
NumUpdates: channel.NumUpdates,
FeePerKw: chainfee.SatPerKWeight(channel.FeePerKw),
CommitWeight: channel.CommitWeight,
CommitFee: btcutil.Amount(channel.CommitFee),
LifeTime: time.Second * time.Duration(
channel.Lifetime,
),
Uptime: time.Second * time.Duration(
channel.Uptime,
),
LocalConstraints: newChannelConstraint(
channel.LocalConstraints,
),
RemoteConstraints: newChannelConstraint(
channel.RemoteConstraints,
),
ZeroConf: channel.ZeroConf,
ZeroConfScid: channel.ZeroConfConfirmedScid,
}
chanInfo.AliasScids = make([]uint64, len(channel.AliasScids))
copy(chanInfo.AliasScids, channel.AliasScids)
chanInfo.PendingHtlcs = make([]PendingHtlc, len(channel.PendingHtlcs))
for i, rpcHtlc := range channel.PendingHtlcs {
htlc, err := newPendingHtlc(rpcHtlc)
if err != nil {
return nil, err
}
chanInfo.PendingHtlcs[i] = *htlc
}
if channel.CloseAddress != "" {
chanInfo.CloseAddr, err = btcutil.DecodeAddress(
channel.CloseAddress, s.params,
)
if err != nil {
return nil, err
}
}
return chanInfo, nil
}
// ChannelConstraints contains information about the restraints place on a
// channel commit for a particular node.
type ChannelConstraints struct {
// CsvDelay is the relative CSV delay expressed in blocks.
CsvDelay uint32
// Reserve is the minimum balance that the node must maintain.
Reserve btcutil.Amount
// DustLimit is the dust limit for the channel commitment.
DustLimit btcutil.Amount
// MaxPendingAmt is the maximum amount that may be pending on the
// channel.
MaxPendingAmt lnwire.MilliSatoshi
// MinHtlc is the minimum htlc size that will be accepted on the
// channel.
MinHtlc lnwire.MilliSatoshi
// MaxAcceptedHtlcs is the maximum number of htlcs that the node will
// accept from its peer.
MaxAcceptedHtlcs uint32
}
// newChannelConstraint creates a channel constraints struct from the rpc
// response.
func newChannelConstraint(cc *lnrpc.ChannelConstraints) *ChannelConstraints {
if cc == nil {
return nil
}
return &ChannelConstraints{
CsvDelay: cc.CsvDelay,
Reserve: btcutil.Amount(cc.ChanReserveSat),
DustLimit: btcutil.Amount(cc.DustLimitSat),
MaxPendingAmt: lnwire.MilliSatoshi(cc.MaxPendingAmtMsat),
MinHtlc: lnwire.MilliSatoshi(cc.MinHtlcMsat),
MaxAcceptedHtlcs: cc.MaxAcceptedHtlcs,
}
}
// ChannelUpdateType encodes the type of update for a channel update event.
type ChannelUpdateType uint8
const (
// PendingOpenChannelUpdate indicates that the channel event holds
// information about a recently opened channel still in pending state.
PendingOpenChannelUpdate ChannelUpdateType = iota
// OpenChannelUpdate indicates that the channel event holds information
// about a channel that has been opened.
OpenChannelUpdate
// ClosedChannelUpdate indicates that the channel event holds
// information about a closed channel.
ClosedChannelUpdate
// ActiveChannelUpdate indicates that the channel event holds
// information about a channel that became active.
ActiveChannelUpdate
// InactiveChannelUpdate indicates that the channel event holds
// information about a channel that became inactive.
InactiveChannelUpdate
// FullyResolvedChannelUpdate indicates that the channel event holds
// information about a channel has been fully closed.
FullyResolvedChannelUpdate
)
// OpenStatusUpdate is a wrapper for channel status updates following a channel
// open attempt.
type OpenStatusUpdate struct {
// ChanPending signals that the channel is now fully negotiated and the
// funding transaction published.
ChanPending *lnrpc.PendingUpdate
// ChanOpen signals that the channel's funding transaction has now
// reached the required number of confirmations on chain and can be
// used.
ChanOpen *lnrpc.ChannelOpenUpdate
// PsbtFund signals that the funding process has been suspended and the
// construction of a PSBT that funds the channel PK script is now
// required.
PsbtFund *lnrpc.ReadyForPsbtFunding
// PendingChanID is the pending channel ID of the created channel. This
// value may be used to further the funding flow manually via the
// FundingStateStep method.
PendingChanID []byte
}
// ChannelEventUpdate holds the data fields and type for a particular channel
// update event.
type ChannelEventUpdate struct {
// UpdateType encodes the update type. Depending on the type other
// members may be nil.
UpdateType ChannelUpdateType
// ChannelPoints holds the channel point for the updated channel.
ChannelPoint *wire.OutPoint
// OpenedChannelInfo holds the channel info for a newly opened channel.
OpenedChannelInfo *ChannelInfo
// ClosedChannelInfo holds the channel info for a newly closed channel.
ClosedChannelInfo *ClosedChannel
}
// ClosedChannel represents a channel that has been closed.
type ClosedChannel struct {
// ChannelPoint is the funding outpoint of the channel.
ChannelPoint string
// ChannelID holds the unique channel ID for the channel. The first 3
// bytes are the block height, the next 3 the index within the block,
// and the last 2 bytes are the output index for the channel.
ChannelID uint64
// ClosingTxHash is the tx hash of the close transaction for the channel.
ClosingTxHash string
// CloseType is the type of channel closure.
CloseType CloseType
// CloseHeight is the height that the channel was closed at.
CloseHeight uint32
// OpenInitiator is true if we opened the channel. This value is not
// always available (older channels do not have it).
OpenInitiator Initiator
// Initiator indicates which party initiated the channel close. Since
// this value is not always set in the rpc response, we also make a best
// effort attempt to set it based on CloseType.
CloseInitiator Initiator
// PubKeyBytes is the raw bytes of the public key of the remote node.
PubKeyBytes route.Vertex
// Capacity is the total amount of funds held in this channel.
Capacity btcutil.Amount
// SettledBalance is the amount we were paid out directly in this
// channel close. Note that this does not include cases where we need to
// sweep our commitment or htlcs.
SettledBalance btcutil.Amount
}
// CloseType is an enum which represents the types of closes our channels may
// have. This type maps to the rpc value.
type CloseType uint8
const (
// CloseTypeCooperative represents cooperative closes.
CloseTypeCooperative CloseType = iota
// CloseTypeLocalForce represents force closes that we initiated.
CloseTypeLocalForce
// CloseTypeRemoteForce represents force closes that our peer initiated.
CloseTypeRemoteForce
// CloseTypeBreach represents breach closes from our peer.
CloseTypeBreach
// CloseTypeFundingCancelled represents channels which were never
// created because their funding transaction was cancelled.
CloseTypeFundingCancelled
// CloseTypeAbandoned represents a channel that was abandoned.
CloseTypeAbandoned
)
// String returns the string representation of a close type.
func (c CloseType) String() string {
switch c {
case CloseTypeCooperative:
return "Cooperative"
case CloseTypeLocalForce:
return "Local Force"
case CloseTypeRemoteForce:
return "Remote Force"
case CloseTypeBreach:
return "Breach"
case CloseTypeFundingCancelled:
return "Funding Cancelled"
case CloseTypeAbandoned:
return "Abandoned"
default:
return "Unknown"
}
}
// Initiator indicates the party that opened or closed a channel. This enum is
// used for cases where we may not have a full set of initiator information
// available over rpc (this is the case for older channels).
type Initiator uint8
const (
// InitiatorUnrecorded is set when we do not know the open/close
// initiator for a channel, this is the case when the channel was
// closed before lnd started tracking initiators.
InitiatorUnrecorded Initiator = iota
// InitiatorLocal is set when we initiated a channel open or close.
InitiatorLocal
// InitiatorRemote is set when the remote party initiated a chanel open
// or close.
InitiatorRemote
// InitiatorBoth is set in the case where both parties initiated a
// cooperative close (this is possible with multiple rounds of
// negotiation).
InitiatorBoth
)
// ForceCloseAnchorState indicates the resolution state for the anchor.
// There are three resolution states for the anchor: limbo, lost and recovered.
type ForceCloseAnchorState int32
const (
// ForceCloseAnchorStateLimbo is set if the recovered_balance is zero
// and limbo_balance is non-zero.
ForceCloseAnchorStateLimbo = ForceCloseAnchorState(lnrpc.PendingChannelsResponse_ForceClosedChannel_LIMBO)
// ForceCloseAnchorStateRecovered is set if the recovered_balance is
// non-zero.
ForceCloseAnchorStateRecovered = ForceCloseAnchorState(lnrpc.PendingChannelsResponse_ForceClosedChannel_RECOVERED)
// ForceCloseAnchorStateLost indicates a state that is neither
// ForceCloseAnchorStateLimbo nor ForceCloseAnchorStateRecovered.
ForceCloseAnchorStateLost = ForceCloseAnchorState(lnrpc.PendingChannelsResponse_ForceClosedChannel_LOST)
)
// String provides the string represenetation of a close initiator.
func (c Initiator) String() string {
switch c {
case InitiatorUnrecorded:
return "Unrecorded"
case InitiatorLocal:
return "Local"
case InitiatorRemote:
return "Remote"
case InitiatorBoth:
return "Both"
default:
return fmt.Sprintf("unknown initiator: %d", c)
}
}
// Transaction represents an on chain transaction.
type Transaction struct {
// Tx is the on chain transaction.
Tx *wire.MsgTx
// TxHash is the transaction hash string.
TxHash string
// Timestamp is the timestamp our wallet has for the transaction.
Timestamp time.Time
// Amount is the balance change that this transaction had on addresses
// controlled by our wallet.
Amount btcutil.Amount
// Fee is the amount of fees our wallet committed to this transaction.
// Note that this field is not exhaustive, as it does not account for
// fees taken from inputs that the wallet doesn't know it owns (for
// example, the fees taken from our channel balance when we close a
// channel).
Fee btcutil.Amount
// Confirmations is the number of confirmations the transaction has.
Confirmations int32
// Label is an optional label set for on chain transactions.
Label string
// The hash of the block this transaction was included in.
BlockHash string
// The height of the block this transaction was included in.
BlockHeight int32
// Outputs that received funds for this transaction.
OutputDetails []*lnrpc.OutputDetail
// PreviousOutpoints/Inputs of this transaction.
PreviousOutpoints []*lnrpc.PreviousOutPoint
}
// Peer contains information about a peer we are connected to.
type Peer struct {
// Pubkey is the peer's pubkey.
Pubkey route.Vertex
// Address is the host:port of the peer.
Address string
// BytesSent is the total number of bytes we have sent the peer.
BytesSent uint64
// BytesReceived is the total number of bytes we have received from
// the peer.
BytesReceived uint64
// Inbound indicates whether the remote peer initiated the connection.
Inbound bool
// PingTime is the estimated round trip time to this peer.
PingTime time.Duration
// Sent is the total amount we have sent to this peer.
Sent btcutil.Amount
// Received is the total amount we have received from this peer.
Received btcutil.Amount
}
// ChannelBalance contains information about our channel balances.
type ChannelBalance struct {
// Balance is the sum of all open channels balances denominated.
Balance btcutil.Amount
// PendingBalance is the sum of all pending channel balances.
PendingBalance btcutil.Amount
}
// Node describes a node in the network.
type Node struct {
// PubKey is the node's pubkey.
PubKey route.Vertex
// LastUpdate is the last update time for the node.
LastUpdate time.Time
// Alias is the node's chosen alias.
Alias string
// Color is the node's chosen color.
Color string
// Features is the set of features the node supports.
Features []lnwire.FeatureBit
// Addresses holds the network addresses of the node.
Addresses []string
}
func newNode(lnNode *lnrpc.LightningNode) (*Node, error) {
if lnNode == nil {
return nil, nil
}
pubKey, err := route.NewVertexFromStr(lnNode.PubKey)
if err != nil {
return nil, err
}
node := &Node{
PubKey: pubKey,
LastUpdate: time.Unix(int64(lnNode.LastUpdate), 0),
Alias: lnNode.Alias,
Color: lnNode.Color,
Features: make([]lnwire.FeatureBit, 0, len(lnNode.Features)),
Addresses: make([]string, len(lnNode.Addresses)),
}
for featureBit := range lnNode.Features {
node.Features = append(
node.Features, lnwire.FeatureBit(featureBit),
)
}
for i := 0; i < len(lnNode.Addresses); i++ {
node.Addresses[i] = lnNode.Addresses[i].Addr
}
return node, nil
}
// NodeInfo contains information about a node and its channels.
type NodeInfo struct {
// Node contains information about the node itself.
*Node
// ChannelCount is the total number of public channels the node has
// announced.
ChannelCount int
// TotalCapacity is the node's total public channel capacity.
TotalCapacity btcutil.Amount
// Channels contains all of the node's channels, only set if GetNode
// was queried with include channels set to true.
Channels []ChannelEdge
}
// Graph describes our view of the graph.
type Graph struct {
// Nodes is the set of nodes in the channel graph.
Nodes []Node
// Edges is the set of edges in the channel graph.
Edges []ChannelEdge
}
// NodeUpdate holds a node announcement graph topology update.
type NodeUpdate struct {
// Addresses holds the announced node addresses.
Addresses []string
// IdentityKey holds the node's pub key.
IdentityKey route.Vertex
// Features is the set of features the node supports.
Features []lnwire.FeatureBit
// Alias is the node's alias name.
Alias string
// Color is the node's color in hex.
Color string
}
// ChannelEdgeUpdate holds a channel edge graph topology update.
type ChannelEdgeUpdate struct {
// ChannelID is the short channel id.
ChannelID lnwire.ShortChannelID
// ChannelPoint is the funding channel point.
ChannelPoint wire.OutPoint
// Capacity is the channel capacity.
Capacity btcutil.Amount
// RoutingPolicy is the actual routing policy for the channel.
RoutingPolicy RoutingPolicy
// AdvertisingNode is the node who announced the update.
AdvertisingNode route.Vertex
// ConnectingNode is the other end of the channel.
ConnectingNode route.Vertex
}
// ChannelCloseUpdate holds a channel close graph topology update.
type ChannelCloseUpdate struct {
// ChannelID is the short channel id of the closed channel.
ChannelID lnwire.ShortChannelID
// ChannelPoint is the funding channel point of the closed channel.
ChannelPoint wire.OutPoint
// Capacity is the capacity of the closed channel.
Capacity btcutil.Amount
// ClosedHeight is the block height when the channel was closed.
ClosedHeight uint32
}
// GraphTopologyUpdate encapsulates a streamed graph update.
type GraphTopologyUpdate struct {
// NodeUpdates holds the node announcements.
NodeUpdates []NodeUpdate
// ChannelEdgeUpdates holds the channel announcements.
ChannelEdgeUpdates []ChannelEdgeUpdate
// ChannelCloseUpdates holds the closed channel announcements.
ChannelCloseUpdates []ChannelCloseUpdate
}
// NetworkInfo describes the structure of our view of the graph.
type NetworkInfo struct {
// GraphDiameter is the diameter of the graph.
GraphDiameter uint32
// AvgOutDegree is the average out degree in the graph.
AvgOutDegree float64
// MaxOutDegree is the largest out degree in the graph.
MaxOutDegree uint32
// NumNodes is the number of nodes in our view of the network.
NumNodes uint32
// NumChannels is the number of channels in our view of the network.
NumChannels uint32