From d2548cd38ab7beb895a9a49d1c621e61943af917 Mon Sep 17 00:00:00 2001 From: Sebastian Falbesoner Date: Tue, 23 May 2023 23:38:31 +0200 Subject: [PATCH] test: introduce `generate_keypair` helper with WIF support In functional tests it is a quite common scenario to generate fresh elliptic curve keypairs, which is currently a bit cumbersome as it involves multiple steps, e.g.: privkey = ECKey() privkey.generate() privkey_wif = bytes_to_wif(privkey.get_bytes()) pubkey = privkey.get_pubkey().get_bytes() Simplify this by providing a new `generate_keypair` helper function that returns the private key either as `ECKey` object or as WIF-string (depending on the boolean `wif` parameter) and the public key as byte-string; these formats are what we mostly need (currently we don't use `ECPubKey` objects from generated keypairs anywhere). With this, most of the affected code blocks following the pattern above can be replaced by one-liners, e.g.: privkey, pubkey = generate_keypair(wif=True) Github-Pull: #27733 Rebased-From: 1a572ce7d6e2b8282c6ad457cf8ecd2cf5ab7fd6 [partial] --- test/functional/test_framework/wallet_util.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/test/functional/test_framework/wallet_util.py b/test/functional/test_framework/wallet_util.py index b9c0fb6691..531d405488 100755 --- a/test/functional/test_framework/wallet_util.py +++ b/test/functional/test_framework/wallet_util.py @@ -129,3 +129,15 @@ def generate_wif_key(): k = ECKey() k.generate() return bytes_to_wif(k.get_bytes(), k.is_compressed) + +def generate_keypair(compressed=True, wif=False): + """Generate a new random keypair and return the corresponding ECKey / + bytes objects. The private key can also be provided as WIF (wallet + import format) string instead, which is often useful for wallet RPC + interaction.""" + privkey = ECKey() + privkey.generate(compressed) + pubkey = privkey.get_pubkey().get_bytes() + if wif: + privkey = bytes_to_wif(privkey.get_bytes(), compressed) + return privkey, pubkey