Repository: bitcoin/bitcoin
File: test/functional/tool_signet_miner.py (Python)

Code before:
#!/usr/bin/env python3
# Copyright (c) 2022 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test signet miner tool"""

import os.path
import shlex
import subprocess
import sys
import time

from test_framework.blocktools import DIFF_1_N_BITS
from test_framework.key import ECKey
from test_framework.script_util import key_to_p2wpkh_script
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import (
    assert_equal,
    wallet_importprivkey,
)
from test_framework.wallet_util import bytes_to_wif


CHALLENGE_PRIVATE_KEY = (42).to_bytes(32, 'big')


class SignetMinerTest(BitcoinTestFramework):
    def set_test_params(self):
        self.chain = "signet"
        self.setup_clean_chain = True
        self.num_nodes = 1

        # generate and specify signet challenge (simple p2wpkh script)
        privkey = ECKey()
        privkey.set(CHALLENGE_PRIVATE_KEY, True)
        pubkey = privkey.get_pubkey().get_bytes()
        challenge = key_to_p2wpkh_script(pubkey)
        self.extra_args = [[f'-signetchallenge={challenge.hex()}']]

    def skip_test_if_missing_module(self):
        self.skip_if_no_cli()
        self.skip_if_no_wallet()
        self.skip_if_no_bitcoin_util()

    def run_test(self):
        node = self.nodes[0]
        # import private key needed for signing block
        wallet_importprivkey(node, bytes_to_wif(CHALLENGE_PRIVATE_KEY), "now")

        # generate block with signet miner tool
        base_dir = self.config["environment"]["SRCDIR"]
        signet_miner_path = os.path.join(base_dir, "contrib", "signet", "miner")
        rpc_argv = node.binaries.rpc_argv() + [f"-datadir={node.cli.datadir}"]
        util_argv = node.binaries.util_argv() + ["grind"]
        subprocess.run([
                sys.executable,
                signet_miner_path,
                f'--cli={shlex.join(rpc_argv)}',
                'generate',
                f'--address={node.getnewaddress()}',
                f'--grind-cmd={shlex.join(util_argv)}',
                f'--nbits={DIFF_1_N_BITS:08x}',
                f'--set-block-time={int(time.time())}',
                '--poolnum=99',
            ], check=True, stderr=subprocess.STDOUT)
        assert_equal(node.getblockcount(), 1)


if __name__ == "__main__":
    SignetMinerTest(__file__).main()


Review comment (bug):
https://cirrus-ci.com/task/5609902313308160?logs=ci#L5104

```
[20:25:29.234]  test  2025-03-24T00:25:28.624000Z TestFramework (ERROR): Called Process failed with 'b''' 
[20:25:29.234]                                    Traceback (most recent call last):
[20:25:29.234]                                      File "/ci_container_base/test/functional/test_framework/test_framework.py", line 178, in main
[20:25:29.234]                                        self.run_test()
[20:25:29.234]                                      File "/ci_container_base/ci/scratch/build-x86_64-pc-linux-gnu/test/functional/tool_signet_miner.py", line 127, in run_test
[20:25:29.234]                                        self.mine_block_manual(node, True)
[20:25:29.234]                                      File "/ci_container_base/ci/scratch/build-x86_64-pc-linux-gnu/test/functional/tool_signet_miner.py", line 99, in mine_block_manual
[20:25:29.234]                                        genpsbt = subprocess.run(base_cmd + [
[20:25:29.234]                                      File "/usr/lib/python3.10/subprocess.py", line 526, in run
[20:25:29.234]                                        raise CalledProcessError(retcode, process.args,
[20:25:29.234]                                    subprocess.CalledProcessError: Command '['/usr/bin/python3', '/ci_container_base/contrib/signet/miner', '--cli=<test_framework.test_node.TestNodeCLIAttr object at 0x7f6b6a1e6e30> -datadir=/ci_container_base/ci/scratch/test_runner/test_runner_₿_🏃_20250324_001924/tool_signet_miner_215/node0', 'genpsbt', '--address=tb1qpu2pvqxmre76lgych8luu70qvcx0fjjap9d77q', '--poolnum=98']' returned non-zero exit status 1.

Code after:
                f'--grind-cmd={shlex.join(util_argv)}',
                f'--nbits={DIFF_1_N_BITS:08x}',
                f'--set-block-time={int(time.time())}',
                '--poolnum=99',
            ], check=True, stderr=subprocess.STDOUT)
        assert_equal(node.getblockcount(), n_blocks + 1)

    # generate block using the signet miner tool genpsbt and solvepsbt commands
    def mine_block_manual(self, node, *, sign):
        n_blocks = node.getblockcount()
        base_dir = self.config["environment"]["SRCDIR"]
        signet_miner_path = os.path.join(base_dir, "contrib", "signet", "miner")
        rpc_argv = node.binaries.rpc_argv() + [f"-datadir={node.cli.datadir}"]
        util_argv = node.binaries.util_argv() + ["grind"]
        base_cmd = [
            sys.executable,
            signet_miner_path,
            f'--cli={shlex.join(rpc_argv)}',
        ]

        template = node.getblocktemplate(dict(rules=["signet","segwit"]))
        genpsbt = subprocess.run(base_cmd + [
                'genpsbt',
                f'--address={node.getnewaddress()}',
                '--poolnum=98',
            ], check=True, input=json.dumps(template).encode('utf8'), capture_output=True)
        psbt = genpsbt.stdout.decode('utf8').strip()
        if sign:
            self.log.debug("Sign the PSBT")
            res = node.walletprocesspsbt(psbt=psbt, sign=True, sighashtype='ALL')
            assert res['complete']
            psbt = res['psbt']
        solvepsbt = subprocess.run(base_cmd + [
                'solvepsbt',
                f'--grind-cmd={shlex.join(util_argv)}',
            ], check=True, input=psbt.encode('utf8'), capture_output=True)
        node.submitblock(solvepsbt.stdout.decode('utf8').strip())
        assert_equal(node.getblockcount(), n_blocks + 1)

    def run_test(self):
        self.log.info("Signet node with single signature challenge")
        node = self.nodes[0]
        # import private key needed for signing block
        wallet_importprivkey(node, bytes_to_wif(CHALLENGE_PRIVATE_KEY), 0)
        self.mine_block(node)
        # MUST include signet commitment
        assert get_signet_commitment(get_segwit_commitment(node))

        self.log.info("Mine manually using genpsbt and solvepsbt")
        self.mine_block_manual(node, sign=True)
        assert get_signet_commitment(get_segwit_commitment(node))