Skip to content

Commit 64a4483

Browse files
author
MarcoFalke
committed
Merge bitcoin/bitcoin#24496: test: refactor: use random.sample for choosing random keys in wallet_taproot.py
31846b0 test: refactor: use `random.sample` for choosing random keys in wallet_taproot.py (Sebastian Falbesoner) Pull request description: The Python3 standard library method `random.sample` has the exact same functionality as the helper method `rand_keys(...)` (that is, random sampling without replacement) on a generic set or sequence, i.e. we can simply replace it. See https://docs.python.org/3/library/random.html#random.sample Note that this is also safer: in case that the sample size `k` is larger than the population count, `random.sample` throws an error: ``` $ python3 Python 3.8.12 (default, Sep 26 2021, 13:12:50) [Clang 11.1.0 ] on openbsd7 Type "help", "copyright", "credits" or "license" for more information. >>> import random >>> random.sample([23, 42], 3) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.8/random.py", line 363, in sample raise ValueError("Sample larger than population or is negative") ValueError: Sample larger than population or is negative ``` while the custom method would get stuck in an endless loop. ACKs for top commit: shaavan: Code Review ACK 31846b0 Tree-SHA512: d9bd7f8128e43401a5b0388e48ba838155b21db5b4b6ba95c91285880788bc3917cb656b74bbe2d97faf7b44862d20b0899dc3c56aa48b9d2b33b50e37d089f6
2 parents c9ed992 + 31846b0 commit 64a4483

File tree

1 file changed

+1
-14
lines changed

1 file changed

+1
-14
lines changed

test/functional/wallet_taproot.py

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -207,19 +207,6 @@ def setup_network(self):
207207
def init_wallet(self, *, node):
208208
pass
209209

210-
@staticmethod
211-
def rand_keys(n):
212-
ret = []
213-
idxes = set()
214-
for _ in range(n):
215-
while True:
216-
i = random.randrange(len(KEYS))
217-
if not i in idxes:
218-
break
219-
idxes.add(i)
220-
ret.append(KEYS[i])
221-
return ret
222-
223210
@staticmethod
224211
def make_desc(pattern, privmap, keys, pub_only = False):
225212
pat = pattern.replace("$H", H_POINT)
@@ -332,7 +319,7 @@ def do_test_psbt(self, comment, pattern, privmap, treefn, keys_pay, keys_change)
332319

333320
def do_test(self, comment, pattern, privmap, treefn):
334321
nkeys = len(privmap)
335-
keys = self.rand_keys(nkeys * 4)
322+
keys = random.sample(KEYS, nkeys * 4)
336323
self.do_test_addr(comment, pattern, privmap, treefn, keys[0:nkeys])
337324
self.do_test_sendtoaddress(comment, pattern, privmap, treefn, keys[0:nkeys], keys[nkeys:2*nkeys])
338325
self.do_test_psbt(comment, pattern, privmap, treefn, keys[2*nkeys:3*nkeys], keys[3*nkeys:4*nkeys])

0 commit comments

Comments
 (0)