-
Notifications
You must be signed in to change notification settings - Fork 937
/
Copy pathlightning.py
1580 lines (1380 loc) · 51.6 KB
/
lightning.py
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
import json
import logging
import os
import socket
import sys
import tempfile
from contextlib import contextmanager
from decimal import Decimal
from json import JSONEncoder
from math import floor, log10
from typing import Optional, Union
def to_json_default(self, obj):
"""
Try to use .to_json() if available, otherwise use the normal JSON default method.
"""
return getattr(obj.__class__, "to_json", old_json_default)(obj)
old_json_default = JSONEncoder.default
JSONEncoder.default = to_json_default
class RpcError(ValueError):
def __init__(self, method: str, payload: dict, error: str):
super(ValueError, self).__init__(
"RPC call failed: method: {}, payload: {}, error: {}".format(
method, payload, error
)
)
self.method = method
self.payload = payload
self.error = error
class Millisatoshi:
"""
A subtype to represent thousandths of a satoshi.
If you put this in an object, converting to JSON automatically makes it an "...msat" string, so you can safely hand it even to our APIs which treat raw numbers as satoshis. Converts to and from int.
"""
def __init__(self, v: Union[int, str, Decimal]):
"""
Takes either a string ending in 'msat', 'sat', 'btc' or an integer.
"""
if isinstance(v, str):
if v.endswith("msat"):
parsed = Decimal(v[0:-4])
elif v.endswith("sat"):
parsed = Decimal(v[0:-3]) * 1000
elif v.endswith("btc"):
parsed = Decimal(v[0:-3]) * 1000 * 10**8
else:
raise TypeError(
"Millisatoshi must be string with msat/sat/btc suffix or"
" int"
)
if parsed != int(parsed):
raise ValueError("Millisatoshi must be a whole number")
self.millisatoshis = int(parsed)
elif isinstance(v, Millisatoshi):
self.millisatoshis = v.millisatoshis
elif int(v) == v:
self.millisatoshis = int(v)
elif isinstance(v, float):
raise TypeError("Millisatoshi by float is currently not supported")
else:
raise TypeError(
"Millisatoshi must be string with msat/sat/btc suffix or int"
)
if self.millisatoshis < 0:
raise ValueError("Millisatoshi must be >= 0")
def __repr__(self) -> str:
"""
Appends the 'msat' as expected for this type.
"""
return str(self.millisatoshis) + "msat"
def to_satoshi(self) -> Decimal:
"""
Return a Decimal representing the number of satoshis.
"""
return Decimal(self.millisatoshis) / 1000
def to_whole_satoshi(self) -> int:
"""
Return an int respresenting the number of satoshis;
rounded up to the nearest satoshi
"""
return (self.millisatoshis + 999) // 1000
def to_btc(self) -> Decimal:
"""
Return a Decimal representing the number of bitcoin.
"""
return Decimal(self.millisatoshis) / 1000 / 10**8
def to_satoshi_str(self) -> str:
"""
Return a string of form 1234sat or 1234.567sat.
"""
if self.millisatoshis % 1000:
return '{:.3f}sat'.format(self.to_satoshi())
else:
return '{:.0f}sat'.format(self.to_satoshi())
def to_btc_str(self) -> str:
"""
Return a string of form 12.34567890btc or 12.34567890123btc.
"""
if self.millisatoshis % 1000:
return '{:.11f}btc'.format(self.to_btc())
else:
return '{:.8f}btc'.format(self.to_btc())
def to_approx_str(self, digits: int = 3) -> str:
"""Returns the shortmost string using common units representation.
Rounds to significant `digits`. Default: 3
"""
def round_to_n(x: int, n: int) -> float:
return round(x, -int(floor(log10(x))) + (n - 1))
result = self.to_satoshi_str()
# we try to increase digits to check if we did loose out on precision
# without gaining a shorter string, since this is a rarely used UI
# function, performance is not an issue. Adds at least one iteration.
while True:
# first round everything down to effective digits
amount_rounded = round_to_n(self.millisatoshis, digits)
# try different units and take shortest resulting normalized string
amounts_str = [
"%gbtc" % (amount_rounded / 1000 / 10**8),
"%gsat" % (amount_rounded / 1000),
"%gmsat" % (amount_rounded),
]
test_result = min(amounts_str, key=len)
# check result and do another run if necessary
if test_result == result:
return result
elif not result or len(test_result) <= len(result):
digits = digits + 1
result = test_result
else:
return result
def to_json(self) -> str:
return self.__repr__()
def __int__(self) -> int:
return self.millisatoshis
def __lt__(self, other: 'Millisatoshi') -> bool:
if isinstance(other, int):
return self.millisatoshis < other
return self.millisatoshis < other.millisatoshis
def __le__(self, other: 'Millisatoshi') -> bool:
if isinstance(other, int):
return self.millisatoshis <= other
return self.millisatoshis <= other.millisatoshis
def __eq__(self, other: object) -> bool:
if isinstance(other, Millisatoshi):
return self.millisatoshis == other.millisatoshis
elif isinstance(other, int):
return self.millisatoshis == other
else:
return False
def __gt__(self, other: 'Millisatoshi') -> bool:
if isinstance(other, int):
return self.millisatoshis > other
return self.millisatoshis > other.millisatoshis
def __ge__(self, other: 'Millisatoshi') -> bool:
if isinstance(other, int):
return self.millisatoshis >= other
return self.millisatoshis >= other.millisatoshis
def __add__(self, other: 'Millisatoshi') -> 'Millisatoshi':
return Millisatoshi(int(self) + int(other))
def __sub__(self, other: 'Millisatoshi') -> 'Millisatoshi':
return Millisatoshi(int(self) - int(other))
def __mul__(self, other: Union[int, float]) -> 'Millisatoshi':
if isinstance(other, Millisatoshi):
raise TypeError("Resulting unit msat^2 is not supported")
return Millisatoshi(floor(self.millisatoshis * other))
def __truediv__(self, other: Union[int, float, 'Millisatoshi']) -> Union['Millisatoshi', float]:
if isinstance(other, Millisatoshi):
return self.millisatoshis / other.millisatoshis
return Millisatoshi(floor(self.millisatoshis / other))
def __floordiv__(self, other: Union[int, float, 'Millisatoshi']) -> Union['Millisatoshi', int]:
if isinstance(other, Millisatoshi):
return self.millisatoshis // other.millisatoshis
return Millisatoshi(floor(self.millisatoshis // float(other)))
def __mod__(self, other: Union[float, int]) -> 'Millisatoshi':
return Millisatoshi(int(self.millisatoshis % other))
def __radd__(self, other: 'Millisatoshi') -> 'Millisatoshi':
return Millisatoshi(int(self) + int(other))
class UnixSocket(object):
"""A wrapper for socket.socket that is specialized to unix sockets.
Some OS implementations impose restrictions on the Unix sockets.
- On linux OSs the socket path must be shorter than the in-kernel buffer
size (somewhere around 100 bytes), thus long paths may end up failing
the `socket.connect` call.
This is a small wrapper that tries to work around these limitations.
"""
def __init__(self, path: str):
self.path = path
self.sock: Optional[socket.SocketType] = None
self.connect()
def connect(self) -> None:
try:
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect(str(self.path))
except OSError as e:
self.close()
if (e.args[0] == "AF_UNIX path too long" and os.uname()[0] == "Linux"):
# If this is a Linux system we may be able to work around this
# issue by opening our directory and using `/proc/self/fd/` to
# get a short alias for the socket file.
#
# This was heavily inspired by the Open vSwitch code see here:
# https://github.com/openvswitch/ovs/blob/master/python/ovs/socket_util.py
dirname = os.path.dirname(self.path)
basename = os.path.basename(self.path)
# Open an fd to our home directory, that we can then find
# through `/proc/self/fd` and access the contents.
dirfd = os.open(dirname, os.O_DIRECTORY | os.O_RDONLY)
short_path = "/proc/self/fd/%d/%s" % (dirfd, basename)
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect(short_path)
elif (e.args[0] == "AF_UNIX path too long" and os.uname()[0] == "Darwin"):
temp_dir = tempfile.mkdtemp()
temp_link = os.path.join(temp_dir, "socket_link")
if os.path.exists(temp_link):
os.unlink(temp_link)
os.symlink(self.path, temp_link)
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.connect(temp_link)
else:
# There is no good way to recover from this.
raise
def close(self) -> None:
if self.sock is not None:
self.sock.close()
self.sock = None
def sendall(self, b: bytes) -> None:
if self.sock is None:
raise socket.error("not connected")
self.sock.sendall(b)
def recv(self, length: int) -> bytes:
if self.sock is None:
raise socket.error("not connected")
return self.sock.recv(length)
def __del__(self) -> None:
self.close()
class UnixDomainSocketRpc(object):
def __init__(self, socket_path, executor=None, logger=logging, caller_name=None):
self.socket_path = socket_path
self.executor = executor
self.logger = logger
self._notify = None
self._filter = None
if caller_name is None:
self.caller_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
else:
self.caller_name = caller_name
self.cmdprefix = None
self.next_id = 1
def _writeobj(self, sock, obj):
s = json.dumps(obj, ensure_ascii=False)
sock.sendall(bytearray(s, 'UTF-8'))
def _readobj(self, sock, buff=b''):
"""Read a JSON object, starting with buff; returns object and any buffer left over."""
while True:
parts = buff.split(b'\n\n', 1)
if len(parts) == 1:
# Didn't read enough.
b = sock.recv(max(1024, len(buff)))
buff += b
if len(b) == 0:
return {'error': 'Connection to RPC server lost.'}, buff
else:
buff = parts[1]
obj, _ = json.JSONDecoder().raw_decode(parts[0].decode("UTF-8"))
return obj, buff
def __getattr__(self, name):
"""Intercept any call that is not explicitly defined and call @call.
We might still want to define the actual methods in the subclasses for
documentation purposes.
"""
name = name.replace('_', '-')
def wrapper(*args, **kwargs):
if len(args) != 0 and len(kwargs) != 0:
raise RpcError("Cannot mix positional and non-positional arguments")
elif len(args) != 0:
return self.call(name, payload=args)
else:
return self.call(name, payload=kwargs)
return wrapper
def get_json_id(self, method, cmdprefix):
"""Get a nicely formatted, CLN-compliant JSON ID"""
this_id = "{}:{}#{}".format(self.caller_name, method, str(self.next_id))
if cmdprefix is None:
cmdprefix = self.cmdprefix
if cmdprefix:
this_id = f'{cmdprefix}/{this_id}'
return this_id
def call(self, method, payload=None, cmdprefix=None, filter=None):
"""Generic call API: you can set cmdprefix here, or set self.cmdprefix
before the call is made.
"""
self.logger.debug("Calling %s with payload %r", method, payload)
if payload is None:
payload = {}
# Filter out arguments that are None
if isinstance(payload, dict):
payload = {k: v for k, v in payload.items() if v is not None}
this_id = self.get_json_id(method, cmdprefix)
self.next_id += 1
# FIXME: we open a new socket for every readobj call...
sock = UnixSocket(self.socket_path)
buf = b''
if self._notify is not None:
# Opt into the notifications support
self._writeobj(sock, {
"jsonrpc": "2.0",
"method": "notifications",
"id": this_id + "+notify-enable",
"params": {
"enable": True
},
})
# FIXME: Notification schema support?
_, buf = self._readobj(sock, buf)
request = {
"jsonrpc": "2.0",
"method": method,
"params": payload,
"id": this_id,
}
if filter is None:
filter = self._filter
if filter is not None:
request["filter"] = filter
self._writeobj(sock, request)
while True:
resp, buf = self._readobj(sock, buf)
id = resp.get("id", None)
meth = resp.get("method", None)
if meth == 'message' and self._notify is not None:
n = resp['params']
self._notify(
message=n.get('message', None),
progress=n.get('progress', None),
request=request
)
continue
if meth is None or id is None:
break
self.logger.debug("Received response for %s call: %r", method, resp)
if 'id' in resp and resp['id'] != this_id:
raise ValueError("Malformed response, id is not {}: {}.".format(this_id, resp))
sock.close()
if not isinstance(resp, dict):
raise TypeError("Malformed response, response is not a dictionary %s." % resp)
elif "error" in resp:
raise RpcError(method, payload, resp['error'])
elif "result" not in resp:
raise ValueError("Malformed response, \"result\" missing.")
return resp["result"]
@contextmanager
def notify(self, fn):
"""Register a notification callback to use for a set of RPC calls.
This is a context manager and should be used like this:
```python
def fn(message, progress, request, **kwargs):
print(message)
with rpc.notify(fn):
rpc.somemethod()
```
The `fn` function will be called once for each notification
the is sent by `somemethod`. This is a context manager,
meaning that multiple commands can share the same context, and
the same notification function.
"""
old = self._notify
self._notify = fn
yield
self._notify = old
@contextmanager
def reply_filter(self, filter):
"""Filter the fields returned from am RPC call (or more than one)..
This is a context manager and should be used like this:
```python
with rpc.reply_filter({"transactions": [{"outputs": [{"amount_msat": true, "type": true}]}]}):
rpc.listtransactions()
```
"""
old = self._filter
self._filter = filter
yield
self._filter = old
class LightningRpc(UnixDomainSocketRpc):
"""
RPC client for the `lightningd` daemon.
This RPC client connects to the `lightningd` daemon through a unix
domain socket and passes calls through. Since some of the calls
are blocking, the corresponding python methods include an `async`
keyword argument. If `async` is set to true then the method
returns a future immediately, instead of blocking indefinitely.
This implementation is thread safe in that it locks the socket
between calls, but it does not (yet) support concurrent calls.
"""
def __init__(self, socket_path, executor=None, logger=logging):
super().__init__(
socket_path,
executor,
logger
)
def addgossip(self, message):
"""
Inject this (hex-encoded) gossip message.
"""
payload = {
"message": message,
}
return self.call("addgossip", payload)
def autoclean_status(self, subsystem=None):
"""
Print status of autocleaning (optionally, just for {subsystem}).
"""
payload = {
"subsystem": subsystem,
}
return self.call("autoclean-status", payload)
def check(self, command_to_check, **kwargs):
"""
Checks if a command is valid without running it.
"""
payload = {"command_to_check": command_to_check}
payload.update({k: v for k, v in kwargs.items()})
return self.call("check", payload)
def close(self, peer_id, unilateraltimeout=None, destination=None,
fee_negotiation_step=None, force_lease_closed=None, feerange=None):
"""
Close the channel with peer {id}, forcing a unilateral
close after {unilateraltimeout} seconds if non-zero, and
the to-local output will be sent to {destination}.
If channel funds have been leased to the peer and the
lease has not yet expired, you can force a close with
{force_lease_closed}. Note that your funds will still be
locked until the lease expires.
"""
payload = {
"id": peer_id,
"unilateraltimeout": unilateraltimeout,
"destination": destination,
"fee_negotiation_step": fee_negotiation_step,
"force_lease_closed": force_lease_closed,
"feerange": feerange,
}
return self.call("close", payload)
def connect(self, peer_id, host=None, port=None):
"""
Connect to {peer_id} at {host} and {port}.
"""
payload = {
"id": peer_id,
"host": host,
"port": port
}
return self.call("connect", payload)
def datastore(self, key, string=None, hex=None, mode=None, generation=None):
"""
Add/replace an entry in the datastore; either string or hex.
{key} can be a single string, or a sequence of strings.
{mode} defaults to 'must-create', but other options are possible:
- 'must-replace': fail it it doesn't already exist.
- 'create-or-replace': don't fail.
- 'must-append': must exist, and append to existing.
- 'create-or-append': set, or append to existing.
{generation} only succeeds if the current entry has this generation count (mode must be 'must-replace' or 'must-append').
"""
payload = {
"key": key,
"string": string,
"hex": hex,
"mode": mode,
"generation": generation,
}
return self.call("datastore", payload)
def datastoreusage(self, key=None):
"""
Returns the total bytes that are stored for under the given key or the
root of the datastore. All descendants of the given key (or root) are
taken into account.
{key} can be a single string or a sequence of strings.
"""
payload = {
"key": key,
}
return self.call("datastoreusage", payload)
def decodepay(self, bolt11, description=None):
"""
Decode {bolt11}, using {description} if necessary.
"""
payload = {
"bolt11": bolt11,
"description": description
}
return self.call("decodepay", payload)
def deldatastore(self, key, generation=None):
"""
Remove an existing entry from the datastore.
{key} can be a single string, or a sequence of strings.
{generation} means delete only succeeds if the current entry has this generation count.
"""
payload = {
"key": key,
"generation": generation,
}
return self.call("deldatastore", payload)
def delinvoice(self, label, status, desconly=None):
"""
Delete unpaid invoice {label} with {status} (or, with {desconly} true, remove its description).
"""
payload = {
"label": label,
"status": status,
"desconly": desconly,
}
return self.call("delinvoice", payload)
def dev_crash(self):
"""
Crash lightningd by calling fatal().
"""
payload = {
"subcommand": "crash"
}
return self.call("dev", payload)
def dev_fail(self, peer_id):
"""
Fail with peer {peer_id}.
"""
payload = {
"id": peer_id
}
return self.call("dev-fail", payload)
def dev_forget_channel(self, peerid, force=False):
""" Forget the channel with id=peerid.
"""
return self.call(
"dev-forget-channel",
payload={"id": peerid, "force": force}
)
def dev_memdump(self):
"""
Show memory objects currently in use.
"""
return self.call("dev-memdump")
def dev_memleak(self):
"""
Show unreferenced memory objects.
"""
return self.call("dev-memleak")
def dev_pay(self, bolt11, amount_msat=None, label=None, riskfactor=None,
maxfeepercent=None, retry_for=None,
maxdelay=None, exemptfee=None, dev_use_shadow=True, exclude=None):
"""
A developer version of `pay`, with the possibility to deactivate
shadow routing (used for testing).
"""
payload = {
"bolt11": bolt11,
"amount_msat": amount_msat,
"label": label,
"riskfactor": riskfactor,
"maxfeepercent": maxfeepercent,
"retry_for": retry_for,
"maxdelay": maxdelay,
"exemptfee": exemptfee,
"dev_use_shadow": dev_use_shadow,
"exclude": exclude,
}
return self.call("pay", payload)
def dev_reenable_commit(self, peer_id):
"""
Re-enable the commit timer on peer {id}.
"""
payload = {
"id": peer_id
}
return self.call("dev-reenable-commit", payload)
def dev_rescan_outputs(self):
"""
Synchronize the state of our funds with bitcoind.
"""
return self.call("dev-rescan-outputs")
def dev_rhash(self, secret):
"""
Show SHA256 of {secret}
"""
payload = {
"subcommand": "rhash",
"secret": secret
}
return self.call("dev", payload)
def dev_sign_last_tx(self, peer_id):
"""
Sign and show the last commitment transaction with peer {id}.
"""
payload = {
"id": peer_id
}
return self.call("dev-sign-last-tx", payload)
def dev_slowcmd(self, msec=None):
"""
Torture test for slow commands, optional {msec}.
"""
payload = {
"subcommand": "slowcmd",
"msec": msec
}
return self.call("dev", payload)
def disconnect(self, peer_id, force=False):
"""
Disconnect from peer with {peer_id}, optional {force} even if has active channel.
"""
payload = {
"id": peer_id,
"force": force,
}
return self.call("disconnect", payload)
def feerates(self, style, urgent=None, normal=None, slow=None):
"""
Supply feerate estimates manually.
"""
payload = {
"style": style,
"urgent": urgent,
"normal": normal,
"slow": slow
}
return self.call("feerates", payload)
def fundchannel(self, node_id, amount, feerate=None, announce=True,
minconf=None, utxos=None, push_msat=None, close_to=None,
request_amt=None, compact_lease=None,
mindepth: Optional[int] = None,
reserve: Optional[str] = None,
channel_type=None):
"""
Fund channel with {id} using {amount} satoshis with feerate
of {feerate} (uses default feerate if unset).
If {announce} is False, don't send channel announcements.
Only select outputs with {minconf} confirmations.
If {utxos} is specified (as a list of 'txid:vout' strings),
fund a channel from these specifics utxos.
{close_to} is a valid Bitcoin address.
{request_amt} is the lease amount to request from the peer. Only
valid if peer is advertising a liquidity ad + supports v2 channel opens
(dual-funding)
"""
payload = {
"id": node_id,
"amount": amount,
"feerate": feerate,
"announce": announce,
"minconf": minconf,
"utxos": utxos,
"push_msat": push_msat,
"close_to": close_to,
"request_amt": request_amt,
"compact_lease": compact_lease,
"mindepth": mindepth,
"reserve": reserve,
"channel_type": channel_type,
}
return self.call("fundchannel", payload)
def fundchannel_start(self, node_id, amount, feerate=None, announce=True,
close_to=None, mindepth: Optional[int] = None, channel_type=None):
"""
Start channel funding with {id} for {amount} satoshis
with feerate of {feerate} (uses default feerate if unset).
If {announce} is False, don't send channel announcements.
Returns a Bech32 {funding_address} for an external wallet
to create a funding transaction for. Requires a call to
'fundchannel_complete' to complete channel establishment
with peer.
"""
payload = {
"id": node_id,
"amount": amount,
"feerate": feerate,
"announce": announce,
"close_to": close_to,
"mindepth": mindepth,
"channel_type": channel_type,
}
return self.call("fundchannel_start", payload)
def fundchannel_cancel(self, node_id):
"""
Cancel a 'started' fundchannel with node {id}.
"""
payload = {
"id": node_id,
}
return self.call("fundchannel_cancel", payload)
def fundchannel_complete(self, node_id, psbt):
"""
Complete channel establishment with {id}, using {psbt}.
"""
payload = {
"id": node_id,
"psbt": psbt,
}
return self.call("fundchannel_complete", payload)
def getinfo(self):
"""
Show information about this node.
"""
return self.call("getinfo")
def getlog(self, level=None):
"""
Show logs, with optional log {level} (info|unusual|debug|io).
"""
payload = {
"level": level
}
return self.call("getlog", payload)
def getpeer(self, peer_id, level=None):
"""
Show peer with {peer_id}, if {level} is set, include {log}s.
"""
payload = {
"id": peer_id,
"level": level
}
res = self.call("listpeers", payload)
return res.get("peers") and res["peers"][0] or None
def getroute(self, node_id, amount_msat, riskfactor, cltv=9, fromid=None,
fuzzpercent=None, exclude=None, maxhops=None):
"""
Show route to {id} for {amount_msat}, using {riskfactor} and optional
{cltv} (default 9). If specified search from {fromid} otherwise use
this node as source. Randomize the route with up to {fuzzpercent}
(0.0 -> 100.0, default 5.0). {exclude} is an optional array of
scid/direction or node-id to exclude. Limit the number of hops in the
route to {maxhops}.
"""
payload = {
"id": node_id,
"amount_msat": amount_msat,
"riskfactor": riskfactor,
"cltv": cltv,
"fromid": fromid,
"fuzzpercent": fuzzpercent,
"exclude": exclude,
"maxhops": maxhops
}
return self.call("getroute", payload)
def help(self, command=None):
"""
Show available commands, or just {command} if supplied.
"""
payload = {
"command": command,
}
return self.call("help", payload)
def invoice(self, amount_msat, label, description, expiry=None, fallbacks=None,
preimage=None, exposeprivatechannels=None, cltv=None, deschashonly=None):
"""
Create an invoice for {amount_msat} with {label} and {description} with
optional {expiry} seconds (default 1 week).
"""
payload = {
"amount_msat": amount_msat,
"label": label,
"description": description,
"expiry": expiry,
"fallbacks": fallbacks,
"preimage": preimage,
"exposeprivatechannels": exposeprivatechannels,
"cltv": cltv,
"deschashonly": deschashonly,
}
return self.call("invoice", payload)
def listchannels(self, short_channel_id=None, source=None, destination=None):
"""
Show all known channels or filter by optional
{short_channel_id}, {source} or {destination}.
"""
payload = {
"short_channel_id": short_channel_id,
"source": source,
"destination": destination
}
return self.call("listchannels", payload)
def listconfigs(self, config=None):
"""List this node's config.
"""
payload = {
"config": config
}
return self.call("listconfigs", payload)
def listdatastore(self, key=None):
"""
Show entries in the heirarchical datastore, or just one from one {key}root.
{key} can be a single string, or a sequence of strings.
"""
payload = {
"key": key,
}
return self.call("listdatastore", payload)
def listforwards(self, status=None, in_channel=None, out_channel=None, index=None, start=None, limit=None):
"""List all forwarded payments and their information matching
forward {status}, {in_channel} and {out_channel}.
"""
payload = {
"status": status,
"in_channel": in_channel,
"out_channel": out_channel,
"index": index,
"start": start,
"limit": limit,
}
return self.call("listforwards", payload)
def listfunds(self, spent=None):
"""
Show funds available for opening channels
or both unspent and spent funds if {spent} is True.
"""
payload = {
"spent": spent
}
return self.call("listfunds", payload)
def listtransactions(self):
"""
Show wallet history.
"""
return self.call("listtransactions")
def listinvoices(self, label=None, payment_hash=None, invstring=None, offer_id=None, index=None, start=None, limit=None):
"""Query invoices
Show invoice matching {label}, {payment_hash}, {invstring} or {offer_id}
(or all, if no filters are present).
"""
payload = {
"label": label,
"payment_hash": payment_hash,
"invstring": invstring,
"offer_id": offer_id,
"index": index,
"start": start,
"limit": limit,
}
return self.call("listinvoices", payload)
def listnodes(self, node_id=None):
"""
Show all nodes in our local network view, filter on node {id}
if provided.
"""
payload = {
"id": node_id
}
return self.call("listnodes", payload)
def listpays(self, bolt11=None, payment_hash=None, status=None, index=None, start=None, limit=None):
"""
Show outgoing payments, regarding {bolt11} or {payment_hash} if set
Can only specify one of {bolt11} or {payment_hash}. It is possible
filter the payments by {status}.
"""
assert not (bolt11 and payment_hash)
payload = {
"bolt11": bolt11,
"payment_hash": payment_hash,
"status": status,
"index": index,
"start": start,
"limit": limit,
}
return self.call("listpays", payload)