Merge bitcoin/bitcoin#33702: contrib: Remove brittle, confusing and redundant UTF8 encoding from Python IO

fad6118586 test: Fix "typo" in written invalid content (MarcoFalke)
fab085c15f contrib: Use text=True in subprocess over manual encoding handling (MarcoFalke)
fa71c15f86 scripted-diff: Bump copyright headers after encoding changes (MarcoFalke)
fae612424b contrib: Remove confusing and redundant encoding from IO (MarcoFalke)
fa7d72bd1b lint: Drop check to enforce encoding to be specified in Python scripts (MarcoFalke)
faf39d8539 test: Clarify that Python UTF-8 mode is the default today for most systems (MarcoFalke)
fa83e3a81d lint: Do not allow locale dependent shell scripts (MarcoFalke)

Pull request description:

  Historically, there was an attempt via `test/lint/lint-python-utf8-encoding.py` to enforce explicit UTF8 in every Python IO statement (`open`, `subprocess`, ...). However, the lint check has many problems:

  * The check is incomplete and many IO statements lack the explicit UTF8 specification.
  * It was added at a time when some systems were not UTF8 by default.
  * The check is brittle, as it depends on a fragile regex.

  In theory, now that the minimum Python version is 3.10 (since commit 2123c94448), the check could be replaced by `PYTHONWARNDEFAULTENCODING=1` from https://docs.python.org/3/whatsnew/3.10.html#optional-encodingwarning-and-encoding-locale-option. However, this comes with many other problems:

  * All our Python scripts already assume and require UTF8 to be set externally. On almost all modern systems, this is already the default. Some Windows versions do not have UTF8 by default and require `PYTHONUTF8=1` to be set for the tests to run already today (with or without the changes in this pull). Also, the CI and many other Bash scripts force UTF8 via `LC_ALL`. Finally, Python 3.15 will likely enable UTF8 on *all* systems by default, per https://peps.python.org/pep-0686/#abstract.
  * So adding UTF8 to every single IO call is redundant, verbose, and confusing, given that it is the expected default.

  So fix all issues, by:

  * Removing the `test/lint/lint-python-utf8-encoding.py` check.
  * Removing the encoding on the individual IO calls.
  * Clarifying the existing docs around the existing UTF8 requirement and assumption.

  Obviously, every IO call is still free to specify UTF8 or any other encoding explicitly, if there is a documented need for it in the future.

ACKs for top commit:
  theStack:
    re-ACK fad6118586
  laanwj:
    Re-ACK fad6118586

Tree-SHA512: 78025ea3508597d2299490347614f0ee3e4c66e3ba559ff50e498045a9c8bbd92f3a5ced18719d8fcebbd1e47bdbb56a0c85a5b73b425adb0ea4f02fe69c3149
This commit is contained in:
merge-script committed 2025-12-03 09:54:47 +00:00
commit af0e6a65c9
63 files changed
+217 -299

No files matched your search

+3 -3
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
# Copyright (c) 2015-2021 The Bitcoin Core developers
# Copyright (c) 2015-present The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Utilities for doing coverage analysis on the RPC interface.
@@ -55,7 +55,7 @@ class AuthServiceProxyWrapper():
rpc_method = self.auth_service_proxy_instance._service_name
if self.coverage_logfile:
with open(self.coverage_logfile, 'a+', encoding='utf8') as f:
with open(self.coverage_logfile, 'a+') as f:
f.write("%s\n" % rpc_method)
def __truediv__(self, relative_uri):
@@ -107,7 +107,7 @@ def write_all_rpc_commands(dirname: str, node: AuthServiceProxy) -> bool:
if line and not line.startswith('='):
commands.add("%s\n" % line.split()[0])
with open(filename, 'w', encoding='utf8') as f:
with open(filename, 'w') as f:
f.writelines(list(commands))
return True
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
# Copyright (c) 2022 The Bitcoin Core developers
# Copyright (c) 2022-present 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-only Elligator Swift implementation
@@ -134,7 +134,7 @@ class TestFrameworkEllSwift(unittest.TestCase):
def test_elligator_encode_testvectors(self):
"""Implement the BIP324 test vectors for ellswift encoding (read from xswiftec_inv_test_vectors.csv)."""
vectors_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'xswiftec_inv_test_vectors.csv')
with open(vectors_file, newline='', encoding='utf8') as csvfile:
with open(vectors_file, newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
u = FE.from_bytes(bytes.fromhex(row['u']))
@@ -150,7 +150,7 @@ class TestFrameworkEllSwift(unittest.TestCase):
def test_elligator_decode_testvectors(self):
"""Implement the BIP324 test vectors for ellswift decoding (read from ellswift_decode_test_vectors.csv)."""
vectors_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'ellswift_decode_test_vectors.csv')
with open(vectors_file, newline='', encoding='utf8') as csvfile:
with open(vectors_file, newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
encoding = bytes.fromhex(row['ellswift'])
+1 -1
View File
@@ -316,7 +316,7 @@ class TestFrameworkKey(unittest.TestCase):
"""Implement the BIP340 test vectors (read from bip340_test_vectors.csv)."""
num_tests = 0
vectors_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'bip340_test_vectors.csv')
with open(vectors_file, newline='', encoding='utf8') as csvfile:
with open(vectors_file, newline='') as csvfile:
reader = csv.reader(csvfile)
next(reader)
for row in reader:
+2 -2
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
# Copyright (c) 2014-2022 The Bitcoin Core developers
# Copyright (c) 2014-present The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Linux network utilities.
@@ -69,7 +69,7 @@ def netstat(typ='tcp'):
To get pid of all network process running on system, you must run this script
as superuser
'''
with open('/proc/net/'+typ,'r',encoding='utf8') as f:
with open('/proc/net/'+typ,'r') as f:
content = f.readlines()
content.pop(0)
result = []
@@ -751,7 +751,7 @@ class BitcoinTestFramework(metaclass=BitcoinTestMetaClass):
self.log = logging.getLogger('TestFramework')
self.log.setLevel(logging.DEBUG)
# Create file handler to log all messages
fh = logging.FileHandler(self.options.tmpdir + '/test_framework.log', encoding='utf-8')
fh = logging.FileHandler(self.options.tmpdir + '/test_framework.log')
fh.setLevel(logging.DEBUG)
# Create console handler to log messages to stderr. By default this logs only error messages, but can be configured with --loglevel.
ch = logging.StreamHandler(sys.stdout)
+2 -2
View File
@@ -506,13 +506,13 @@ class TestNode():
The substitutions are passed as a list of search-replace-tuples, e.g.
[("old", "new"), ("foo", "bar"), ...]
"""
with open(self.bitcoinconf, 'r', encoding='utf8') as conf:
with open(self.bitcoinconf, 'r') as conf:
conf_data = conf.read()
for replacement in replacements:
assert_equal(len(replacement), 2)
old, new = replacement[0], replacement[1]
conf_data = conf_data.replace(old, new)
with open(self.bitcoinconf, 'w', encoding='utf8') as conf:
with open(self.bitcoinconf, 'w') as conf:
conf.write(conf_data)
@property
+5 -5
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
# Copyright (c) 2014-2022 The Bitcoin Core developers
# Copyright (c) 2014-present The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Helpful routines for regression testing."""
@@ -528,7 +528,7 @@ def write_config(config_path, *, n, chain, extra_config="", disable_autoconnect=
else:
chain_name_conf_arg = chain
chain_name_conf_section = chain
with open(config_path, 'w', encoding='utf8') as f:
with open(config_path, 'w') as f:
if chain_name_conf_arg:
f.write("{}=1\n".format(chain_name_conf_arg))
if chain_name_conf_section:
@@ -594,7 +594,7 @@ def get_temp_default_datadir(temp_dir: pathlib.Path) -> tuple[dict, pathlib.Path
def append_config(datadir, options):
with open(os.path.join(datadir, "bitcoin.conf"), 'a', encoding='utf8') as f:
with open(os.path.join(datadir, "bitcoin.conf"), 'a') as f:
for option in options:
f.write(option + "\n")
@@ -603,7 +603,7 @@ def get_auth_cookie(datadir, chain):
user = None
password = None
if os.path.isfile(os.path.join(datadir, "bitcoin.conf")):
with open(os.path.join(datadir, "bitcoin.conf"), 'r', encoding='utf8') as f:
with open(os.path.join(datadir, "bitcoin.conf"), 'r') as f:
for line in f:
if line.startswith("rpcuser="):
assert user is None # Ensure that there is only one rpcuser line
@@ -612,7 +612,7 @@ def get_auth_cookie(datadir, chain):
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:
with open(os.path.join(datadir, chain, ".cookie"), 'r') as f:
userpass = f.read()
split_userpass = userpass.split(':')
user = split_userpass[0]