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

Code before:
                results.append(dict(result=request()))
            except JSONRPCException as e:
                results.append(dict(error=e))
        return results

    def send_cli(self, clicommand=None, *args, **kwargs):
        """Run bitcoin-cli command. Deserializes returned string as python object."""
        pos_args = [arg_to_cli(arg) for arg in args]
        named_args = [key + "=" + arg_to_cli(value) for (key, value) in kwargs.items() if value is not None]
        p_args = self.binaries.rpc_argv() + [f"-datadir={self.datadir}"] + self.options
        if named_args:
            p_args += ["-named"]
        base_arg_pos = len(p_args)
        if clicommand is not None:
            p_args += [clicommand]
        p_args += pos_args + named_args
        max_arg_size = max(len(arg) for arg in p_args)
        stdin_data = self.input
        if max_arg_size > CLI_MAX_ARG_SIZE:
            self.log.debug(f"Cli: Command size {max_arg_size} too large, using stdin")
            rpc_args = "\n".join([arg for arg in p_args[base_arg_pos:]])
            if stdin_data is not None:
                stdin_data += "\n" + rpc_args
            else:
                stdin_data = rpc_args
            p_args = p_args[:base_arg_pos] + ['-stdin']

        self.log.debug("Running bitcoin-cli {}".format(p_args[2:]))
        process = subprocess.Popen(p_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        cli_stdout, cli_stderr = process.communicate(input=stdin_data)
        returncode = process.poll()
        if returncode:
            match = re.match(r'error code: ([-0-9]+)\nerror message:\n(.*)', cli_stderr)
            if match:
                code, message = match.groups()
                raise JSONRPCException(dict(code=int(code), message=message))
            # Ignore cli_stdout, raise with cli_stderr
            raise subprocess.CalledProcessError(returncode, p_args, output=cli_stderr)
        try:
            if not cli_stdout.strip():
                return None
            return json.loads(cli_stdout, parse_float=decimal.Decimal)
        except (json.JSONDecodeError, decimal.InvalidOperation):
            return cli_stdout.rstrip("\n")


Review comment (bug):
```
2025-08-25T15:54:00.131311Z TestFramework.bitcoincli (DEBUG): Cli: Command size 131140 too large, using stdin
2025-08-25T15:54:00.148742Z TestFramework.bitcoincli (DEBUG): Cli: Command size 262212 too large, using stdin
2025-08-25T15:54:00.179312Z TestFramework.bitcoincli (DEBUG): Cli: Command size 4194372 too large, using stdin
2025-08-25T15:54:00.418554Z TestFramework.bitcoincli (DEBUG): Cli: Command size 8388676 too large, using stdin
```

fa18c82 — The debug logs show byte-based sizes (131140 for 65K chars). Should we use `len(a.encode('utf-8'))` to ensure consistency between the check and the actual command size measurement?

Code after:

    def batch(self, requests):
        results = []
        for request in requests:
            try:
                results.append(dict(result=request()))
            except JSONRPCException as e:
                results.append(dict(error=e))
        return results

    def send_cli(self, clicommand=None, *args, **kwargs):
        """Run bitcoin-cli command. Deserializes returned string as python object."""
        pos_args = [arg_to_cli(arg) for arg in args]
        named_args = [key + "=" + arg_to_cli(value) for (key, value) in kwargs.items() if value is not None]
        p_args = self.binaries.rpc_argv() + [f"-datadir={self.datadir}"] + self.options
        if named_args:
            p_args += ["-named"]
        base_arg_pos = len(p_args)
        if clicommand is not None:
            p_args += [clicommand]
        p_args += pos_args + named_args

        # TEST_CLI_MAX_ARG_SIZE is set low enough that checking the string
        # length is enough and encoding to bytes is not needed before
        # calculating the sum.
        sum_arg_size = sum(len(arg) for arg in p_args)
        stdin_data = self.input
        if sum_arg_size >= TEST_CLI_MAX_ARG_SIZE:
            self.log.debug(f"Cli: Command size {sum_arg_size} too large, using stdin")
            rpc_args = "\n".join([arg for arg in p_args[base_arg_pos:]])
            if stdin_data is not None:
                stdin_data += "\n" + rpc_args
            else:
                stdin_data = rpc_args
            p_args = p_args[:base_arg_pos] + ['-stdin']

        self.log.debug("Running bitcoin-cli {}".format(p_args[2:]))
        process = subprocess.Popen(p_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        cli_stdout, cli_stderr = process.communicate(input=stdin_data)
        returncode = process.poll()
        if returncode:
            match = re.match(r'error code: ([-0-9]+)\nerror message:\n(.*)', cli_stderr)
            if match:
                code, message = match.groups()
                raise JSONRPCException(dict(code=int(code), message=message))
            # Ignore cli_stdout, raise with cli_stderr
            raise subprocess.CalledProcessError(returncode, p_args, output=cli_stderr)
        try:
            if not cli_stdout.strip():
                return None
            return json.loads(cli_stdout, parse_float=decimal.Decimal)