forked from DeFiCh/ain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.py
885 lines (706 loc) · 28.4 KB
/
util.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
#!/usr/bin/env python3
# Copyright (c) 2014-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
"""Helpful routines for regression testing."""
from base64 import b64encode
from binascii import unhexlify
from decimal import Decimal, ROUND_DOWN
import inspect
import json
import logging
import os
import random
import re
from subprocess import CalledProcessError
import time
import web3
from . import coverage
from .authproxy import AuthServiceProxy, JSONRPCException
from io import BytesIO
logger = logging.getLogger("TestFramework.utils")
# Assert functions
##################
def assert_fee_amount(fee, tx_size, fee_per_kB):
"""Assert the fee was in range"""
target_fee = round(tx_size * fee_per_kB / 1000, 8)
if fee < target_fee:
raise AssertionError(
"Fee of %s BTC too low! (Should be %s BTC)" % (str(fee), str(target_fee))
)
# allow the wallet's estimation to be at most 2 bytes off
if fee > (tx_size + 2) * fee_per_kB / 1000:
raise AssertionError(
"Fee of %s BTC too high! (Should be %s BTC)" % (str(fee), str(target_fee))
)
def assert_equal(thing1, thing2, *args):
if thing1 != thing2 or any(thing1 != arg for arg in args):
raise AssertionError(
"not(%s)" % " == ".join(str(arg) for arg in (thing1, thing2) + args)
)
def assert_greater_than(thing1, thing2):
if thing1 <= thing2:
raise AssertionError("%s <= %s" % (str(thing1), str(thing2)))
def assert_greater_than_or_equal(thing1, thing2):
if thing1 < thing2:
raise AssertionError("%s < %s" % (str(thing1), str(thing2)))
def assert_raises(exc, fun, *args, **kwds):
assert_raises_message(exc, None, fun, *args, **kwds)
def assert_raises_web3_error(code, message, fun, *args, **kwargs):
try:
fun(*args, **kwargs)
except ValueError as e:
assert_equal(e.args[0]["code"], code)
if message not in e.args[0]["message"]:
raise AssertionError("Expected substring not found:" + e.args[0]["message"])
except web3.exceptions.ContractLogicError as e:
assert_equal(message, e.message)
except Exception as e:
raise AssertionError("Unexpected exception raised: " + type(e).__name__)
else:
raise AssertionError("No exception raised")
def assert_raises_message(exc, message, fun, *args, **kwds):
try:
fun(*args, **kwds)
except JSONRPCException:
raise AssertionError("Use assert_raises_rpc_error() to test RPC failures")
except exc as e:
if message is not None and message not in e.error["message"]:
raise AssertionError("Expected substring not found:" + e.error["message"])
except Exception as e:
raise AssertionError("Unexpected exception raised: " + type(e).__name__)
else:
raise AssertionError("No exception raised")
def assert_raises_process_error(returncode, output, fun, *args, **kwds):
"""Execute a process and asserts the process return code and output.
Calls function `fun` with arguments `args` and `kwds`. Catches a CalledProcessError
and verifies that the return code and output are as expected. Throws AssertionError if
no CalledProcessError was raised or if the return code and output are not as expected.
Args:
returncode (int): the process return code.
output (string): [a substring of] the process output.
fun (function): the function to call. This should execute a process.
args*: positional arguments for the function.
kwds**: named arguments for the function.
"""
try:
fun(*args, **kwds)
except CalledProcessError as e:
if returncode != e.returncode:
raise AssertionError("Unexpected returncode %i" % e.returncode)
if output not in e.output:
raise AssertionError("Expected substring not found:" + e.output)
else:
raise AssertionError("No exception raised")
def assert_raises_rpc_error(code, message, fun, *args, **kwds):
"""Run an RPC and verify that a specific JSONRPC exception code and message is raised.
Calls function `fun` with arguments `args` and `kwds`. Catches a JSONRPCException
and verifies that the error code and message are as expected. Throws AssertionError if
no JSONRPCException was raised or if the error code/message are not as expected.
Args:
code (int), optional: the error code returned by the RPC call (defined
in src/rpc/protocol.h). Set to None if checking the error code is not required.
message (string), optional: [a substring of] the error string returned by the
RPC call. Set to None if checking the error string is not required.
fun (function): the function to call. This should be the name of an RPC.
args*: positional arguments for the function.
kwds**: named arguments for the function.
"""
assert try_rpc(code, message, fun, *args, **kwds), "No exception raised"
def try_rpc(code, message, fun, *args, **kwds):
"""Tries to run an rpc command.
Test against error code and message if the rpc fails.
Returns whether a JSONRPCException was raised."""
try:
fun(*args, **kwds)
except JSONRPCException as e:
# JSONRPCException was thrown as expected. Check the code and message values are correct.
if (code is not None) and (code != e.error["code"]):
err_str = str(e.error["code"]) + " (" + e.error["message"] + ")"
raise AssertionError("Unexpected JSONRPC error code: " + err_str)
if (message is not None) and (message not in e.error["message"]):
raise AssertionError(
"Expected substring (" + message + ") not found:" + e.error["message"]
)
return True
except Exception as e:
raise AssertionError("Unexpected exception raised: " + type(e).__name__)
else:
return False
def assert_is_hex_string(string):
try:
int(string, 16)
except Exception as e:
raise AssertionError(
"Couldn't interpret %r as hexadecimal; raised: %s" % (string, e)
)
def assert_is_hash_string(string, length=64):
if not isinstance(string, str):
raise AssertionError("Expected a string, got type %r" % type(string))
elif length and len(string) != length:
raise AssertionError(
"String of length %d expected; got %d" % (length, len(string))
)
elif not re.match("[abcdef0-9]+$", string):
raise AssertionError(
"String %r contains invalid characters for a hash." % string
)
def assert_array_result(object_array, to_match, expected, should_not_find=False):
"""
Pass in array of JSON objects, a dictionary with key/value pairs
to match against, and another dictionary with expected key/value
pairs.
If the should_not_find flag is true, to_match should not be found
in object_array
"""
if should_not_find:
assert_equal(expected, {})
num_matched = 0
for item in object_array:
all_match = True
for key, value in to_match.items():
if item[key] != value:
all_match = False
if not all_match:
continue
elif should_not_find:
num_matched = num_matched + 1
for key, value in expected.items():
if item[key] != value:
raise AssertionError(
"%s : expected %s=%s" % (str(item), str(key), str(value))
)
num_matched = num_matched + 1
if num_matched == 0 and not should_not_find:
raise AssertionError("No objects matched %s" % (str(to_match)))
if num_matched > 0 and should_not_find:
raise AssertionError("Objects were found %s" % (str(to_match)))
# Utility functions
###################
def check_json_precision():
"""Make sure json library being used does not lose precision converting BTC values"""
n = Decimal("20000000.00000003")
satoshis = int(json.loads(json.dumps(float(n))) * 1.0e8)
if satoshis != 2000000000000003:
raise RuntimeError("JSON encode/decode loses precision")
def almost_equal(x, y, threshold=0.0001):
return abs(x - y) < threshold
def truncate(str, decimal):
return str if not str.find(".") + 1 else str[: str.find(".") + decimal + 1]
def count_bytes(hex_string):
return len(bytearray.fromhex(hex_string))
def hex_str_to_bytes(hex_str):
return unhexlify(hex_str.encode("ascii"))
def str_to_b64str(string):
return b64encode(string.encode("utf-8")).decode("ascii")
def satoshi_round(amount):
return Decimal(amount).quantize(Decimal("0.00000001"), rounding=ROUND_DOWN)
def get_decimal_amount(amount):
account_tmp = amount.split("@")[0]
return Decimal(account_tmp)
def wait_until(predicate, *, attempts=float("inf"), timeout=float("inf"), lock=None):
if attempts == float("inf") and timeout == float("inf"):
timeout = 60
attempt = 0
time_end = time.time() + timeout
while attempt < attempts and time.time() < time_end:
if lock:
with lock:
if predicate():
return
else:
if predicate():
return
attempt += 1
time.sleep(0.05)
# Print the cause of the timeout
predicate_source = "''''\n" + inspect.getsource(predicate) + "'''"
logger.error("wait_until() failed. Predicate: {}".format(predicate_source))
if attempt >= attempts:
raise AssertionError(
"Predicate {} not true after {} attempts".format(predicate_source, attempts)
)
elif time.time() >= time_end:
raise AssertionError(
"Predicate {} not true after {} seconds".format(predicate_source, timeout)
)
raise RuntimeError("Unreachable")
# Utility function to assert value of U256 output
def int_to_eth_u256(value):
"""
Convert a non-negative integer to an Ethereum U256-compatible format.
The input value is multiplied by a fixed factor of 10^18 (1 ether in wei)
and represented as a hexadecimal string. This function validates that the
input is a non-negative integer and checks if the converted value is within
the range of U256 values (0 to 2^256 - 1). If the input is valid and within
range, it returns the corresponding U256-compatible hexadecimal representation.
Args:
value (int): The non-negative integer to convert.
Returns:
str: The U256-compatible hexadecimal representation of the input value.
Raises:
ValueError: If the input is not a non-negative integer or if the
converted value is outside the U256 range.
"""
if not isinstance(value, int) or value < 0:
raise ValueError("Value must be a non-negative integer")
max_u256_value = 2**256 - 1
factor = 10**18
converted_value = value * factor
if converted_value > max_u256_value:
raise ValueError(f"Value must be less than or equal to {max_u256_value}")
return hex(converted_value)
def hex_to_decimal(value):
"""
Convert a hexadecimal string to decimal in satoshi format.
The input value is converted to int and then divided from GWEI to sat and
again divided by COIN to get decimals.
Args:
value (str): Hexadecimal string to convert.
Returns:
Decimal: Decimal represantation of the value in satoshis
Raises:
ValueError: If the input value is equal zero.
"""
WEI = 1000000000
GWEI = 10
COIN = 100000000
if value == 0:
raise ValueError(f"Value must be non zero")
amount = int(value, 0)
gwei = Decimal(amount / GWEI)
sat = Decimal(gwei / WEI)
decimal = Decimal(sat / COIN)
return decimal
# RPC/P2P connection constants and functions
############################################
# The maximum number of nodes a single test can spawn
MAX_NODES = 12
# Don't assign rpc or p2p ports lower than this
PORT_MIN = 11000
# The number of ports to "reserve" for p2p and rpc, each
PORT_RANGE = 5000
# Don't assign rpc or p2p ports higher than this
PORT_MAX = 65000
class PortSeed:
# Must be initialized with a unique integer for each process
n = None
def get_rpc_proxy(url, node_number, timeout=None, coveragedir=None):
"""
Args:
url (str): URL of the RPC server to call
node_number (int): the node number (or id) that this calls to
Kwargs:
timeout (int): HTTP timeout in seconds
Returns:
AuthServiceProxy. convenience object for making RPC calls.
"""
proxy_kwargs = {}
if timeout is not None:
proxy_kwargs["timeout"] = timeout
proxy = AuthServiceProxy(url, **proxy_kwargs)
proxy.url = url # store URL on proxy for info
coverage_logfile = (
coverage.get_filename(coveragedir, node_number) if coveragedir else None
)
return coverage.AuthServiceProxyWrapper(proxy, coverage_logfile)
def p2p_port(n):
return rpc_port(n, 0)
def rpc_port(n, i):
# We space out n, the node index, and i the item
# Additionally, use a reasonably large enough prime to tame the port seed
# to spread out concurrent processes.
return PORT_MIN + ((n * 1000) + (i * 100) + (PortSeed.n % 9973)) % (
PORT_MAX - PORT_MIN
)
def rpc_url(datadir, n, i, chain, rpchost):
rpc_u, rpc_p = get_auth_cookie(datadir, chain)
host = "127.0.0.1"
port = rpc_port(n, i)
if rpchost:
parts = rpchost.split(":")
if len(parts) == 2:
host, port = parts
else:
host = rpchost
return "http://%s:%s@%s:%d" % (rpc_u, rpc_p, host, int(port))
# Node functions
################
def initialize_datadir(dirname, n, chain):
datadir = get_datadir_path(dirname, n)
if not os.path.isdir(datadir):
os.makedirs(datadir)
with open(os.path.join(datadir, "defi.conf"), "w", encoding="utf8") as f:
f.write("{}=1\n".format(chain))
f.write("[{}]\n".format(chain))
f.write("port=" + str(p2p_port(n)) + "\n")
f.write("rpcport=" + str(rpc_port(n, 1)) + "\n")
f.write("grpcport=" + str(rpc_port(n, 2)) + "\n") # GRPC will use two ports
f.write("ethrpcport=" + str(rpc_port(n, 3)) + "\n")
f.write("wsport=" + str(rpc_port(n, 4)) + "\n")
f.write("server=1\n")
f.write("keypool=1\n")
f.write("discover=0\n")
f.write("listenonion=0\n")
f.write("printtoconsole=0\n")
f.write("upnp=0\n")
os.makedirs(os.path.join(datadir, "stderr"), exist_ok=True)
os.makedirs(os.path.join(datadir, "stdout"), exist_ok=True)
return datadir
def get_datadir_path(dirname, n):
return os.path.join(dirname, "node" + str(n))
def append_config(datadir, options):
with open(os.path.join(datadir, "defi.conf"), "a", encoding="utf8") as f:
for option in options:
f.write(option + "\n")
def get_auth_cookie(datadir, chain):
user = None
password = None
if os.path.isfile(os.path.join(datadir, "defi.conf")):
with open(os.path.join(datadir, "defi.conf"), "r", encoding="utf8") as f:
for line in f:
if line.startswith("rpcuser="):
assert user is None # Ensure that there is only one rpcuser line
user = line.split("=")[1].strip("\n")
if line.startswith("rpcpassword="):
assert (
password is None
) # Ensure that there is only one rpcpassword line
password = line.split("=")[1].strip("\n")
try:
with open(os.path.join(datadir, chain, ".cookie"), "r", encoding="ascii") as f:
userpass = f.read()
split_userpass = userpass.split(":")
user = split_userpass[0]
password = split_userpass[1]
except OSError:
pass
if user is None or password is None:
raise ValueError("No RPC credentials")
return user, password
def get_conf_data(datadir):
if os.path.isfile(os.path.join(datadir, "defi.conf")):
with open(os.path.join(datadir, "defi.conf"), "r", encoding="utf8") as f:
return f.read()
def delete_cookie_file(datadir, chain):
"""
If a cookie file exists in the given datadir, delete it.
"""
if os.path.isfile(os.path.join(datadir, chain, ".cookie")):
logger.debug("Deleting leftover cookie file")
os.remove(os.path.join(datadir, chain, ".cookie"))
def set_node_times(nodes, t):
for node in nodes:
node.setmocktime(t)
def disconnect_nodes(from_connection, node_num):
for peer_id in [
peer["id"]
for peer in from_connection.getpeerinfo()
if "testnode%d" % node_num in peer["subver"]
]:
try:
from_connection.disconnectnode(nodeid=peer_id)
except JSONRPCException as e:
# If this node is disconnected between calculating the peer id
# and issuing the disconnect, don't worry about it.
# This avoids a race condition if we're mass-disconnecting peers.
if e.error["code"] != -29: # RPC_CLIENT_NODE_NOT_CONNECTED
raise
# wait to disconnect
wait_until(
lambda: [
peer["id"]
for peer in from_connection.getpeerinfo()
if "testnode%d" % node_num in peer["subver"]
]
== [],
timeout=5,
)
def connect_nodes(from_connection, node_num):
ip_port = "127.0.0.1:" + str(p2p_port(node_num))
from_connection.addnode(ip_port, "onetry")
# poll until version handshake complete to avoid race conditions
# with transaction relaying
wait_until(
lambda: all(peer["version"] != 0 for peer in from_connection.getpeerinfo())
)
def connect_nodes_bi(nodes, a, b):
connect_nodes(nodes[a], b)
connect_nodes(nodes[b], a)
def sync_blocks(rpc_connections, *, wait=1, timeout=60):
"""
Wait until everybody has the same tip.
sync_blocks needs to be called with an rpc_connections set that has least
one node already synced to the latest, stable tip, otherwise there's a
chance it might return before all nodes are stably synced.
"""
stop_time = time.time() + timeout
while time.time() <= stop_time:
best_hash = [x.getbestblockhash() for x in rpc_connections]
if best_hash.count(best_hash[0]) == len(rpc_connections):
return
time.sleep(wait)
raise AssertionError(
"Block sync timed out:{}".format(
"".join("\n {!r}".format(b) for b in best_hash)
)
)
def sync_mempools(rpc_connections, *, wait=1, timeout=60, flush_scheduler=True):
"""
Wait until everybody has the same transactions in their memory
pools
"""
stop_time = time.time() + timeout
while time.time() <= stop_time:
pool = [set(r.getrawmempool()) for r in rpc_connections]
if pool.count(pool[0]) == len(rpc_connections):
if flush_scheduler:
for r in rpc_connections:
r.syncwithvalidationinterfacequeue()
return
time.sleep(wait)
raise AssertionError(
"Mempool sync timed out:{}".format("".join("\n {!r}".format(m) for m in pool))
)
# Transaction/Block functions
#############################
def find_output(node, txid, amount, *, blockhash=None):
"""
Return index to output of txid with value amount
Raises exception if there is none.
"""
txdata = node.getrawtransaction(txid, 1, blockhash)
for i in range(len(txdata["vout"])):
if txdata["vout"][i]["value"] == amount:
return i
raise RuntimeError("find_output txid %s : %s not found" % (txid, str(amount)))
def gather_inputs(from_node, amount_needed, confirmations_required=1):
"""
Return a random set of unspent txouts that are enough to pay amount_needed
"""
assert confirmations_required >= 0
utxo = from_node.listunspent(confirmations_required)
random.shuffle(utxo)
inputs = []
total_in = Decimal("0.00000000")
while total_in < amount_needed and len(utxo) > 0:
t = utxo.pop()
total_in += t["amount"]
inputs.append({"txid": t["txid"], "vout": t["vout"], "address": t["address"]})
if total_in < amount_needed:
raise RuntimeError(
"Insufficient funds: need %d, have %d" % (amount_needed, total_in)
)
return (total_in, inputs)
def make_change(from_node, amount_in, amount_out, fee):
"""
Create change output(s), return them
"""
outputs = {}
amount = amount_out + fee
change = amount_in - amount
if change > amount * 2:
# Create an extra change output to break up big inputs
change_address = from_node.getnewaddress()
# Split change in two, being careful of rounding:
outputs[change_address] = Decimal(change / 2).quantize(
Decimal("0.00000001"), rounding=ROUND_DOWN
)
change = amount_in - amount - outputs[change_address]
if change > 0:
outputs[from_node.getnewaddress()] = change
return outputs
def random_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
"""
Create a random transaction.
Returns (txid, hex-encoded-transaction-data, fee)
"""
from_node = random.choice(nodes)
to_node = random.choice(nodes)
fee = min_fee + fee_increment * random.randint(0, fee_variants)
(total_in, inputs) = gather_inputs(from_node, amount + fee)
outputs = make_change(from_node, total_in, amount, fee)
outputs[to_node.getnewaddress()] = float(amount)
rawtx = from_node.createrawtransaction(inputs, outputs)
signresult = from_node.signrawtransactionwithwallet(rawtx)
txid = from_node.sendrawtransaction(signresult["hex"], 0)
return (txid, signresult["hex"], fee)
def make_utxo(node, amount, confirmed=True, scriptPubKey=None):
"""
Create a txout with a given amount and scriptPubKey that mines coins as needed.
confirmed txouts created will be confirmed in the blockchain.
"""
from .script import CScript
from .messages import COIN, CTransaction, CTxIn, COutPoint, CTxOut, ToHex
if not scriptPubKey:
scriptPubKey = CScript([1])
fee = 1 * COIN
while node.getbalance() < satoshi_round((amount + fee) / COIN):
node.generate(100)
new_addr = node.getnewaddress()
txid = node.sendtoaddress(new_addr, satoshi_round((amount + fee) / COIN))
tx1 = node.getrawtransaction(txid, 1)
txid = int(txid, 16)
i = None
for i, txout in enumerate(tx1["vout"]):
if txout["scriptPubKey"]["addresses"] == [new_addr]:
break
assert i is not None
tx2 = CTransaction()
tx2.vin = [CTxIn(COutPoint(txid, i))]
tx2.vout = [CTxOut(amount, scriptPubKey)]
tx2.rehash()
signed_tx = node.signrawtransactionwithwallet(ToHex(tx2))
txid = node.sendrawtransaction(signed_tx["hex"], 0)
# If requested, ensure txouts are confirmed.
if confirmed:
mempool_size = len(node.getrawmempool())
while mempool_size > 0:
node.generate(1)
new_size = len(node.getrawmempool())
# Error out if we have something stuck in the mempool, as this
# would likely be a bug.
assert new_size < mempool_size
mempool_size = new_size
return COutPoint(int(txid, 16), 0)
def create_confirmed_utxos(fee, node, count):
"""
Helper function to create at least "count" utxos.
Pass in a fee that is sufficient for relaying and mining new transactions.
"""
to_generate = int(0.5 * count) + 101
while to_generate > 0:
node.generate(min(25, to_generate))
to_generate -= 25
utxos = node.listunspent()
iterations = count - len(utxos)
addr1 = node.getnewaddress()
addr2 = node.getnewaddress()
if iterations <= 0:
return utxos
for i in range(iterations):
t = utxos.pop()
inputs = []
inputs.append({"txid": t["txid"], "vout": t["vout"]})
outputs = {}
send_value = t["amount"] - fee
outputs[addr1] = satoshi_round(send_value / 2)
outputs[addr2] = satoshi_round(send_value / 2)
raw_tx = node.createrawtransaction(inputs, outputs)
signed_tx = node.signrawtransactionwithwallet(raw_tx)["hex"]
node.sendrawtransaction(signed_tx)
while node.getmempoolinfo()["size"] > 0:
node.generate(1)
utxos = node.listunspent()
assert len(utxos) >= count
return utxos
def gen_return_txouts():
"""
Create a large OP_RETURN txouts that can append to a transaction to make it large (helper for
constructing large transactions).
"""
# Some pre-processing to create a bunch of OP_RETURN txouts to insert into transactions we create
# So we have big transactions (and therefore can't fit very many into each block)
# create one script_pubkey
script_pubkey = b"\x6a\x4d\x02\x00" + b"\x01" * 512 # OP_RETURN OP_PUSH2 512 bytes
# concatenate 128 txouts of above script_pubkey which we'll insert before the txout for change
txouts = []
from .messages import CTxOut
txout = CTxOut()
txout.nValue = 0
txout.scriptPubKey = script_pubkey
for k in range(128):
txouts.append(txout)
return txouts
def find_spendable_utxo(node, min_value):
"""
Get utxo with a value equal to or higher than the minimum value.
"""
for utxo in node.listunspent(query_options={"minimumAmount": min_value}):
if utxo["spendable"]:
return utxo
raise AssertionError("Unspent output equal or higher than %s not found" % min_value)
def create_address_utxo(node, address, amount):
"""
Create and send new utxo of the specified amount to address.
"""
tx = node.sendtoaddress(address, amount)
output_num = 0
for details in node.gettransaction(tx)["details"]:
if details["address"] == address:
output_num = details["vout"]
break
node.generate(1)
return tx, output_num
def create_lots_of_big_transactions(node, txouts, utxos, num, fee):
"""
Create a spend of each passed-in utxo, splicing in "txouts" to each raw transaction to make
it large. See gen_return_txouts() above.
"""
addr = node.getnewaddress()
txids = []
from .messages import CTransaction
for _ in range(num):
t = utxos.pop()
inputs = [{"txid": t["txid"], "vout": t["vout"]}]
outputs = {}
change = t["amount"] - fee
outputs[addr] = satoshi_round(change)
rawtx = node.createrawtransaction(inputs, outputs)
tx = CTransaction()
tx.deserialize(BytesIO(hex_str_to_bytes(rawtx)))
for txout in txouts:
tx.vout.append(txout)
newtx = tx.serialize().hex()
signresult = node.signrawtransactionwithwallet(newtx, None, "NONE")
txid = node.sendrawtransaction(signresult["hex"], 0)
txids.append(txid)
return txids
def mine_large_block(node, utxos=None):
"""
Generate a ~1M transaction, and 16 of them will be close to the 16MB block limit.
"""
num = 16 # old value 14
from .messages import CTxOut
from .script import CScript, OP_RETURN, OP_NOP
big_script = CScript([OP_RETURN] + [OP_NOP] * 980000)
big_txout = CTxOut(0, big_script)
utxos = utxos if utxos is not None else []
if len(utxos) < num:
utxos.clear()
utxos.extend(node.listunspent())
fee = 1000 * node.getnetworkinfo()["relayfee"]
create_lots_of_big_transactions(node, [big_txout], utxos, num, fee=fee)
node.generate(1)
def find_vout_for_address(node, txid, addr):
"""
Locate the vout index of the given transaction sending to the
given address. Raises runtime error exception if not found.
"""
tx = node.getrawtransaction(txid, True)
for i in range(len(tx["vout"])):
if any([addr == a for a in tx["vout"][i]["scriptPubKey"]["addresses"]]):
return i
raise RuntimeError("Vout not found for address: txid=%s, addr=%s" % (txid, addr))
# Token functions
#############################
def get_id_token(node, symbol):
"""
Get the token ID
"""
list_tokens = node.listtokens()
for idx, token in list_tokens.items():
if token["symbol"] == symbol:
return str(idx)
def token_index_in_account(account, symbol):
"""
Get token id in a given account
"""
for id in range(len(account)):
if symbol in account[id]:
return id
return -1
# Web3 functions
#############################
def get_solc_artifact_path(contract: str, file_name: str) -> str:
return f"{os.path.dirname(__file__)}/../../../build/lib/target/sol_artifacts/{contract}/{file_name}"