forked from ElementsProject/lightning
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.py
More file actions
1946 lines (1621 loc) · 72.5 KB
/
utils.py
File metadata and controls
1946 lines (1621 loc) · 72.5 KB
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
from bitcoin.core import COIN # type: ignore
from bitcoin.rpc import RawProxy as BitcoinProxy # type: ignore
from bitcoin.rpc import JSONRPCError
from contextlib import contextmanager
from pathlib import Path
from pyln.client import RpcError
from pyln.testing.btcproxy import BitcoinRpcProxy
from pyln.testing.gossip import GossipStore
from collections import OrderedDict
from decimal import Decimal
from pyln.client import LightningRpc
from pyln.client import Millisatoshi
from pyln.client import NodeVersion
import ephemeral_port_reserve # type: ignore
import json
import logging
import lzma
import math
import mnemonic
import os
import random
import re
import shutil
import sqlite3
import string
import struct
import subprocess
import sys
import threading
import time
import warnings
BITCOIND_CONFIG = {
"regtest": 1,
"rpcuser": "rpcuser",
"rpcpassword": "rpcpass",
"fallbackfee": Decimal(1000) / COIN,
}
LIGHTNINGD_CONFIG = OrderedDict({
"log-level": "trace",
"cltv-delta": 6,
"cltv-final": 5,
"watchtime-blocks": 5,
"rescan": 1,
'disable-dns': None,
})
FUNDAMOUNT = 10**6
def env(name, default=None):
"""Access to environment variables
Allows access to environment variables, falling back to config.vars (part
of Core Lightning's `./configure` output), and finally falling back to a
default value.
"""
fname = 'config.vars'
if os.path.exists(fname):
with open(fname, 'r') as f:
lines = f.readlines()
config = dict([(line.rstrip().split('=', 1)) for line in lines])
else:
config = {}
if name in os.environ:
return os.environ[name]
elif name in config:
return config[name]
else:
return default
VALGRIND = env("VALGRIND") == "1"
TEST_NETWORK = env("TEST_NETWORK", 'regtest')
TEST_DEBUG = env("TEST_DEBUG", "0") == "1"
SLOW_MACHINE = env("SLOW_MACHINE", "0") == "1"
DEPRECATED_APIS = env("DEPRECATED_APIS", "0") == "1"
TIMEOUT = int(env("TIMEOUT", 180 if SLOW_MACHINE else 60))
EXPERIMENTAL_DUAL_FUND = env("EXPERIMENTAL_DUAL_FUND", "0") == "1"
GENERATE_EXAMPLES = env("GENERATE_EXAMPLES", "0") == "1"
RUST = env("RUST", "0") == "1"
def wait_for(success, timeout=TIMEOUT):
start_time = time.time()
interval = 0.25
while not success():
time_left = start_time + timeout - time.time()
if time_left <= 0:
raise ValueError("Timeout while waiting for {}".format(success))
time.sleep(min(interval, time_left))
interval *= 2
if interval > 5:
interval = 5
def write_config(filename, opts, regtest_opts=None, section_name='regtest'):
with open(filename, 'w') as f:
for k, v in opts.items():
f.write("{}={}\n".format(k, v))
if regtest_opts:
f.write("[{}]\n".format(section_name))
for k, v in regtest_opts.items():
f.write("{}={}\n".format(k, v))
def scid_to_int(scid):
"""Convert a 1x2x3 scid to a raw integer"""
blocknum, txnum, outnum = scid.split("x")
# BOLT #7:
# ## Definition of `short_channel_id`
#
# The `short_channel_id` is the unique description of the funding transaction.
# It is constructed as follows:
# 1. the most significant 3 bytes: indicating the block height
# 2. the next 3 bytes: indicating the transaction index within the block
# 3. the least significant 2 bytes: indicating the output index that pays to the
# channel.
return (int(blocknum) << 40) | (int(txnum) << 16) | int(outnum)
def only_one(arr):
"""Many JSON RPC calls return an array; often we only expect a single entry
"""
assert len(arr) == 1
return arr[0]
def sync_blockheight(bitcoind, nodes):
height = bitcoind.rpc.getblockchaininfo()['blocks']
for n in nodes:
wait_for(lambda: n.rpc.getinfo()['blockheight'] == height)
def mine_funding_to_announce(bitcoind, nodes, num_blocks=5, wait_for_mempool=0):
"""Mine blocks so a channel can be announced (5, if it's already
mined), but make sure we don't leave nodes behind who will reject the
announcement. Not needed if there are only two nodes.
"""
bitcoind.generate_block(num_blocks - 1, wait_for_mempool)
sync_blockheight(bitcoind, nodes)
bitcoind.generate_block(1)
def wait_channel_quiescent(n1, n2):
wait_for(lambda: only_one(n1.rpc.listpeerchannels(n2.info['id'])['channels'])['htlcs'] == [])
wait_for(lambda: only_one(n2.rpc.listpeerchannels(n1.info['id'])['channels'])['htlcs'] == [])
def get_tx_p2wsh_outnum(bitcoind, tx, amount):
"""Get output number of this tx which is p2wsh of amount"""
decoded = bitcoind.rpc.decoderawtransaction(tx, True)
for out in decoded['vout']:
if out['scriptPubKey']['type'] == 'witness_v0_scripthash':
if out['value'] == Decimal(amount) / 10**8:
return out['n']
return None
unused_port_lock = threading.Lock()
unused_port_set = set()
def reserve_unused_port():
"""Get an unused port: avoids handing out the same port unless it's been
returned"""
with unused_port_lock:
while True:
port = ephemeral_port_reserve.reserve()
if port not in unused_port_set:
break
unused_port_set.add(port)
return port
def drop_unused_port(port):
unused_port_set.remove(port)
class TailableProc(object):
"""A monitorable process that we can start, stop and tail.
This is the base class for the daemons. It allows us to directly
tail the processes and react to their output.
"""
def __init__(self, outputDir, verbose=True):
self.logs = []
self.env = os.environ.copy()
# Add coverage support: inject LLVM_PROFILE_FILE if CLN_COVERAGE_DIR is set
if os.getenv('CLN_COVERAGE_DIR'):
coverage_dir = os.getenv('CLN_COVERAGE_DIR')
# Organize profraw files by test name for per-test coverage analysis
test_name = os.getenv('CLN_TEST_NAME')
if test_name:
test_coverage_dir = os.path.join(coverage_dir, test_name)
os.makedirs(test_coverage_dir, exist_ok=True)
profraw_path = test_coverage_dir
else:
os.makedirs(coverage_dir, exist_ok=True)
profraw_path = coverage_dir
# %p=PID, %m=binary signature prevents collisions across parallel processes
# Note: We don't use %c (continuous mode) as it causes "__llvm_profile_counter_bias"
# errors with our multi-binary setup. Instead, we validate and filter corrupt files
# during collection (see contrib/coverage/collect-coverage.sh)
self.env['LLVM_PROFILE_FILE'] = os.path.join(
profraw_path, '%p-%m.profraw'
)
self.proc = None
self.outputDir = outputDir
if not os.path.exists(outputDir):
os.makedirs(outputDir)
# Create and open them.
self.stdout_filename = os.path.join(outputDir, "log")
self.stderr_filename = os.path.join(outputDir, "errlog")
self.stdout_write = open(self.stdout_filename, "wt")
self.stderr_write = open(self.stderr_filename, "wt")
self.stdout_read = open(self.stdout_filename, "rt")
self.stderr_read = open(self.stderr_filename, "rt")
self.logsearch_start = 0
self.err_logs = []
self.prefix = ""
# Should we be logging lines we read from stdout?
self.verbose = verbose
# A filter function that'll tell us whether to filter out the line (not
# pass it to the log matcher and not print it to stdout).
self.log_filter = lambda line: False
def start(self, stdin=None, stdout_redir=True, stderr_redir=True):
"""Start the underlying process and start monitoring it. If
stdout_redir is false, you have to make sure logs go into
outputDir/log
"""
logging.debug("Starting '%s'", " ".join(self.cmd_line))
if stdout_redir:
stdout = self.stdout_write
else:
stdout = None
if stderr_redir:
stderr = self.stderr_write
self.stderr_redir = True
else:
stderr = None
self.stderr_redir = False
self.proc = subprocess.Popen(self.cmd_line,
stdin=stdin,
stdout=stdout,
stderr=stderr,
env=self.env)
def stop(self, timeout=10):
self.proc.terminate()
# Now give it some time to react to the signal
rc = self.proc.wait(timeout)
if rc is None:
self.proc.kill()
self.proc.wait()
return self.proc.returncode
def kill(self):
"""Kill process without giving it warning."""
self.proc.kill()
self.proc.wait()
def cleanup_files(self):
"""Ensure files are closed."""
for f in ["stdout_write", "stderr_write", "stdout_read", "stderr_read"]:
try:
getattr(self, f).close()
except Exception:
pass
def readlines_wait_for_end(self, f, timeout=TIMEOUT):
"""Read all complete lines from file object `f`.
If the last line is incomplete (no trailing newline), wait briefly
for it to complete before returning.
Returns list of lines including trailing newline.
"""
lines = []
cur = ''
start = time.time()
while True:
line = f.readline()
if not line:
if cur != '':
if time.time() - start > timeout:
raise TimeoutError(f"Incomplete line never finished: {cur}")
time.sleep(0.01)
continue
return lines
cur += line
if cur.endswith('\n'):
lines.append(cur)
cur = ''
def logs_catchup(self):
"""Save the latest stdout / stderr contents; return true if we got anything.
"""
new_stdout = self.readlines_wait_for_end(self.stdout_read)
if self.verbose:
for line in new_stdout:
sys.stdout.write("{}: {}".format(self.prefix, line))
self.logs += [l.rstrip() for l in new_stdout]
new_stderr = self.readlines_wait_for_end(self.stderr_read)
if self.verbose:
for line in new_stderr:
sys.stderr.write("{}-stderr: {}".format(self.prefix, line))
self.err_logs += [l.rstrip() for l in new_stderr]
return len(new_stdout) > 0 or len(new_stderr) > 0
def is_in_log(self, regex, start=0):
"""Look for `regex` in the logs."""
self.logs_catchup()
ex = re.compile(regex)
for l in self.logs[start:]:
if ex.search(l):
logging.debug("Found '%s' in logs", regex)
return l
logging.debug("Did not find '%s' in logs", regex)
return None
def is_in_stderr(self, regex):
"""Look for `regex` in stderr."""
assert self.stderr_redir
self.logs_catchup()
ex = re.compile(regex)
for l in self.err_logs:
if ex.search(l):
logging.debug("Found '%s' in stderr", regex)
return l
logging.debug("Did not find '%s' in stderr", regex)
return None
def wait_for_logs(self, regexs, timeout=TIMEOUT):
"""Look for `regexs` in the logs.
The logs contain tailed stdout of the process. We look for each regex
in `regexs`, starting from `logsearch_start` which normally is the
position of the last found entry of a previous wait-for logs call.
The ordering inside `regexs` doesn't matter.
We fail if the timeout is exceeded or if the underlying process
exits before all the `regexs` were found.
If timeout is None, no time-out is applied.
"""
logging.debug("Waiting for {} in the logs".format(regexs))
exs = [re.compile(r) for r in regexs]
start_time = time.time()
while True:
if self.logsearch_start >= len(self.logs):
if not self.logs_catchup():
time.sleep(0.25)
if timeout is not None and time.time() > start_time + timeout:
print("Time-out: can't find {} in logs".format(exs))
for r in exs:
if self.is_in_log(r):
print("({} was previously in logs!)".format(r))
raise TimeoutError('Unable to find "{}" in logs.'.format(exs))
continue
line = self.logs[self.logsearch_start]
self.logsearch_start += 1
for r in exs.copy():
if r.search(line):
logging.debug("Found '%s' in logs", r)
exs.remove(r)
if len(exs) == 0:
return line
# Don't match same line with different regexs!
break
def wait_for_log(self, regex, timeout=TIMEOUT):
"""Look for `regex` in the logs.
Convenience wrapper for the common case of only seeking a single entry.
"""
return self.wait_for_logs([regex], timeout)
class SimpleBitcoinProxy:
"""Wrapper for BitcoinProxy to reconnect.
Long wait times between calls to the Bitcoin RPC could result in
`bitcoind` closing the connection, so here we just create
throwaway connections. This is easier than to reach into the RPC
library to close, reopen and reauth upon failure.
"""
def __init__(self, btc_conf_file, timeout=TIMEOUT, *args, **kwargs):
self.__btc_conf_file__ = btc_conf_file
self.__timeout__ = timeout
def __getattr__(self, name):
if name.startswith('__') and name.endswith('__'):
# Python internal stuff
raise AttributeError
# Create a callable to do the actual call
proxy = BitcoinProxy(btc_conf_file=self.__btc_conf_file__,
timeout=self.__timeout__)
def f(*args):
logging.debug("Calling {name} with arguments {args}".format(
name=name,
args=args
))
res = proxy._call(name, *args)
logging.debug("Result for {name} call: {res}".format(
name=name,
res=res,
))
return res
# Make debuggers show <function bitcoin.rpc.name> rather than <function
# bitcoin.rpc.<lambda>>
f.__name__ = name
return f
class BitcoinD(TailableProc):
def __init__(self, bitcoin_dir="/tmp/bitcoind-test", rpcport=None):
TailableProc.__init__(self, bitcoin_dir, verbose=False)
if rpcport is None:
self.reserved_rpcport = reserve_unused_port()
rpcport = self.reserved_rpcport
else:
self.reserved_rpcport = None
self.bitcoin_dir = bitcoin_dir
self.rpcport = rpcport
self.prefix = 'bitcoind'
self.canned_blocks = None
regtestdir = os.path.join(bitcoin_dir, 'regtest')
if not os.path.exists(regtestdir):
os.makedirs(regtestdir)
self.cmd_line = [
'bitcoind',
'-datadir={}'.format(bitcoin_dir),
'-printtoconsole',
'-server',
'-logtimestamps',
'-nolisten',
'-txindex',
'-nowallet',
'-addresstype=bech32',
'-debug=mempool',
'-debug=mempoolrej',
'-debug=rpc',
'-debug=validation',
'-rpcthreads=20',
]
# For up to and including 0.16.1, this needs to be in main section.
BITCOIND_CONFIG['rpcport'] = rpcport
# For after 0.16.1 (eg. 3f398d7a17f136cd4a67998406ca41a124ae2966), this
# needs its own [regtest] section.
BITCOIND_REGTEST = {'rpcport': rpcport}
self.conf_file = os.path.join(bitcoin_dir, 'bitcoin.conf')
write_config(self.conf_file, BITCOIND_CONFIG, BITCOIND_REGTEST)
self.rpc = SimpleBitcoinProxy(btc_conf_file=self.conf_file)
self.proxies = []
def __del__(self):
if self.reserved_rpcport is not None:
drop_unused_port(self.reserved_rpcport)
def start(self, wallet_file=None):
TailableProc.start(self)
self.wait_for_log("Done loading", timeout=TIMEOUT)
logging.info("BitcoinD started")
if wallet_file:
self.rpc.restorewallet("lightningd-tests", wallet_file)
else:
try:
self.rpc.createwallet("lightningd-tests")
except JSONRPCError:
self.rpc.loadwallet("lightningd-tests")
def stop(self):
for p in self.proxies:
p.stop()
self.rpc.stop()
return TailableProc.stop(self)
def get_proxy(self):
proxy = BitcoinRpcProxy(self)
self.proxies.append(proxy)
proxy.start()
return proxy
def set_canned_blocks(self, blocks):
"""Set blocks as an array of blocks to "generate", or None to reset"""
self.canned_blocks = blocks
# wait_for_mempool can be used to wait for the mempool before generating blocks:
# True := wait for at least 1 transation
# int > 0 := wait for at least N transactions
# 'tx_id' := wait for one transaction id given as a string
# ['tx_id1', 'tx_id2'] := wait until all of the specified transaction IDs
def generate_block(self, numblocks=1, wait_for_mempool=0, to_addr=None, needfeerate=None):
if wait_for_mempool:
if isinstance(wait_for_mempool, str):
wait_for_mempool = [wait_for_mempool]
if isinstance(wait_for_mempool, list):
wait_for(lambda: all(txid in self.rpc.getrawmempool() for txid in wait_for_mempool))
else:
wait_for(lambda: len(self.rpc.getrawmempool()) >= wait_for_mempool)
# Use canned blocks if we have them (fails if we run out!).
if self.canned_blocks is not None:
ret = []
while numblocks > 0:
self.rpc.submitblock(self.canned_blocks[0])
ret.append(self.rpc.getbestblockhash())
numblocks -= 1
del self.canned_blocks[0]
return ret
mempool = self.rpc.getrawmempool(True)
logging.debug("Generating {numblocks}, confirming {lenmempool} transactions: {mempool}".format(
numblocks=numblocks,
mempool=mempool,
lenmempool=len(mempool),
))
# As of 0.16, generate() is removed; use generatetoaddress.
if to_addr is None:
to_addr = self.rpc.getnewaddress()
# We assume all-or-nothing.
if needfeerate is not None:
assert numblocks == 1
# If any tx including ancestors is above the given feerate, mine all.
for txid, details in mempool.items():
feerate = float(details['fees']['ancestor']) * 100_000_000 / (float(details['ancestorsize']) * 4 / 1000)
if feerate >= needfeerate:
return self.rpc.generatetoaddress(numblocks, to_addr)
else:
print(f"Feerate {feerate} for {txid} below {needfeerate}")
# Otherwise, mine none.
return self.rpc.generateblock(to_addr, [])
return self.rpc.generatetoaddress(numblocks, to_addr)
def send_and_mine_block(self, addr, sats):
"""Sometimes we want the txid. We assume it's the first tx for canned blocks"""
if self.canned_blocks:
self.generate_block(1)
# Find which non-coinbase txs sent to this address: return txid
for txid in self.rpc.getblock(self.rpc.getbestblockhash())['tx'][1:]:
for out in self.rpc.getrawtransaction(txid, 1)['vout']:
if out['scriptPubKey'].get('address') == addr:
return txid
assert False, f"No address {addr} in block {self.rpc.getblock(self.rpc.getbestblockhash())}"
txid = self.rpc.sendtoaddress(addr, sats / 10**8)
self.generate_block(1)
return txid
def simple_reorg(self, height, shift=0):
"""
Reorganize chain by creating a fork at height=[height] and re-mine all mempool
transactions into [height + shift], where shift >= 0. Returns hashes of generated
blocks.
Note that tx's that become invalid at [height] (because coin maturity, locktime
etc.) are removed from mempool. The length of the new chain will be original + 1
OR original + [shift], whichever is larger.
For example: to push tx's backward from height h1 to h2 < h1, use [height]=h2.
Or to change the txindex of tx's at height h1:
1. A block at height h2 < h1 should contain a non-coinbase tx that can be pulled
forward to h1.
2. Set [height]=h2 and [shift]= h1-h2
"""
assert self.canned_blocks is None
hashes = []
fee_delta = 1000000
orig_len = self.rpc.getblockcount()
old_hash = self.rpc.getblockhash(height)
final_len = height + shift if height + shift > orig_len else 1 + orig_len
# TODO: raise error for insane args?
self.rpc.invalidateblock(old_hash)
self.wait_for_log(r'InvalidChainFound: invalid block=.* height={}'.format(height))
memp = self.rpc.getrawmempool()
if shift == 0:
hashes += self.generate_block(1 + final_len - height)
else:
for txid in memp:
# lower priority (to effective feerate=0) so they are not mined
self.rpc.prioritisetransaction(txid, None, -fee_delta)
hashes += self.generate_block(shift)
for txid in memp:
# restore priority so they are mined
self.rpc.prioritisetransaction(txid, None, fee_delta)
hashes += self.generate_block(1 + final_len - (height + shift))
self.wait_for_log(r'UpdateTip: new best=.* height={}'.format(final_len))
return hashes
def getnewaddress(self):
return self.rpc.getnewaddress()
def save_blocks(self):
"""Bundle up blocks into an array, for restore_blocks"""
blocks = []
numblocks = self.rpc.getblockcount()
for bnum in range(1, numblocks + 1):
bhash = self.rpc.getblockhash(bnum)
blocks.append(self.rpc.getblock(bhash, False))
return blocks
def restore_blocks(self, blocks):
"""Restore blocks from an array"""
for b in blocks:
self.rpc.submitblock(b)
class ElementsD(BitcoinD):
def __init__(self, bitcoin_dir="/tmp/bitcoind-test", rpcport=None):
config = BITCOIND_CONFIG.copy()
if 'regtest' in config:
del config['regtest']
config['chain'] = 'liquid-regtest'
BitcoinD.__init__(self, bitcoin_dir, rpcport)
self.cmd_line = [
'elementsd',
'-datadir={}'.format(bitcoin_dir),
'-printtoconsole',
'-server',
'-logtimestamps',
'-nolisten',
'-nowallet',
'-validatepegin=0',
'-con_blocksubsidy=5000000000',
'-acceptnonstdtxn=1', # FIXME Issues such as dust limit interacting with anchors
]
conf_file = os.path.join(bitcoin_dir, 'elements.conf')
config['rpcport'] = self.rpcport
BITCOIND_REGTEST = {'rpcport': self.rpcport}
write_config(conf_file, config, BITCOIND_REGTEST, section_name='liquid-regtest')
self.conf_file = conf_file
self.rpc = SimpleBitcoinProxy(btc_conf_file=self.conf_file)
self.prefix = 'elementsd'
def getnewaddress(self):
"""Need to get an address and then make it unconfidential
"""
addr = self.rpc.getnewaddress()
info = self.rpc.getaddressinfo(addr)
return info['unconfidential']
def mnemonic_from_seed(seed):
m = mnemonic.Mnemonic('english')
mnem = m.to_mnemonic(seed)
if not m.check(mnem):
raise RuntimeError("Generated mnemonic failed BIP39 validation (unexpected).")
return mnem
class LightningD(TailableProc):
def __init__(
self,
lightning_dir,
bitcoindproxy,
port=9735,
random_hsm=False,
node_id=0,
executable=None,
old_hsmsecret=None,
):
# We handle our own version of verbose, below.
TailableProc.__init__(self, lightning_dir, verbose=False)
self.executable = "lightningd" if executable is None else executable
self.lightning_dir = lightning_dir
self.port = port
self.cmd_prefix = []
self.rpcproxy = bitcoindproxy
self.env['CLN_PLUGIN_LOG'] = "cln_plugin=trace,cln_rpc=trace,cln_grpc=trace,debug"
self.opts = LIGHTNINGD_CONFIG.copy()
# Query the version of the cln-binary
cln_version_proc = subprocess.check_output([self.executable, "--version"])
self.cln_version = NodeVersion(cln_version_proc.decode('ascii').strip())
if self.cln_version <= "v24.02.2":
self.opts['log-level'] = "debug"
opts = {
'lightning-dir': lightning_dir,
'addr': '127.0.0.1:{}'.format(port),
'allow-deprecated-apis': '{}'.format("true" if DEPRECATED_APIS
else "false"),
'network': TEST_NETWORK,
'ignore-fee-limits': 'false',
'bitcoin-rpcuser': BITCOIND_CONFIG['rpcuser'],
'bitcoin-rpcpassword': BITCOIND_CONFIG['rpcpassword'],
# Make sure we don't touch any existing config files in the user's $HOME
'bitcoin-datadir': lightning_dir,
}
for k, v in opts.items():
self.opts[k] = v
if not os.path.exists(os.path.join(lightning_dir, TEST_NETWORK)):
os.makedirs(os.path.join(lightning_dir, TEST_NETWORK))
# Default: use newfangled hsm_secret, except old versions.
if old_hsmsecret is None:
# BIP 39 secrets were only added in v25.12.
old_hsmsecret = (self.cln_version < "v25.12")
if not random_hsm:
# Last 32-bytes of final part of dir -> seed.
seed = (bytes(re.search('([^/]+)/*$', lightning_dir).group(1), encoding='utf-8') + bytes(32))[:32]
# Modern style is 32 zeroes then a 12-word mnemonic phrase.
if not old_hsmsecret:
# Use first 16 bytes (128 bits) for 12-word mnemonic
entropy_128 = seed[:16]
mnemonic_phrase = mnemonic_from_seed(entropy_128)
seed = bytes(32) + bytes(mnemonic_phrase, encoding='utf-8')
with open(os.path.join(lightning_dir, TEST_NETWORK, 'hsm_secret'), 'wb') as f:
f.write(seed)
self.opts['dev-fast-gossip'] = None
self.opts['dev-bitcoind-poll'] = 1
self.prefix = 'lightningd-%d' % (node_id)
# Log to stdout so we see it in failure cases, and log file for TailableProc.
self.opts['log-file'] = ['-', os.path.join(lightning_dir, "log")]
self.opts['log-prefix'] = self.prefix + ' '
# In case you want specific ordering!
self.early_opts = []
# Before this we had a developer build option.
if self.cln_version >= "v23.11":
self.early_opts.append('--developer')
def cleanup(self):
# To force blackhole to exit, disconnect file must be truncated!
if 'dev-disconnect' in self.opts:
with open(self.opts['dev-disconnect'], "w") as f:
f.truncate()
@property
def cmd_line(self):
opts = []
for k, v in self.opts.items():
if v is None:
opts.append("--{}".format(k))
elif isinstance(v, list):
for i in v:
opts.append("--{}={}".format(k, i))
else:
opts.append("--{}={}".format(k, v))
return self.cmd_prefix + [self.executable] + self.early_opts + opts
def start(self, stdin=None, wait_for_initialized=True, stderr_redir=False):
self.opts['bitcoin-rpcport'] = self.rpcproxy.rpcport
TailableProc.start(self, stdin, stdout_redir=False, stderr_redir=stderr_redir)
if wait_for_initialized:
self.wait_for_log("Server started with public key")
logging.info("LightningD started")
def wait(self, timeout=TIMEOUT):
"""Wait for the daemon to stop for up to timeout seconds
Returns the returncode of the process, None if the process did
not return before the timeout triggers.
"""
self.proc.wait(timeout)
return self.proc.returncode
class PrettyPrintingLightningRpc(LightningRpc):
"""A version of the LightningRpc that pretty-prints calls and results.
Useful when debugging based on logs, and less painful to the
eyes. It has some overhead since we re-serialize the request and
result to json in order to pretty print it.
Also validates (optional) schemas for us.
"""
def __init__(self, socket_path, executor=None, logger=logging,
jsonschemas={}):
super().__init__(
socket_path,
executor,
logger,
)
self.jsonschemas = jsonschemas
self.check_request_schemas = True
def call(self, method, payload=None, cmdprefix=None, filter=None):
id = self.get_json_id(method, cmdprefix)
schemas = self.jsonschemas.get(method)
self.logger.debug(json.dumps({
"id": id,
"method": method,
"params": payload,
"filter": filter,
}, indent=2))
# We only check payloads which are dicts, which is what we
# usually use: there are some cases which tests [] params,
# which we ignore.
if schemas and schemas[0] and isinstance(payload, dict) and self.check_request_schemas:
# fields which are None are explicitly removed, so do that now
testpayload = {}
for k, v in payload.items():
if v is not None:
testpayload[k] = v
schemas[0].validate(testpayload)
if method != 'check':
if isinstance(payload, dict):
checkpayload = payload.copy()
checkpayload['command_to_check'] = method
elif payload is None:
checkpayload = [method]
else:
checkpayload = [method] + list(payload)
# This can fail, that's fine! But causes lightningd to check
# that we don't access db.
try:
LightningRpc.call(self, 'check', checkpayload)
except ValueError:
pass
res = LightningRpc.call(self, method, payload, cmdprefix, filter)
self.logger.debug(json.dumps({
"id": id,
"result": res
}, indent=2))
# FIXME: if filter set, just remove "required" from schemas?
if schemas and schemas[1] and filter is None and self._filter is None:
schemas[1].validate(res)
return res
class LightningNode(object):
def __init__(self, node_id, lightning_dir, bitcoind, executor, may_fail=False,
may_reconnect=False,
broken_log=None,
allow_warning=False,
allow_bad_gossip=False,
db=None, port=None, grpc_port=None, disconnect=None, random_hsm=None, options=None,
jsonschemas={},
valgrind_plugins=True,
executable=None,
bad_notifications=False,
old_hsmsecret=None,
**kwargs):
self.bitcoin = bitcoind
self.executor = executor
self.may_fail = may_fail
self.may_reconnect = may_reconnect
self.bad_notifications = bad_notifications
self.broken_log = broken_log
self.allow_bad_gossip = allow_bad_gossip
self.allow_warning = allow_warning
self.db = db
self.lightning_dir = Path(lightning_dir)
# Assume successful exit
self.rc = 0
# Ensure we have an RPC we can use to talk to the node
self._create_rpc(jsonschemas)
self.gossip_store = GossipStore(Path(lightning_dir, TEST_NETWORK, "gossip_store"))
self.daemon = LightningD(
lightning_dir, bitcoindproxy=bitcoind.get_proxy(),
port=port, random_hsm=random_hsm, node_id=node_id,
executable=executable,
old_hsmsecret=old_hsmsecret,
)
self.cln_version = self.daemon.cln_version
self.disconnect = disconnect
if self.disconnect:
self.daemon.opts["dev-disconnect"] = os.path.join(lightning_dir, TEST_NETWORK, "dev-disconnect")
# Actual population of that file occurs at start.
# Various developer options let us be more aggressive
self.daemon.opts["dev-fail-on-subdaemon-fail"] = None
# Don't run --version on every subdaemon if we're valgrinding and slow.
if SLOW_MACHINE and VALGRIND:
self.daemon.opts["dev-no-version-checks"] = None
dbgvar = os.getenv("DEBUG_SUBD")
if dbgvar and ':' in dbgvar:
path = dbgvar.split(':')[0]
if lightning_dir.endswith(path + '/'):
dbgvar = dbgvar.split(':')[-1]
else:
dbgvar = None
if dbgvar:
self.daemon.opts["dev-debugger"] = dbgvar
if os.getenv("DEBUG_LIGHTNINGD"):
self.daemon.opts["dev-debug-self"] = None
if VALGRIND:
self.daemon.env["LIGHTNINGD_DEV_NO_BACKTRACE"] = "1"
self.daemon.opts["dev-no-plugin-checksum"] = None
else:
# Under valgrind, scanning can access uninitialized mem.
self.daemon.env["LIGHTNINGD_DEV_MEMLEAK"] = "1"
if not may_reconnect:
self.daemon.opts["dev-no-reconnect"] = None
if EXPERIMENTAL_DUAL_FUND:
self.daemon.opts["experimental-dual-fund"] = None
# Avoid test flakes cause by this option unless explicitly set.
if self.cln_version >= "v24.11":
self.daemon.opts.update({"autoconnect-seeker-peers": 0})
jsondir = Path(lightning_dir) / "plugin-io"
jsondir.mkdir()
if self.cln_version >= "v25.09":
self.daemon.opts['dev-save-plugin-io'] = jsondir
if options is not None:
self.daemon.opts.update(options)
dsn = db.get_dsn()
if dsn is not None:
self.daemon.opts['wallet'] = dsn
if VALGRIND:
trace_skip_pattern = '*python*,*bitcoin-cli*,*elements-cli*,*cln-grpc*,*clnrest*,*wss-proxy*,*cln-bip353*,*reckless,*cln-currencyrate*'
if not valgrind_plugins:
trace_skip_pattern += ',*plugins*'
self.daemon.cmd_prefix = [
'valgrind',
'-q',
'--trace-children=yes',
'--trace-children-skip={}'.format(trace_skip_pattern),
'--error-exitcode=7',
'--log-file={}/valgrind-errors.%p'.format(self.daemon.lightning_dir)
]
# Reduce precision of errors, speeding startup and reducing memory greatly:
if SLOW_MACHINE:
self.daemon.cmd_prefix += ['--read-inline-info=no']
if self.daemon.opts.get('disable-plugin') == 'cln-grpc' or env('RUST') == '0':
self.grpc_port = None
else:
if grpc_port:
self.daemon.opts['grpc-port'] = grpc_port
self.grpc_port = grpc_port or 9736