1
0

Merge pull request #10356 from f321x/remove_newline_rawtx

tx: replace all whitespace chars in raw tx (convert_raw_tx_to_hex)
This commit is contained in:
ghost43
2025-12-11 18:49:13 +00:00
committed by GitHub
3 changed files with 51 additions and 27 deletions

View File

@@ -2368,13 +2368,26 @@ class ElectrumWindow(QMainWindow, MessageBoxMixin, Logger, QtEventListener):
)
if not fileName:
return
file_content = None # type: None | str | bytes
# 1. try to open file as "text"
try:
with open(fileName, "rb") as f:
file_content = f.read() # type: Union[str, bytes]
with open(fileName, "r", encoding="ascii") as f:
file_content = f.read() # type: str
except (ValueError, IOError, os.error) as reason:
self.show_critical(_("Electrum was unable to open your transaction file") + "\n" + str(reason),
title=_("Unable to read file or no transaction found"))
return
pass
else:
assert isinstance(file_content, str), f"expected str, got {type(file_content)}"
file_content = file_content.strip() # for text, we can safely strip leading/trailing whitespaces
# 2. try to open file as "binary"
if file_content is None:
try:
with open(fileName, "rb") as f:
file_content = f.read() # type: bytes
except (ValueError, IOError, os.error) as reason:
self.show_critical(_("Electrum was unable to open your transaction file") + "\n" + str(reason),
title=_("Unable to read file or no transaction found"))
if file_content is None:
return None
return self.tx_from_text(file_content)
def do_process_from_text(self):

View File

@@ -36,6 +36,7 @@ from enum import IntEnum
import itertools
import binascii
import copy
import re
import electrum_ecc as ecc
from electrum_ecc.util import bip340_tagged_hash
@@ -1482,7 +1483,16 @@ def convert_raw_tx_to_hex(raw: Union[str, bytes]) -> str:
if not raw:
raise ValueError("empty string")
raw_unstripped = raw
raw = raw.strip()
if isinstance(raw, str):
# remove all whitespace characters, anywhere, for convenience
# - leading/trailing whitespaces are quite common for user-input
# - newlines in the middle can also happen, e.g. when copying a raw tx from a pdf
# note: we don't do this for bytes-like inputs, as whitespace-looking bytes can appear
# anywhere in a raw tx. Even leading/trailing pseudo-whitespace: consider that
# the nVersion or the nLocktime might contain e.g. "0a" bytes
# consider: "\n".encode().hex() == "0a"
# For str, this is a non-issue and safe to do.
raw = re.sub(r'\s', '', raw)
# try hex
try:
return binascii.unhexlify(raw).hex()
@@ -1524,7 +1534,7 @@ def tx_from_any(raw: Union[str, bytes], *,
return tx
except Exception as e:
raise SerializationError(f"Failed to recognise tx encoding, or to parse transaction. "
f"raw: {raw[:30]}...") from e
f"raw: {raw[:30]!r}...") from e
class PSBTGlobalType(IntEnum):