-
Notifications
You must be signed in to change notification settings - Fork 3
/
api_clnraw.go
1031 lines (840 loc) · 25.7 KB
/
api_clnraw.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 lightning
import (
"context"
"encoding/json"
"fmt"
"io"
"time"
entities "github.com/bolt-observer/go_common/entities"
"github.com/golang/glog"
)
// Compile time check for the interface.
var _ LightingAPICalls = &ClnRawLightningAPI{}
// Method names.
const (
ListChannels = "listchannels"
ListNodes = "listnodes"
ListFunds = "listfunds"
GetInfo = "getinfo"
ListForwards = "listforwards"
ListInvoices = "listinvoices"
ListSendPays = "listsendpays"
ListPays = "listpays"
Connect = "connect"
NewAddr = "newaddr"
Withdraw = "withdraw"
Pay = "pay"
InvoiceCmd = "invoice"
DefaultDuration = 1 * time.Hour
)
// ClnRawLightningAPI struct.
type ClnRawLightningAPI struct {
API
connection ClnConnectionAPI
}
// Cleanup - clean up API.
func (l *ClnRawLightningAPI) Cleanup() {
l.connection.Cleanup()
}
// DescribeGraph - DescribeGraph API call.
func (l *ClnRawLightningAPI) DescribeGraph(ctx context.Context, unannounced bool) (*DescribeGraphAPI, error) {
var reply ClnListNodeResp
err := l.connection.Call(ctx, ListNodes, []interface{}{}, &reply, DefaultDuration)
if err != nil {
return nil, err
}
nodes := make([]DescribeGraphNodeAPI, 0)
for _, one := range reply.Nodes {
nodes = append(nodes, *ConvertNodeInfo(one))
}
channels := make([]NodeChannelAPI, 0)
chans, err := l.GetInternalChannelsAll(ctx)
if err != nil {
return nil, err
}
for k, v := range chans {
if len(v) < 1 {
glog.Warningf("Bad data for %v", k)
continue
}
lnd, err := ToLndChanID(k)
if err != nil {
glog.Warningf("Could not convert %v", k)
continue
}
ret, err := ConvertChannelInternal(v, lnd, "none")
if err != nil {
glog.Warningf("Could not convert %v", k)
continue
}
if !unannounced && ret.Private {
continue
}
channels = append(channels, ret.NodeChannelAPI)
}
return &DescribeGraphAPI{
Nodes: nodes,
Channels: channels,
}, nil
}
// ConvertChannelInternal - convert CLN channel to internal format.
func ConvertChannelInternal(chans []ClnListChan, id uint64, chanpoint string) (*NodeChannelAPIExtended, error) {
ret := &NodeChannelAPIExtended{
NodeChannelAPI: NodeChannelAPI{
ChannelID: id,
Capacity: chans[0].Capacity,
ChanPoint: chanpoint,
},
Private: !chans[0].Public,
}
if chans[0].Source < chans[0].Destination {
ret.Node1Pub = chans[0].Source
ret.Node2Pub = chans[0].Destination
} else {
ret.Node1Pub = chans[0].Destination
ret.Node2Pub = chans[0].Source
}
maxUpdate := time.Time{}
for _, one := range chans {
if time.Time(one.LastUpdate).After(maxUpdate) {
maxUpdate = time.Time(one.LastUpdate)
}
if one.Source == ret.Node1Pub {
ret.Node1Policy = &RoutingPolicyAPI{
TimeLockDelta: uint32(one.Delay),
Disabled: !one.Active,
LastUpdate: one.LastUpdate,
BaseFee: one.FeeBase,
FeeRate: one.FeePpm,
MinHtlc: ConvertAmount(one.MinHtlc),
MaxHtlc: ConvertAmount(one.MaxHtlc),
}
} else if one.Source == ret.Node2Pub {
ret.Node2Policy = &RoutingPolicyAPI{
TimeLockDelta: uint32(one.Delay),
Disabled: !one.Active,
LastUpdate: one.LastUpdate,
BaseFee: one.FeeBase,
FeeRate: one.FeePpm,
MinHtlc: ConvertAmount(one.MinHtlc),
MaxHtlc: ConvertAmount(one.MaxHtlc),
}
} else {
return nil, ErrInvalidResponse
}
}
ret.LastUpdate = entities.JsonTime(maxUpdate)
return ret, nil
}
// GetChanInfo - GetChanInfo API call.
func (l *ClnRawLightningAPI) GetChanInfo(ctx context.Context, chanID uint64) (*NodeChannelAPI, error) {
var listChanReply ClnListChanResp
err := l.connection.Call(ctx, ListChannels, []string{FromLndChanID(chanID)}, &listChanReply, DefaultDuration)
if err != nil {
return nil, err
}
// There can either be one or two channels
if len(listChanReply.Channels) < 1 || len(listChanReply.Channels) > 2 {
return nil, ErrNoChan
}
ret, err := ConvertChannelInternal(listChanReply.Channels, chanID, "none")
if err != nil {
return nil, err
}
return &ret.NodeChannelAPI, nil
}
// GetChannels - GetChannels API call.
func (l *ClnRawLightningAPI) GetChannels(ctx context.Context) (*ChannelsAPI, error) {
var fundsReply ClnFundsChanResp
err := l.connection.Call(ctx, ListFunds, []string{}, &fundsReply, DefaultDuration)
if err != nil {
return nil, err
}
channels := make([]ChannelAPI, 0)
var listChanReply ClnListChanResp
for _, one := range fundsReply.Channels {
err = l.connection.Call(ctx, ListChannels, []string{one.ShortChannelID}, &listChanReply, DefaultDuration)
if err != nil {
return nil, err
}
for _, two := range listChanReply.Channels {
if two.Destination != one.PeerID {
continue
}
lndchan, err := ToLndChanID(one.ShortChannelID)
if err != nil {
return nil, err
}
// TODO: we don't seems to have info about channel reserve, commit-fee, in-flight HTLCs etc.
remoteBalance := uint64(0)
if one.OurAmount <= two.Capacity {
remoteBalance = two.Capacity - one.OurAmount
}
result := ChannelAPI{
Active: two.Active,
Private: !two.Public,
Capacity: two.Capacity,
RemotePubkey: one.PeerID,
ChanID: lndchan,
RemoteBalance: remoteBalance,
LocalBalance: one.OurAmount,
// TODO: No data available
CommitFee: 0,
Initiator: false,
PendingHtlcs: nil,
TotalSatoshisSent: 0,
TotalSatoshisReceived: 0,
NumUpdates: 0,
}
channels = append(channels, result)
}
}
return &ChannelsAPI{Channels: channels}, nil
}
func (l *ClnRawLightningAPI) getMyChannels(ctx context.Context) ([]NodeChannelAPIExtended, error) {
var fundsReply ClnFundsChanResp
err := l.connection.Call(ctx, ListFunds, []string{}, &fundsReply, DefaultDuration)
if err != nil {
return nil, err
}
channels := make([]NodeChannelAPIExtended, 0)
var listChanReply ClnListChanResp
for _, one := range fundsReply.Channels {
err = l.connection.Call(ctx, ListChannels, []string{one.ShortChannelID}, &listChanReply, DefaultDuration)
if err != nil {
return nil, err
}
if one.ShortChannelID == "" {
continue
}
lnd, err := ToLndChanID(one.ShortChannelID)
if err != nil {
glog.Warningf("Could not convert %v", one.ShortChannelID)
continue
}
ret, err := ConvertChannelInternal(listChanReply.Channels, lnd, fmt.Sprintf("%s:%d", one.FundingTxID, one.FundingOutput))
if err != nil {
return nil, err
}
channels = append(channels, *ret)
}
return channels, nil
}
// GetInfo - GetInfo API call.
func (l *ClnRawLightningAPI) GetInfo(ctx context.Context) (*InfoAPI, error) {
var reply ClnInfo
err := l.connection.Call(ctx, GetInfo, []string{}, &reply, DefaultDuration)
if err != nil {
return nil, err
}
syncedToGraph := reply.WarningLightningdSync == ""
syncedToChain := reply.WarningBitcoindSync == ""
return &InfoAPI{
IdentityPubkey: reply.PubKey,
Alias: reply.Alias,
Network: reply.Network,
Chain: "mainnet", // assume mainnet
Version: fmt.Sprintf("corelightning-%s", reply.Version),
IsSyncedToGraph: syncedToGraph,
IsSyncedToChain: syncedToChain,
BlockHeight: int(reply.Blockheight),
}, nil
}
// ConvertNodeInfo - convert CLN to internal node representation.
func ConvertNodeInfo(node ClnListNode) *DescribeGraphNodeAPI {
if node.LastUpdate == nil {
glog.Warningf("Gossip message for node %s was not received yet", node.PubKey)
return &DescribeGraphNodeAPI{
PubKey: node.PubKey,
}
}
addresses := ConvertAddresses(node.Addresses)
features := ConvertFeatures(node.Features)
if features == nil {
features = make(map[string]NodeFeatureAPI)
}
return &DescribeGraphNodeAPI{
PubKey: node.PubKey,
Alias: node.Alias,
Color: fmt.Sprintf("#%s", node.Color),
LastUpdate: *node.LastUpdate,
Addresses: addresses,
Features: features,
}
}
// ConvertAddresses converts CLN addresses to interanl format.
func ConvertAddresses(addr []ClnListNodeAddr) []NodeAddressAPI {
addresses := make([]NodeAddressAPI, 0)
for _, one := range addr {
if one.Type == "ipv6" {
addresses = append(addresses, NodeAddressAPI{Network: "tcp", Addr: fmt.Sprintf("[%s]:%d", one.Address, one.Port)})
} else if one.Type == "dns" || one.Type == "websocket" {
// Ignore that stuff
continue
} else {
addresses = append(addresses, NodeAddressAPI{Network: "tcp", Addr: fmt.Sprintf("%s:%d", one.Address, one.Port)})
}
}
return addresses
}
// GetNodeInfo - API call.
func (l *ClnRawLightningAPI) GetNodeInfo(ctx context.Context, pubKey string, channels bool) (*NodeInfoAPI, error) {
var reply ClnListNodeResp
err := l.connection.Call(ctx, ListNodes, []string{pubKey}, &reply, DefaultDuration)
if err != nil {
return nil, err
}
if len(reply.Nodes) != 1 {
return nil, ErrNoNode
}
result := &NodeInfoAPI{
Node: *ConvertNodeInfo(reply.Nodes[0]),
Channels: make([]NodeChannelAPI, 0),
NumChannels: 0,
TotalCapacity: 0,
}
if !channels {
return result, nil
}
chans, err := l.GetInternalChannels(ctx, pubKey)
if err != nil {
return result, err
}
for k, v := range chans {
if len(v) < 1 {
glog.Warningf("Bad data for %v", k)
continue
}
lnd, err := ToLndChanID(k)
if err != nil {
glog.Warningf("Could not convert %v", k)
continue
}
ret, err := ConvertChannelInternal(v, lnd, "none")
if err != nil {
glog.Warningf("Could not convert %v", k)
continue
}
result.Channels = append(result.Channels, ret.NodeChannelAPI)
}
result.NumChannels = uint32(len(result.Channels))
result.TotalCapacity = SumCapacitySimple(result.Channels)
return result, nil
}
// GetNodeInfoFull - API call.
func (l *ClnRawLightningAPI) GetNodeInfoFull(ctx context.Context, channels bool, unannounced bool) (*NodeInfoAPIExtended, error) {
var reply ClnInfo
err := l.connection.Call(ctx, GetInfo, []string{}, &reply, DefaultDuration)
if err != nil {
return nil, err
}
node := DescribeGraphNodeAPI{
PubKey: reply.PubKey,
Alias: reply.Alias,
Color: fmt.Sprintf("#%s", reply.Color),
Addresses: ConvertAddresses(reply.Addresses),
Features: ConvertFeatures(reply.Features.Node),
LastUpdate: entities.JsonTime(time.Now()),
}
result := &NodeInfoAPIExtended{}
result.Node = node
result.Channels = make([]NodeChannelAPIExtended, 0)
result.NumChannels = 0
result.TotalCapacity = 0
if !channels {
return result, nil
}
chans, err := l.getMyChannels(ctx)
if err != nil {
return nil, err
}
result.Channels = chans
result.NumChannels = uint32(len(result.Channels))
result.TotalCapacity = SumCapacityExtended(result.Channels)
return result, nil
}
// SubscribeForwards - API call.
func (l *ClnRawLightningAPI) SubscribeForwards(ctx context.Context, since time.Time, batchSize uint16, maxErrors uint16) (<-chan []ForwardingEvent, <-chan ErrorData) {
var reply ClnForwardEntries
if batchSize == 0 {
batchSize = l.API.GetDefaultBatchSize()
}
errors := 0
errorChan := make(chan ErrorData, 1)
outChan := make(chan []ForwardingEvent)
go func() {
batch := make([]ForwardingEvent, 0, batchSize)
minTime := since
for {
if ctx.Err() != nil {
return
}
err := l.connection.Call(ctx, ListForwards, []interface{}{}, &reply, DefaultDuration)
if err != nil {
glog.Warningf("Error getting forwards %v\n", err)
if errors >= int(maxErrors) {
errorChan <- ErrorData{Error: err, IsStillRunning: false}
return
}
errorChan <- ErrorData{Error: err, IsStillRunning: true}
continue
}
for _, one := range reply.Entries {
if ctx.Err() != nil {
return
}
if time.Time(one.ReceivedTime).Before(minTime) {
continue
}
if one.Status == "settled" {
continue
}
success := one.Status != "local_failed" && one.Status != "failed"
batch = append(batch, ForwardingEvent{
Timestamp: time.Time(one.ReceivedTime),
ChanIDIn: stringToUint64(one.InChannel),
ChanIDOut: stringToUint64(one.OutChannel),
AmountInMsat: ConvertAmount(one.InMsat),
AmountOutMsat: ConvertAmount(one.OutMsat),
FeeMsat: ConvertAmount(one.FeeMsat),
IsSuccess: success,
FailureString: one.FailReason,
})
if len(batch) >= int(batchSize) {
outChan <- batch
batch = make([]ForwardingEvent, 0, batchSize)
}
}
if len(batch) > 0 {
outChan <- batch
batch = make([]ForwardingEvent, 0, batchSize)
}
minTime = time.Time(reply.Entries[len(reply.Entries)-1].ReceivedTime)
}
}()
return outChan, errorChan
}
func rawJSONIterator(ctx context.Context, reader io.Reader, name string, channel chan json.RawMessage) error {
dec := json.NewDecoder(reader)
// read open bracket
t, err := dec.Token()
if err != nil {
return err
}
x, ok := t.(json.Delim)
if !ok || x.String() != "{" {
return fmt.Errorf("unexpected character")
}
// read array name
t, err = dec.Token()
if err != nil {
return err
}
s, ok := t.(string)
if !ok || s != name {
return fmt.Errorf("unexpected name")
}
// read begin of array
t, err = dec.Token()
if err != nil {
return err
}
x, ok = t.(json.Delim)
if !ok || x.String() != "[" {
return fmt.Errorf("unexpected character")
}
go func(ctx context.Context) {
for dec.More() {
// elements of array
var m json.RawMessage
if ctx.Err() != nil {
return
}
err := dec.Decode(&m)
if err != nil {
return
}
channel <- m
}
close(channel)
}(ctx)
return nil
}
func getRaw[T ClnRawTimeItf](ctx context.Context, l *ClnRawLightningAPI, gettime T, method string, jsonArray string, pagination *RawPagination) ([]RawMessage, *ResponseRawPagination, error) { //nolint:all
respPagination := &ResponseRawPagination{UseTimestamp: true}
if pagination.BatchSize == 0 {
pagination.BatchSize = uint64(l.GetDefaultBatchSize())
}
minTime := time.Unix(1<<63-1, 0)
maxTime := time.Unix(0, 0)
reader, err := l.connection.StreamResponse(ctx, method, []interface{}{})
if err != nil {
return nil, respPagination, err
}
outchan := make(chan json.RawMessage, pagination.BatchSize)
ret := make([]RawMessage, 0, pagination.BatchSize)
err = rawJSONIterator(ctx, reader, jsonArray, outchan)
if err != nil {
return nil, respPagination, err
}
for {
select {
case <-ctx.Done():
return ret, respPagination, nil
case one, ok := <-outchan:
if !ok {
respPagination.FirstTime = minTime
respPagination.LastTime = maxTime
return ret, respPagination, nil
}
err = json.Unmarshal(one, &gettime)
if err != nil {
return nil, respPagination, err
}
t := time.Unix(0, int64(gettime.GetUnixTimeMs()*1e6))
if pagination.From != nil && t.Before(*pagination.From) {
continue
}
if t.Before(minTime) {
minTime = t
}
if t.After(maxTime) {
maxTime = t
}
m := RawMessage{
Implementation: l.Name,
Timestamp: t,
Message: one,
}
ret = append(ret, m)
if len(ret) >= int(pagination.BatchSize) {
respPagination.FirstTime = minTime
respPagination.LastTime = maxTime
return ret, respPagination, nil
}
case <-time.After(1 * time.Second):
respPagination.FirstTime = minTime
respPagination.LastTime = maxTime
return ret, respPagination, nil
}
}
}
// GetInvoicesRaw - API call.
func (l *ClnRawLightningAPI) GetInvoicesRaw(ctx context.Context, pendingOnly bool, pagination RawPagination) ([]RawMessage, *ResponseRawPagination, error) {
var gettime ClnRawInvoiceTime
return getRaw(ctx, l, gettime, ListInvoices, "invoices", &pagination)
}
// GetPaymentsRaw - API call.
func (l *ClnRawLightningAPI) GetPaymentsRaw(ctx context.Context, includeIncomplete bool, pagination RawPagination) ([]RawMessage, *ResponseRawPagination, error) {
var gettime ClnRawPayTime
return getRaw(ctx, l, gettime, ListSendPays, "payments", &pagination)
}
// GetForwardsRaw - API call.
func (l *ClnRawLightningAPI) GetForwardsRaw(ctx context.Context, pagination RawPagination) ([]RawMessage, *ResponseRawPagination, error) {
var gettime ClnRawForwardsTime
return getRaw(ctx, l, gettime, ListForwards, "forwards", &pagination)
}
// GetInvoices - API call.
func (l *ClnRawLightningAPI) GetInvoices(ctx context.Context, pendingOnly bool, pagination Pagination) (*InvoicesResponse, error) {
panic("not implemented")
}
// GetPayments - API call.
func (l *ClnRawLightningAPI) GetPayments(ctx context.Context, includeIncomplete bool, pagination Pagination) (*PaymentsResponse, error) {
panic("not implemented")
}
// GetAPIType - API call.
func (l *ClnRawLightningAPI) GetAPIType() APIType {
return ClnSocket
}
// GetInternalChannels - internal method to get channels.
func (l *ClnRawLightningAPI) GetInternalChannels(ctx context.Context, pubKey string) (map[string][]ClnListChan, error) {
result := make(map[string][]ClnListChan, 0)
var listChanReply ClnListChanResp
err := l.connection.Call(ctx, ListChannels, []interface{}{nil, pubKey, nil}, &listChanReply, DefaultDuration)
if err != nil {
return nil, err
}
for _, one := range listChanReply.Channels {
if one.ShortChannelID == "" {
continue
}
if _, ok := result[one.ShortChannelID]; !ok {
result[one.ShortChannelID] = make([]ClnListChan, 0)
}
result[one.ShortChannelID] = append(result[one.ShortChannelID], one)
}
err = l.connection.Call(ctx, ListChannels, []interface{}{nil, nil, pubKey}, &listChanReply, DefaultDuration)
if err != nil {
return nil, err
}
for _, one := range listChanReply.Channels {
if one.ShortChannelID == "" {
continue
}
if _, ok := result[one.ShortChannelID]; !ok {
result[one.ShortChannelID] = make([]ClnListChan, 0)
}
result[one.ShortChannelID] = append(result[one.ShortChannelID], one)
}
return result, nil
}
// GetInternalChannelsAll - internal method to get all channels.
func (l *ClnRawLightningAPI) GetInternalChannelsAll(ctx context.Context) (map[string][]ClnListChan, error) {
result := make(map[string][]ClnListChan, 0)
var listChanReply ClnListChanResp
err := l.connection.Call(ctx, ListChannels, []interface{}{}, &listChanReply, DefaultDuration)
if err != nil {
return nil, err
}
for _, one := range listChanReply.Channels {
if one.ShortChannelID == "" {
continue
}
if _, ok := result[one.ShortChannelID]; !ok {
result[one.ShortChannelID] = make([]ClnListChan, 0)
}
result[one.ShortChannelID] = append(result[one.ShortChannelID], one)
}
return result, nil
}
// ConnectPeer - API call.
func (l *ClnRawLightningAPI) ConnectPeer(ctx context.Context, id string) error {
var resp ClnConnectResp
err := l.connection.Call(ctx, Connect, []string{id}, &resp, DefaultDuration)
if err != nil {
return err
}
if len(resp.ID) == 0 {
return fmt.Errorf("invalid response")
}
return nil
}
// GetOnChainAddress - API call.
func (l *ClnRawLightningAPI) GetOnChainAddress(ctx context.Context) (string, error) {
var resp ClnNewAddrResp
err := l.connection.Call(ctx, NewAddr, []interface{}{}, &resp, DefaultDuration)
if err != nil {
return "", err
}
if len(resp.Bech32) == 0 {
return "", fmt.Errorf("invalid response")
}
return resp.Bech32, nil
}
// GetOnChainFunds - API call.
func (l *ClnRawLightningAPI) GetOnChainFunds(ctx context.Context) (*Funds, error) {
const (
Confirmed = "confirmed"
Unconfirmed = "uncomfirmed"
Mili = 1000
)
var fundsReply ClnFundsChainResp
err := l.connection.Call(ctx, ListFunds, []string{}, &fundsReply, DefaultDuration)
if err != nil {
return nil, err
}
f := &Funds{}
f.ConfirmedBalance = 0
f.TotalBalance = 0
f.LockedBalance = 0
for _, one := range fundsReply.Outputs {
amount := int64(ConvertAmount(one.AmountMsat))
if !one.Reserved && one.Status == Confirmed {
f.ConfirmedBalance += (amount / Mili)
f.TotalBalance += (amount / Mili)
} else if !one.Reserved && one.Status == Unconfirmed {
f.TotalBalance += (amount / Mili)
} else if one.Reserved && (one.Status == Unconfirmed || one.Status == Confirmed) {
f.LockedBalance += (amount / Mili)
}
}
return f, nil
}
// SendToOnChainAddress - API call.
func (l *ClnRawLightningAPI) SendToOnChainAddress(ctx context.Context, address string, sats int64, useUnconfirmed bool, urgency Urgency) (string, error) {
var reply ClnWithdrawResp
feerate := "normal"
switch urgency {
case Urgent:
feerate = "urgent"
case Normal:
feerate = "normal"
case Low:
feerate = "slow" // slow not low, beware!
}
minConf := 1
if useUnconfirmed {
minConf = 0
}
err := l.connection.Call(ctx, Withdraw, []interface{}{address, sats, feerate, minConf}, &reply, DefaultDuration)
if err != nil {
return "", err
}
if len(reply.TxID) == 0 {
return "", fmt.Errorf("invalid transaction id")
}
return reply.TxID, nil
}
// PayInvoice - API call.
func (l *ClnRawLightningAPI) PayInvoice(ctx context.Context, paymentRequest string, sats int64, outgoingChanIds []uint64) (*PaymentResp, error) {
var (
err error
reply ClnPayResp
)
exclusions, err := l.calculateExclusions(ctx, outgoingChanIds)
if err != nil {
return nil, err
}
// "The response will occur when the payment fails or succeeds. Once a payment has succeeded, calls to pay with the same bolt11 will succeed immediately.
// Until retry_for seconds passes (default: 60), the command will keep finding routes and retrying the payment. However,
// a payment may be delayed for up to maxdelay blocks by another node; clients should be prepared for this worst case.""
// OR in layman terms this might just block for 2016 blocks (almost forever)
timeoutSeconds := 10
timeout := time.Duration((int64(timeoutSeconds) + 1) * int64(time.Second))
if sats > 0 {
err = l.connection.Call(ctx, Pay, []interface{}{paymentRequest, sats * 1000, nil, nil, nil, timeoutSeconds, nil, nil, nil, exclusions}, &reply, timeout)
} else {
err = l.connection.Call(ctx, Pay, []interface{}{paymentRequest, nil, nil, nil, nil, nil, nil, timeoutSeconds, nil, exclusions}, &reply, timeout)
}
if err != nil {
return nil, err
}
r := &PaymentResp{}
if reply.Status == "complete" {
r.Preimage = reply.PaymentPreimage
r.Hash = reply.PaymentHash
r.Status = Success
} else if reply.Status == "pending" {
r.Hash = reply.PaymentHash
r.Preimage = ""
r.Status = Pending
} else {
return nil, fmt.Errorf("payment failed")
}
return r, nil
}
// calculateExclusions is used since CLN can just exclude channels, so we tell it which channels we want and method calculates the "inverse" of it
func (l *ClnRawLightningAPI) calculateExclusions(ctx context.Context, outgoingChanIds []uint64) ([]string, error) {
result := make([]string, 0)
if outgoingChanIds == nil || len(outgoingChanIds) == 0 {
return nil, nil
}
var info ClnInfo
err := l.connection.Call(ctx, GetInfo, []string{}, &info, DefaultDuration)
if err != nil {
return nil, err
}
chans, err := l.getMyChannels(ctx)
if err != nil {
return nil, err
}
m := make(map[uint64]struct{})
for _, id := range outgoingChanIds {
m[id] = struct{}{}
}
for _, one := range chans {
_, ok := m[one.ChannelID]
if ok {
continue
}
// not an outgoing channel, create exclusion
id := FromLndChanID(one.ChannelID)
peer := ""
if one.Node1Pub == info.PubKey {
peer = one.Node2Pub
} else if one.Node2Pub == info.PubKey {
peer = one.Node1Pub
} else {
glog.Warningf("Channel %d is not mine?", one.ChannelID)
continue
}
// direction (u32): 0 if this channel is traversed from lesser to greater id, otherwise 1
direction := 0
if info.PubKey > peer {
direction = 1
}
result = append(result, fmt.Sprintf("%s/%d", id, direction))
}
return result, nil
}
// GetPaymentStatus - API call.
func (l *ClnRawLightningAPI) GetPaymentStatus(ctx context.Context, paymentHash string) (*PaymentResp, error) {
var reply ClnPaymentEntries
err := l.connection.Call(ctx, ListPays, []interface{}{nil, paymentHash}, &reply, DefaultDuration)
if err != nil {
return nil, err
}
if len(reply.Entries) != 1 {
return nil, fmt.Errorf("invalid response")
}
hash := reply.Entries[0].PaymentHash
if hash != paymentHash {
return nil, fmt.Errorf("invalid response")
}
switch reply.Entries[0].Status {
case "failed":
return &PaymentResp{
Status: Failed,
Preimage: "",
Hash: hash,
}, nil
case "complete":
return &PaymentResp{
Status: Success,
Preimage: reply.Entries[0].PaymentPreimage,
Hash: hash,
}, nil
default:
return &PaymentResp{
Status: Pending,
Preimage: "",
Hash: hash,
}, nil
}
}
// CreateInvoice - API call.
func (l *ClnRawLightningAPI) CreateInvoice(ctx context.Context, sats int64, preimage string, memo string, expiry time.Duration) (*InvoiceResp, error) {
var (
err error
reply ClnInvoiceResp
)
duration := int(expiry.Seconds())
if sats > 0 {
if preimage != "" {
err = l.connection.Call(ctx, InvoiceCmd, []interface{}{sats * 1000, "", memo, duration, nil, preimage}, &reply, DefaultDuration)
} else {
err = l.connection.Call(ctx, InvoiceCmd, []interface{}{sats * 1000, "", memo, duration, nil, nil}, &reply, DefaultDuration)
}
} else {
if preimage != "" {
err = l.connection.Call(ctx, InvoiceCmd, []interface{}{"any", "", memo, duration, nil, preimage}, &reply, DefaultDuration)
} else {
err = l.connection.Call(ctx, InvoiceCmd, []interface{}{"any", "", memo, duration, nil, nil}, &reply, DefaultDuration)
}
}
if err != nil {