Browse Source

util: kill bh2u

no longer useful, and the name is so confusing...
master
SomberNight 3 years ago
parent
commit
373db76ac9
No known key found for this signature in database
GPG Key ID: B33B5F232C6271E9
  1. 2
      electrum/bip32.py
  2. 20
      electrum/bitcoin.py
  3. 4
      electrum/blockchain.py
  4. 4
      electrum/channel_db.py
  5. 6
      electrum/commands.py
  6. 4
      electrum/ecc.py
  7. 5
      electrum/gui/kivy/uix/dialogs/lightning_channels.py
  8. 3
      electrum/gui/kivy/uix/dialogs/lightning_open_channel.py
  9. 4
      electrum/gui/qt/channel_details.py
  10. 2
      electrum/gui/qt/channels_list.py
  11. 2
      electrum/gui/qt/main_window.py
  12. 4
      electrum/gui/qt/send_tab.py
  13. 2
      electrum/keystore.py
  14. 8
      electrum/lnchannel.py
  15. 2
      electrum/lnhtlc.py
  16. 2
      electrum/lnonion.py
  17. 14
      electrum/lnpeer.py
  18. 2
      electrum/lnrouter.py
  19. 24
      electrum/lnsweep.py
  20. 2
      electrum/lntransport.py
  21. 26
      electrum/lnutil.py
  22. 4
      electrum/lnverifier.py
  23. 4
      electrum/lnwatcher.py
  24. 16
      electrum/lnworker.py
  25. 4
      electrum/mnemonic.py
  26. 2
      electrum/paymentrequest.py
  27. 4
      electrum/plugins/bitbox02/bitbox02.py
  28. 2
      electrum/plugins/coldcard/coldcard.py
  29. 4
      electrum/plugins/cosigner_pool/qt.py
  30. 4
      electrum/plugins/keepkey/keepkey.py
  31. 3
      electrum/plugins/keepkey/qt.py
  32. 4
      electrum/plugins/revealer/revealer.py
  33. 3
      electrum/plugins/safe_t/qt.py
  34. 4
      electrum/plugins/safe_t/safe_t.py
  35. 3
      electrum/plugins/trezor/qt.py
  36. 4
      electrum/plugins/trezor/trezor.py
  37. 6
      electrum/scripts/ln_features.py
  38. 4
      electrum/synchronizer.py
  39. 20
      electrum/tests/test_bitcoin.py
  40. 2
      electrum/tests/test_blockchain.py
  41. 4
      electrum/tests/test_lnpeer.py
  42. 2
      electrum/tests/test_lnrouter.py
  43. 6
      electrum/tests/test_lnutil.py
  44. 10
      electrum/tests/test_mnemonic.py
  45. 3
      electrum/tests/test_network.py
  46. 4
      electrum/tests/test_transaction.py
  47. 6
      electrum/tests/test_wallet_vertical.py
  48. 20
      electrum/transaction.py
  49. 13
      electrum/util.py
  50. 4
      electrum/verifier.py
  51. 2
      electrum/wallet.py
  52. 6
      electrum/x509.py

2
electrum/bip32.py

@ -5,7 +5,7 @@
import hashlib
from typing import List, Tuple, NamedTuple, Union, Iterable, Sequence, Optional
from .util import bfh, bh2u, BitcoinException
from .util import bfh, BitcoinException
from . import constants
from . import ecc
from .crypto import hash_160, hmac_oneshot

20
electrum/bitcoin.py

@ -28,7 +28,7 @@ from typing import List, Tuple, TYPE_CHECKING, Optional, Union, Sequence
import enum
from enum import IntEnum, Enum
from .util import bfh, bh2u, BitcoinException, assert_bytes, to_bytes, inv_dict, is_hex_str
from .util import bfh, BitcoinException, assert_bytes, to_bytes, inv_dict, is_hex_str
from . import version
from . import segwit_addr
from . import constants
@ -198,7 +198,7 @@ class opcodes(IntEnum):
def rev_hex(s: str) -> str:
return bh2u(bfh(s)[::-1])
return bfh(s)[::-1].hex()
def int_to_hex(i: int, length: int=1) -> str:
@ -238,7 +238,7 @@ def script_num_to_hex(i: int) -> str:
elif neg:
result[-1] |= 0x80
return bh2u(result)
return result.hex()
def var_int(i: int) -> str:
@ -288,11 +288,11 @@ def push_script(data: str) -> str:
if data_len == 0 or data_len == 1 and data[0] == 0:
return opcodes.OP_0.hex()
elif data_len == 1 and data[0] <= 16:
return bh2u(bytes([opcodes.OP_1 - 1 + data[0]]))
return bytes([opcodes.OP_1 - 1 + data[0]]).hex()
elif data_len == 1 and data[0] == 0x81:
return opcodes.OP_1NEGATE.hex()
return _op_push(data_len) + bh2u(data)
return _op_push(data_len) + data.hex()
def make_op_return(x:bytes) -> bytes:
@ -310,7 +310,7 @@ def construct_witness(items: Sequence[Union[str, int, bytes]]) -> str:
if type(item) is int:
item = script_num_to_hex(item)
elif isinstance(item, (bytes, bytearray)):
item = bh2u(item)
item = item.hex()
else:
assert is_hex_str(item)
witness += witness_push(item)
@ -366,7 +366,7 @@ def dust_threshold(network: 'Network' = None) -> int:
def hash_encode(x: bytes) -> str:
return bh2u(x[::-1])
return x[::-1].hex()
def hash_decode(x: str) -> bytes:
@ -464,7 +464,7 @@ def address_to_script(addr: str, *, net=None) -> str:
return construct_script([witver, bytes(witprog)])
addrtype, hash_160_ = b58_address_to_hash160(addr)
if addrtype == net.ADDRTYPE_P2PKH:
script = pubkeyhash_to_p2pkh_script(bh2u(hash_160_))
script = pubkeyhash_to_p2pkh_script(hash_160_.hex())
elif addrtype == net.ADDRTYPE_P2SH:
script = construct_script([opcodes.OP_HASH160, hash_160_, opcodes.OP_EQUAL])
else:
@ -519,7 +519,7 @@ def address_to_scripthash(addr: str, *, net=None) -> str:
def script_to_scripthash(script: str) -> str:
h = sha256(bfh(script))[0:32]
return bh2u(bytes(reversed(h)))
return h[::-1].hex()
def public_key_to_p2pk_script(pubkey: str) -> str:
return construct_script([pubkey, opcodes.OP_CHECKSIG])
@ -613,7 +613,7 @@ def DecodeBase58Check(psz: Union[bytes, str]) -> bytes:
csum_found = vchRet[-4:]
csum_calculated = sha256d(payload)[0:4]
if csum_calculated != csum_found:
raise InvalidChecksum(f'calculated {bh2u(csum_calculated)}, found {bh2u(csum_found)}')
raise InvalidChecksum(f'calculated {csum_calculated.hex()}, found {csum_found.hex()}')
else:
return payload

4
electrum/blockchain.py

@ -29,7 +29,7 @@ from . import util
from .bitcoin import hash_encode, int_to_hex, rev_hex
from .crypto import sha256d
from . import constants
from .util import bfh, bh2u, with_lock
from .util import bfh, with_lock
from .simple_config import SimpleConfig
from .logging import get_logger, Logger
@ -408,7 +408,7 @@ class Blockchain(Logger):
# swap parameters
self.parent, parent.parent = parent.parent, self # type: Optional[Blockchain], Optional[Blockchain]
self.forkpoint, parent.forkpoint = parent.forkpoint, self.forkpoint
self._forkpoint_hash, parent._forkpoint_hash = parent._forkpoint_hash, hash_raw_header(bh2u(parent_data[:HEADER_SIZE]))
self._forkpoint_hash, parent._forkpoint_hash = parent._forkpoint_hash, hash_raw_header(parent_data[:HEADER_SIZE].hex())
self._prev_hash, parent._prev_hash = parent._prev_hash, self._prev_hash
# parent's new name
os.replace(child_old_name, parent.path())

4
electrum/channel_db.py

@ -38,7 +38,7 @@ from aiorpcx import NetAddress
from .sql_db import SqlDB, sql
from . import constants, util
from .util import bh2u, profiler, get_headers_dir, is_ip_address, json_normalize
from .util import profiler, get_headers_dir, is_ip_address, json_normalize
from .logging import Logger
from .lnutil import (LNPeerAddr, format_short_channel_id, ShortChannelID,
validate_features, IncompatibleOrInsaneFeatures, InvalidGossipMsg)
@ -396,7 +396,7 @@ class ChannelDB(SqlDB):
if short_channel_id in self._channels:
continue
if constants.net.rev_genesis_bytes() != msg['chain_hash']:
self.logger.info("ChanAnn has unexpected chain_hash {}".format(bh2u(msg['chain_hash'])))
self.logger.info("ChanAnn has unexpected chain_hash {}".format(msg['chain_hash'].hex()))
continue
try:
channel_info = ChannelInfo.from_msg(msg)

6
electrum/commands.py

@ -41,7 +41,7 @@ from typing import Optional, TYPE_CHECKING, Dict, List
import os
from .import util, ecc
from .util import (bfh, bh2u, format_satoshis, json_decode, json_normalize,
from .util import (bfh, format_satoshis, json_decode, json_normalize,
is_hash256_str, is_hex_str, to_bytes, parse_max_spend)
from . import bitcoin
from .bitcoin import is_address, hash_160, COIN
@ -1126,7 +1126,7 @@ class Commands:
@command('wl')
async def nodeid(self, wallet: Abstract_Wallet = None):
listen_addr = self.config.get('lightning_listen')
return bh2u(wallet.lnworker.node_keypair.pubkey) + (('@' + listen_addr) if listen_addr else '')
return wallet.lnworker.node_keypair.pubkey.hex() + (('@' + listen_addr) if listen_addr else '')
@command('wl')
async def list_channels(self, wallet: Abstract_Wallet = None):
@ -1142,7 +1142,7 @@ class Commands:
'channel_point': chan.funding_outpoint.to_str(),
'state': chan.get_state().name,
'peer_state': chan.peer_state.name,
'remote_pubkey': bh2u(chan.node_id),
'remote_pubkey': chan.node_id.hex(),
'local_balance': chan.balance(LOCAL)//1000,
'remote_balance': chan.balance(REMOTE)//1000,
'local_ctn': chan.get_latest_ctn(LOCAL),

4
electrum/ecc.py

@ -32,7 +32,7 @@ from ctypes import (
CFUNCTYPE, POINTER, cast
)
from .util import bfh, bh2u, assert_bytes, to_bytes, InvalidPassword, profiler, randrange
from .util import bfh, assert_bytes, to_bytes, InvalidPassword, profiler, randrange
from .crypto import (sha256d, aes_encrypt_with_iv, aes_decrypt_with_iv, hmac_oneshot)
from . import constants
from .logging import get_logger
@ -221,7 +221,7 @@ class ECPubkey(object):
return header + x + y
def get_public_key_hex(self, compressed=True) -> str:
return bh2u(self.get_public_key_bytes(compressed))
return self.get_public_key_bytes(compressed).hex()
def point(self) -> Tuple[Optional[int], Optional[int]]:
x = self.x()

5
electrum/gui/kivy/uix/dialogs/lightning_channels.py

@ -5,7 +5,6 @@ from kivy.lang import Builder
from kivy.factory import Factory
from kivy.uix.popup import Popup
from electrum.util import bh2u
from electrum.logging import Logger
from electrum.lnutil import LOCAL, REMOTE, format_short_channel_id
from electrum.lnchannel import AbstractChannel, Channel, ChannelState, ChanCloseOption
@ -465,8 +464,8 @@ class ChannelDetailsPopup(Popup, Logger):
self.app = app
self.chan = chan
self.title = _('Channel details')
self.node_id = bh2u(chan.node_id)
self.channel_id = bh2u(chan.channel_id)
self.node_id = chan.node_id.hex()
self.channel_id = chan.channel_id.hex()
self.funding_txid = chan.funding_outpoint.txid
self.short_id = format_short_channel_id(chan.short_channel_id)
self.capacity = self.app.format_amount_and_units(chan.get_capacity())

3
electrum/gui/kivy/uix/dialogs/lightning_open_channel.py

@ -6,7 +6,6 @@ from kivy.factory import Factory
from electrum.gui import messages
from electrum.gui.kivy.i18n import _
from electrum.lnaddr import lndecode
from electrum.util import bh2u
from electrum.bitcoin import COIN
import electrum.simple_config as config
from electrum.logging import Logger
@ -150,7 +149,7 @@ class LightningOpenChannelDialog(Factory.Popup, Logger):
if not fee:
fee = config.FEERATE_FALLBACK_STATIC_FEE
self.amount = self.app.format_amount_and_units(self.lnaddr.amount * COIN + fee * 2) # FIXME magic number?!
self.pubkey = bh2u(self.lnaddr.pubkey.serialize())
self.pubkey = self.lnaddr.pubkey.serialize().hex()
if self.msg:
self.app.show_info(self.msg)

4
electrum/gui/qt/channel_details.py

@ -7,7 +7,7 @@ from PyQt5.QtWidgets import QLabel, QLineEdit, QHBoxLayout, QGridLayout
from electrum.util import EventListener
from electrum.i18n import _
from electrum.util import bh2u, format_time
from electrum.util import format_time
from electrum.lnutil import format_short_channel_id, LOCAL, REMOTE, UpdateAddHtlc, Direction
from electrum.lnchannel import htlcsum, Channel, AbstractChannel, HTLCWithStatus
from electrum.lnaddr import LnAddr, lndecode
@ -86,7 +86,7 @@ class ChannelDetailsDialog(QtWidgets.QDialog, MessageBoxMixin, QtEventListener):
it = HTLCItem(_('Sent HTLC with ID {}' if Direction.SENT == direction else 'Received HTLC with ID {}').format(i.htlc_id))
it.appendRow([HTLCItem(_('Amount')),HTLCItem(self.format_msat(i.amount_msat))])
it.appendRow([HTLCItem(_('CLTV expiry')),HTLCItem(str(i.cltv_expiry))])
it.appendRow([HTLCItem(_('Payment hash')),HTLCItem(bh2u(i.payment_hash))])
it.appendRow([HTLCItem(_('Payment hash')),HTLCItem(i.payment_hash.hex())])
return it
def make_model(self, htlcs: Sequence[HTLCWithStatus]) -> QtGui.QStandardItemModel:

2
electrum/gui/qt/channels_list.py

@ -11,7 +11,7 @@ from PyQt5.QtWidgets import (QMenu, QHBoxLayout, QLabel, QVBoxLayout, QGridLayou
QToolTip)
from PyQt5.QtGui import QFont, QStandardItem, QBrush, QPainter, QIcon, QHelpEvent
from electrum.util import bh2u, NotEnoughFunds, NoDynamicFeeEstimates
from electrum.util import NotEnoughFunds, NoDynamicFeeEstimates
from electrum.i18n import _
from electrum.lnchannel import AbstractChannel, PeerState, ChannelBackup, Channel, ChannelState, ChanCloseOption
from electrum.wallet import Abstract_Wallet

2
electrum/gui/qt/main_window.py

@ -57,7 +57,7 @@ from electrum.plugin import run_hook, BasePlugin
from electrum.i18n import _
from electrum.util import (format_time, get_asyncio_loop,
UserCancelled, profiler,
bh2u, bfh, InvalidPassword,
bfh, InvalidPassword,
UserFacingException, FailedToParsePaymentIdentifier,
get_new_wallet_name, send_exception_to_crash_reporter,
AddTransactionException, BITCOIN_BIP21_URI_SCHEME, os_chmod)

4
electrum/gui/qt/send_tab.py

@ -15,7 +15,7 @@ from electrum import util, paymentrequest
from electrum import lnutil
from electrum.plugin import run_hook
from electrum.i18n import _
from electrum.util import (get_asyncio_loop, bh2u, FailedToParsePaymentIdentifier,
from electrum.util import (get_asyncio_loop, FailedToParsePaymentIdentifier,
InvalidBitcoinURI, maybe_extract_lightning_payment_identifier, NotEnoughFunds,
NoDynamicFeeEstimates, InvoiceError, parse_max_spend)
from electrum.invoices import PR_PAID, Invoice
@ -396,7 +396,7 @@ class SendTab(QWidget, MessageBoxMixin, Logger):
self.show_error(_("Invoice requires unknown or incompatible Lightning feature") + f":\n{e!r}")
return
pubkey = bh2u(lnaddr.pubkey.serialize())
pubkey = lnaddr.pubkey.serialize().hex()
for k,v in lnaddr.tags:
if k == 'd':
description = v

2
electrum/keystore.py

@ -42,7 +42,7 @@ from .crypto import (pw_decode, pw_encode, sha256, sha256d, PW_HASH_VERSION_LATE
SUPPORTED_PW_HASH_VERSIONS, UnsupportedPasswordHashVersion, hash_160,
CiphertextFormatError)
from .util import (InvalidPassword, WalletFileException,
BitcoinException, bh2u, bfh, inv_dict, is_hex_str)
BitcoinException, bfh, inv_dict, is_hex_str)
from .mnemonic import Mnemonic, Wordlist, seed_type, is_seed
from .plugin import run_hook
from .logging import Logger

8
electrum/lnchannel.py

@ -35,7 +35,7 @@ import attr
from . import ecc
from . import constants, util
from .util import bfh, bh2u, chunks, TxMinedInfo
from .util import bfh, chunks, TxMinedInfo
from .invoices import PR_PAID
from .bitcoin import redeem_script_to_address
from .crypto import sha256, sha256d
@ -1525,8 +1525,8 @@ class Channel(AbstractChannel):
},
local_amount_msat=self.balance(LOCAL),
remote_amount_msat=self.balance(REMOTE) if not drop_remote else 0,
local_script=bh2u(local_script),
remote_script=bh2u(remote_script),
local_script=local_script.hex(),
remote_script=remote_script.hex(),
htlcs=[],
dust_limit_sat=self.config[LOCAL].dust_limit_sat)
@ -1552,7 +1552,7 @@ class Channel(AbstractChannel):
def force_close_tx(self) -> PartialTransaction:
tx = self.get_latest_commitment(LOCAL)
assert self.signature_fits(tx)
tx.sign({bh2u(self.config[LOCAL].multisig_key.pubkey): (self.config[LOCAL].multisig_key.privkey, True)})
tx.sign({self.config[LOCAL].multisig_key.pubkey.hex(): (self.config[LOCAL].multisig_key.privkey, True)})
remote_sig = self.config[LOCAL].current_commitment_signature
remote_sig = ecc.der_sig_from_sig_string(remote_sig) + Sighash.to_sigbytes(Sighash.ALL)
tx.add_signature_to_txin(txin_idx=0,

2
electrum/lnhtlc.py

@ -3,7 +3,7 @@ from typing import Optional, Sequence, Tuple, List, Dict, TYPE_CHECKING, Set
import threading
from .lnutil import SENT, RECEIVED, LOCAL, REMOTE, HTLCOwner, UpdateAddHtlc, Direction, FeeUpdate
from .util import bh2u, bfh, with_lock
from .util import bfh, with_lock
if TYPE_CHECKING:
from .json_db import StoredDict

2
electrum/lnonion.py

@ -30,7 +30,7 @@ from enum import IntEnum
from . import ecc
from .crypto import sha256, hmac_oneshot, chacha20_encrypt
from .util import bh2u, profiler, xor_bytes, bfh
from .util import profiler, xor_bytes, bfh
from .lnutil import (get_ecdh, PaymentFailure, NUM_MAX_HOPS_IN_PAYMENT_PATH,
NUM_MAX_EDGES_IN_PAYMENT_PATH, ShortChannelID, OnionFailureCodeMetaFlag)
from .lnmsg import OnionWireSerializer, read_bigsize_int, write_bigsize_int

14
electrum/lnpeer.py

@ -21,7 +21,7 @@ from . import bitcoin, util
from . import ecc
from .ecc import sig_string_from_r_and_s, der_sig_from_sig_string
from . import constants
from .util import (bh2u, bfh, log_exceptions, ignore_exceptions, chunks, OldTaskGroup,
from .util import (bfh, log_exceptions, ignore_exceptions, chunks, OldTaskGroup,
UnrelatedTransactionException)
from . import transaction
from .bitcoin import make_op_return
@ -1020,7 +1020,7 @@ class Peer(Logger):
# -> funding signed
funding_idx = funding_created['funding_output_index']
funding_txid = bh2u(funding_created['funding_txid'][::-1])
funding_txid = funding_created['funding_txid'][::-1].hex()
channel_id, funding_txid_bytes = channel_id_from_funding_tx(funding_txid, funding_idx)
constraints = ChannelConstraints(
capacity=funding_sat,
@ -1157,7 +1157,7 @@ class Peer(Logger):
if our_pcs != their_claim_of_our_last_per_commitment_secret:
self.logger.error(
f"channel_reestablish ({chan.get_id_for_log()}): "
f"(DLP) local PCS mismatch: {bh2u(our_pcs)} != {bh2u(their_claim_of_our_last_per_commitment_secret)}")
f"(DLP) local PCS mismatch: {our_pcs.hex()} != {their_claim_of_our_last_per_commitment_secret.hex()}")
return False
assert chan.is_static_remotekey_enabled()
return True
@ -1167,7 +1167,7 @@ class Peer(Logger):
if they_are_ahead:
self.logger.warning(
f"channel_reestablish ({chan.get_id_for_log()}): "
f"remote is ahead of us! They should force-close. Remote PCP: {bh2u(their_local_pcp)}")
f"remote is ahead of us! They should force-close. Remote PCP: {their_local_pcp.hex()}")
# data_loss_protect_remote_pcp is used in lnsweep
chan.set_data_loss_protect_remote_pcp(their_next_local_ctn - 1, their_local_pcp)
chan.set_state(ChannelState.WE_ARE_TOXIC)
@ -1311,7 +1311,7 @@ class Peer(Logger):
self.mark_open(chan)
def on_channel_ready(self, chan: Channel, payload):
self.logger.info(f"on_channel_ready. channel: {bh2u(chan.channel_id)}")
self.logger.info(f"on_channel_ready. channel: {chan.channel_id.hex()}")
# save remote alias for use in invoices
scid_alias = payload.get('channel_ready_tlvs', {}).get('short_channel_id', {}).get('alias')
if scid_alias:
@ -2185,11 +2185,11 @@ class Peer(Logger):
closing_tx.add_signature_to_txin(
txin_idx=0,
signing_pubkey=chan.config[LOCAL].multisig_key.pubkey.hex(),
sig=bh2u(der_sig_from_sig_string(our_sig) + Sighash.to_sigbytes(Sighash.ALL)))
sig=(der_sig_from_sig_string(our_sig) + Sighash.to_sigbytes(Sighash.ALL)).hex())
closing_tx.add_signature_to_txin(
txin_idx=0,
signing_pubkey=chan.config[REMOTE].multisig_key.pubkey.hex(),
sig=bh2u(der_sig_from_sig_string(their_sig) + Sighash.to_sigbytes(Sighash.ALL)))
sig=(der_sig_from_sig_string(their_sig) + Sighash.to_sigbytes(Sighash.ALL)).hex())
# save local transaction and set state
try:
self.lnworker.wallet.adb.add_transaction(closing_tx)

2
electrum/lnrouter.py

@ -31,7 +31,7 @@ from threading import RLock
import attr
from math import inf
from .util import profiler, with_lock, bh2u
from .util import profiler, with_lock
from .logging import Logger
from .lnutil import (NUM_MAX_EDGES_IN_PAYMENT_PATH, ShortChannelID, LnFeatures,
NBLOCK_CLTV_EXPIRY_TOO_FAR_INTO_FUTURE)

24
electrum/lnsweep.py

@ -5,7 +5,7 @@
from typing import Optional, Dict, List, Tuple, TYPE_CHECKING, NamedTuple, Callable
from enum import Enum, auto
from .util import bfh, bh2u
from .util import bfh
from .bitcoin import redeem_script_to_address, dust_threshold, construct_witness
from .invoices import PR_PAID
from . import ecc
@ -52,8 +52,8 @@ def create_sweeptxs_for_watchtower(chan: 'Channel', ctx: Transaction, per_commit
txs = []
# to_local
revocation_pubkey = ecc.ECPrivkey(other_revocation_privkey).get_public_key_bytes(compressed=True)
witness_script = bh2u(make_commitment_output_to_local_witness_script(
revocation_pubkey, to_self_delay, this_delayed_pubkey))
witness_script = make_commitment_output_to_local_witness_script(
revocation_pubkey, to_self_delay, this_delayed_pubkey).hex()
to_local_address = redeem_script_to_address('p2wsh', witness_script)
output_idxs = ctx.get_output_idxs_from_address(to_local_address)
if output_idxs:
@ -119,8 +119,8 @@ def create_sweeptx_for_their_revoked_ctx(
txs = []
# to_local
revocation_pubkey = ecc.ECPrivkey(other_revocation_privkey).get_public_key_bytes(compressed=True)
witness_script = bh2u(make_commitment_output_to_local_witness_script(
revocation_pubkey, to_self_delay, this_delayed_pubkey))
witness_script = make_commitment_output_to_local_witness_script(
revocation_pubkey, to_self_delay, this_delayed_pubkey).hex()
to_local_address = redeem_script_to_address('p2wsh', witness_script)
output_idxs = ctx.get_output_idxs_from_address(to_local_address)
if output_idxs:
@ -159,8 +159,8 @@ def create_sweeptx_for_their_revoked_htlc(
this_delayed_pubkey = derive_pubkey(this_conf.delayed_basepoint.pubkey, pcp)
# same witness script as to_local
revocation_pubkey = ecc.ECPrivkey(other_revocation_privkey).get_public_key_bytes(compressed=True)
witness_script = bh2u(make_commitment_output_to_local_witness_script(
revocation_pubkey, to_self_delay, this_delayed_pubkey))
witness_script = make_commitment_output_to_local_witness_script(
revocation_pubkey, to_self_delay, this_delayed_pubkey).hex()
htlc_address = redeem_script_to_address('p2wsh', witness_script)
# check that htlc_tx is a htlc
if htlc_tx.outputs()[0].address != htlc_address:
@ -201,8 +201,8 @@ def create_sweeptxs_for_our_ctx(
our_htlc_privkey = derive_privkey(secret=int.from_bytes(our_conf.htlc_basepoint.privkey, 'big'),
per_commitment_point=our_pcp).to_bytes(32, 'big')
our_localdelayed_pubkey = our_localdelayed_privkey.get_public_key_bytes(compressed=True)
to_local_witness_script = bh2u(make_commitment_output_to_local_witness_script(
their_revocation_pubkey, to_self_delay, our_localdelayed_pubkey))
to_local_witness_script = make_commitment_output_to_local_witness_script(
their_revocation_pubkey, to_self_delay, our_localdelayed_pubkey).hex()
to_local_address = redeem_script_to_address('p2wsh', to_local_witness_script)
# test if this is our_ctx
found_to_local = bool(ctx.get_output_idxs_from_address(to_local_address))
@ -354,8 +354,8 @@ def create_sweeptxs_for_their_ctx(
# to_local and to_remote addresses
our_revocation_pubkey = derive_blinded_pubkey(our_conf.revocation_basepoint.pubkey, their_pcp)
their_delayed_pubkey = derive_pubkey(their_conf.delayed_basepoint.pubkey, their_pcp)
witness_script = bh2u(make_commitment_output_to_local_witness_script(
our_revocation_pubkey, our_conf.to_self_delay, their_delayed_pubkey))
witness_script = make_commitment_output_to_local_witness_script(
our_revocation_pubkey, our_conf.to_self_delay, their_delayed_pubkey).hex()
to_local_address = redeem_script_to_address('p2wsh', witness_script)
# test if this is their ctx
found_to_local = bool(ctx.get_output_idxs_from_address(to_local_address))
@ -463,7 +463,7 @@ def create_htlctx_that_spends_from_our_ctx(
commit=ctx,
htlc=htlc,
ctx_output_idx=ctx_output_idx,
name=f'our_ctx_{ctx_output_idx}_htlc_tx_{bh2u(htlc.payment_hash)}')
name=f'our_ctx_{ctx_output_idx}_htlc_tx_{htlc.payment_hash.hex()}')
remote_htlc_sig = chan.get_remote_htlc_sig_for_htlc(htlc_relative_idx=htlc_relative_idx)
local_htlc_sig = bfh(htlc_tx.sign_txin(0, local_htlc_privkey))
txin = htlc_tx.inputs()[0]

2
electrum/lntransport.py

@ -15,7 +15,7 @@ from .crypto import sha256, hmac_oneshot, chacha20_poly1305_encrypt, chacha20_po
from .lnutil import (get_ecdh, privkey_to_pubkey, LightningPeerConnectionClosed,
HandshakeFailed, LNPeerAddr)
from . import ecc
from .util import bh2u, MySocksProxy
from .util import MySocksProxy
class HandshakeState(object):

26
electrum/lnutil.py

@ -11,7 +11,7 @@ import re
import attr
from aiorpcx import NetAddress
from .util import bfh, bh2u, inv_dict, UserFacingException
from .util import bfh, inv_dict, UserFacingException
from .util import list_enabled_bits
from .util import ShortID as ShortChannelID
from .util import format_short_id as format_short_channel_id
@ -430,7 +430,7 @@ class RevocationStore:
this_bucket = self.buckets[i]
e = shachain_derive(new_element, this_bucket.index)
if e != this_bucket:
raise Exception("hash is not derivable: {} {} {}".format(bh2u(e.secret), bh2u(this_bucket.secret), this_bucket.index))
raise Exception("hash is not derivable: {} {} {}".format(e.secret.hex(), this_bucket.secret.hex(), this_bucket.index))
self.buckets[bucket] = new_element
self.storage['index'] = index - 1
@ -474,7 +474,7 @@ def shachain_derive(element, to_index):
to_index)
ShachainElement = namedtuple("ShachainElement", ["secret", "index"])
ShachainElement.__str__ = lambda self: "ShachainElement(" + bh2u(self.secret) + "," + str(self.index) + ")"
ShachainElement.__str__ = lambda self: f"ShachainElement({self.secret.hex()},{self.index})"
def get_per_commitment_secret_from_seed(seed: bytes, i: int, bits: int = 48) -> bytes:
"""Generate per commitment secret."""
@ -528,7 +528,7 @@ def make_htlc_tx_output(amount_msat, local_feerate, revocationpubkey, local_dela
delayed_pubkey=local_delayedpubkey,
)
p2wsh = bitcoin.redeem_script_to_address('p2wsh', bh2u(script))
p2wsh = bitcoin.redeem_script_to_address('p2wsh', script.hex())
weight = HTLC_SUCCESS_WEIGHT if success else HTLC_TIMEOUT_WEIGHT
fee = local_feerate * weight
fee = fee // 1000 * 1000
@ -740,7 +740,7 @@ def possible_output_idxs_of_htlc_in_ctx(*, chan: 'Channel', pcp: bytes, subject:
local_htlc_pubkey=htlc_pubkey,
payment_hash=payment_hash,
cltv_expiry=cltv_expiry)
htlc_address = redeem_script_to_address('p2wsh', bh2u(preimage_script))
htlc_address = redeem_script_to_address('p2wsh', preimage_script.hex())
candidates = ctx.get_output_idxs_from_address(htlc_address)
return {output_idx for output_idx in candidates
if ctx.outputs()[output_idx].value == htlc.amount_msat // 1000}
@ -806,7 +806,7 @@ def make_htlc_tx_with_open_channel(*, chan: 'Channel', pcp: bytes, subject: 'HTL
htlc_tx_inputs = make_htlc_tx_inputs(
commit.txid(), ctx_output_idx,
amount_msat=amount_msat,
witness_script=bh2u(preimage_script))
witness_script=preimage_script.hex())
if is_htlc_success:
cltv_expiry = 0
htlc_tx = make_htlc_tx(cltv_expiry=cltv_expiry, inputs=htlc_tx_inputs, output=htlc_tx_output)
@ -814,7 +814,7 @@ def make_htlc_tx_with_open_channel(*, chan: 'Channel', pcp: bytes, subject: 'HTL
def make_funding_input(local_funding_pubkey: bytes, remote_funding_pubkey: bytes,
funding_pos: int, funding_txid: str, funding_sat: int) -> PartialTxInput:
pubkeys = sorted([bh2u(local_funding_pubkey), bh2u(remote_funding_pubkey)])
pubkeys = sorted([local_funding_pubkey.hex(), remote_funding_pubkey.hex()])
# commitment tx input
prevout = TxOutpoint(txid=bfh(funding_txid), out_idx=funding_pos)
c_input = PartialTxInput(prevout=prevout)
@ -859,7 +859,7 @@ def make_commitment_outputs(*, fees_per_participant: Mapping[HTLCOwner, int], lo
non_htlc_outputs = [to_local, to_remote]
htlc_outputs = []
for script, htlc in htlcs:
addr = bitcoin.redeem_script_to_address('p2wsh', bh2u(script))
addr = bitcoin.redeem_script_to_address('p2wsh', script.hex())
htlc_outputs.append(PartialTxOutput(scriptpubkey=bfh(address_to_script(addr)),
value=htlc.amount_msat // 1000))
@ -985,13 +985,13 @@ def make_commitment_output_to_local_witness_script(
def make_commitment_output_to_local_address(
revocation_pubkey: bytes, to_self_delay: int, delayed_pubkey: bytes) -> str:
local_script = make_commitment_output_to_local_witness_script(revocation_pubkey, to_self_delay, delayed_pubkey)
return bitcoin.redeem_script_to_address('p2wsh', bh2u(local_script))
return bitcoin.redeem_script_to_address('p2wsh', local_script.hex())
def make_commitment_output_to_remote_address(remote_payment_pubkey: bytes) -> str:
return bitcoin.pubkey_to_address('p2wpkh', bh2u(remote_payment_pubkey))
return bitcoin.pubkey_to_address('p2wpkh', remote_payment_pubkey.hex())
def sign_and_get_sig_string(tx: PartialTransaction, local_config, remote_config):
tx.sign({bh2u(local_config.multisig_key.pubkey): (local_config.multisig_key.privkey, True)})
tx.sign({local_config.multisig_key.pubkey.hex(): (local_config.multisig_key.privkey, True)})
sig = tx.inputs()[0].part_sigs[local_config.multisig_key.pubkey]
sig_64 = sig_string_from_der_sig(sig[:-1])
return sig_64
@ -1000,7 +1000,7 @@ def funding_output_script(local_config, remote_config) -> str:
return funding_output_script_from_keys(local_config.multisig_key.pubkey, remote_config.multisig_key.pubkey)
def funding_output_script_from_keys(pubkey1: bytes, pubkey2: bytes) -> str:
pubkeys = sorted([bh2u(pubkey1), bh2u(pubkey2)])
pubkeys = sorted([pubkey1.hex(), pubkey2.hex()])
return transaction.multisig_script(pubkeys, 2)
@ -1450,7 +1450,7 @@ def extract_nodeid(connect_contents: str) -> Tuple[bytes, str]:
# invoice?
invoice = lndecode(connect_contents)
nodeid_bytes = invoice.pubkey.serialize()
nodeid_hex = bh2u(nodeid_bytes)
nodeid_hex = nodeid_bytes.hex()
except:
# node id as hex?
nodeid_hex = connect_contents

4
electrum/lnverifier.py

@ -32,7 +32,7 @@ import aiorpcx
from . import bitcoin
from . import ecc
from . import constants
from .util import bh2u, bfh, NetworkJobOnDefaultServer
from .util import bfh, NetworkJobOnDefaultServer
from .lnutil import funding_output_script_from_keys, ShortChannelID
from .verifier import verify_tx_is_in_block, MerkleVerificationFailure
from .transaction import Transaction
@ -105,7 +105,7 @@ class LNChannelVerifier(NetworkJobOnDefaultServer):
continue
self.started_verifying_channel.add(short_channel_id)
await self.taskgroup.spawn(self.verify_channel(block_height, short_channel_id))
#self.logger.info(f'requested short_channel_id {bh2u(short_channel_id)}')
#self.logger.info(f'requested short_channel_id {short_channel_id.hex()}')
async def verify_channel(self, block_height: int, short_channel_id: ShortChannelID):
# we are verifying channel announcements as they are from untrusted ln peers.

4
electrum/lnwatcher.py

@ -11,7 +11,7 @@ from typing import NamedTuple, Dict
from . import util
from .sql_db import SqlDB, sql
from .wallet_db import WalletDB
from .util import bh2u, bfh, log_exceptions, ignore_exceptions, TxMinedInfo, random_shuffled_copy
from .util import bfh, log_exceptions, ignore_exceptions, TxMinedInfo, random_shuffled_copy
from .address_synchronizer import AddressSynchronizer, TX_HEIGHT_LOCAL, TX_HEIGHT_UNCONF_PARENT, TX_HEIGHT_UNCONFIRMED, TX_HEIGHT_FUTURE
from .transaction import Transaction, TxOutpoint
from .transaction import match_script_against_template
@ -69,7 +69,7 @@ class SweepStore(SqlDB):
def get_sweep_tx(self, funding_outpoint, prevout):
c = self.conn.cursor()
c.execute("SELECT tx FROM sweep_txs WHERE funding_outpoint=? AND prevout=?", (funding_outpoint, prevout))
return [Transaction(bh2u(r[0])) for r in c.fetchall()]
return [Transaction(r[0].hex()) for r in c.fetchall()]
@sql
def list_sweep_tx(self):

16
electrum/lnworker.py

@ -40,7 +40,7 @@ from .transaction import Transaction
from .transaction import get_script_type_from_output_script
from .crypto import sha256
from .bip32 import BIP32Node
from .util import bh2u, bfh, InvoiceError, resolve_dns_srv, is_ip_address, log_exceptions
from .util import bfh, InvoiceError, resolve_dns_srv, is_ip_address, log_exceptions
from .crypto import chacha20_encrypt, chacha20_decrypt
from .util import ignore_exceptions, make_aiohttp_session
from .util import timestamp_to_datetime, random_shuffled_copy
@ -499,12 +499,12 @@ class LNWorker(Logger, EventListener, NetworkRetryManager[LNPeerAddr]):
if self.uses_trampoline():
addr = trampolines_by_id().get(node_id)
if not addr:
raise ConnStringFormatError(_('Address unknown for node:') + ' ' + bh2u(node_id))
raise ConnStringFormatError(_('Address unknown for node:') + ' ' + node_id.hex())
host, port = addr.host, addr.port
else:
addrs = self.channel_db.get_node_addresses(node_id)
if not addrs:
raise ConnStringFormatError(_('Don\'t know any addresses for node:') + ' ' + bh2u(node_id))
raise ConnStringFormatError(_('Don\'t know any addresses for node:') + ' ' + node_id.hex())
host, port, timestamp = self.choose_preferred_address(list(addrs))
port = int(port)
# Try DNS-resolving the host (if needed). This is simply so that
@ -891,7 +891,7 @@ class LNWallet(LNWorker):
tx_height = self.wallet.adb.get_tx_height(funding_txid)
self._labels_cache[funding_txid] = _('Open channel') + ' ' + chan.get_id_for_log()
item = {
'channel_id': bh2u(chan.channel_id),
'channel_id': chan.channel_id.hex(),
'type': 'channel_opening',
'label': self.get_label_for_txid(funding_txid),
'txid': funding_txid,
@ -912,7 +912,7 @@ class LNWallet(LNWorker):
tx_height = self.wallet.adb.get_tx_height(closing_txid)
self._labels_cache[closing_txid] = _('Close channel') + ' ' + chan.get_id_for_log()
item = {
'channel_id': bh2u(chan.channel_id),
'channel_id': chan.channel_id.hex(),
'txid': closing_txid,
'label': self.get_label_for_txid(closing_txid),
'type': 'channel_closure',
@ -1309,7 +1309,7 @@ class LNWallet(LNWorker):
code, data = failure_msg.code, failure_msg.data
self.logger.info(f"UPDATE_FAIL_HTLC. code={repr(code)}. "
f"decoded_data={failure_msg.decode_data()}. data={data.hex()!r}")
self.logger.info(f"error reported by {bh2u(erring_node_id)}")
self.logger.info(f"error reported by {erring_node_id.hex()}")
if code == OnionFailureCode.MPP_TIMEOUT:
raise PaymentFailure(failure_msg.code_name())
# trampoline
@ -1847,12 +1847,12 @@ class LNWallet(LNWorker):
def save_preimage(self, payment_hash: bytes, preimage: bytes, *, write_to_disk: bool = True):
assert sha256(preimage) == payment_hash
self.preimages[bh2u(payment_hash)] = bh2u(preimage)
self.preimages[payment_hash.hex()] = preimage.hex()
if write_to_disk:
self.wallet.save_db()
def get_preimage(self, payment_hash: bytes) -> Optional[bytes]:
r = self.preimages.get(bh2u(payment_hash))
r = self.preimages.get(payment_hash.hex())
return bfh(r) if r else None
def get_payment_info(self, payment_hash: bytes) -> Optional[PaymentInfo]:

4
electrum/mnemonic.py

@ -30,7 +30,7 @@ import string
from typing import Sequence, Dict
from types import MappingProxyType
from .util import resource_path, bfh, bh2u, randrange
from .util import resource_path, bfh, randrange
from .crypto import hmac_oneshot
from . import version
from .logging import Logger
@ -224,7 +224,7 @@ class Mnemonic(Logger):
def is_new_seed(x: str, prefix=version.SEED_PREFIX) -> bool:
x = normalize_text(x)
s = bh2u(hmac_oneshot(b"Seed version", x.encode('utf8'), hashlib.sha512))
s = hmac_oneshot(b"Seed version", x.encode('utf8'), hashlib.sha512).hex()
return s.startswith(prefix)

2
electrum/paymentrequest.py

@ -39,7 +39,7 @@ except ImportError:
sys.exit("Error: could not find paymentrequest_pb2.py. Create it with 'contrib/generate_payreqpb2.sh'")
from . import bitcoin, constants, ecc, util, transaction, x509, rsakey
from .util import bh2u, bfh, make_aiohttp_session
from .util import bfh, make_aiohttp_session
from .invoices import Invoice, get_id_from_onchain_outputs
from .crypto import sha256
from .bitcoin import address_to_script

4
electrum/plugins/bitbox02/bitbox02.py

@ -10,7 +10,7 @@ from electrum.i18n import _
from electrum.keystore import Hardware_KeyStore
from electrum.transaction import PartialTransaction, Sighash
from electrum.wallet import Standard_Wallet, Multisig_Wallet, Deterministic_Wallet
from electrum.util import bh2u, UserFacingException
from electrum.util import UserFacingException
from electrum.base_wizard import ScriptTypeNotSupported, BaseWizard
from electrum.logging import get_logger
from electrum.plugin import Device, DeviceInfo, runs_in_hwd_thread
@ -524,7 +524,7 @@ class BitBox02Client(HardwareClientBase):
if len(sigs) != len(tx.inputs()):
raise Exception("Incorrect number of inputs signed.") # Should never occur
sighash = Sighash.to_sigbytes(Sighash.ALL).hex()
signatures = [bh2u(ecc.der_sig_from_sig_string(x[1])) + sighash for x in sigs]
signatures = [ecc.der_sig_from_sig_string(x[1]).hex() + sighash for x in sigs]
tx.update_signatures(signatures)
def sign_message(self, keypath: str, message: bytes, script_type: str) -> bytes:

2
electrum/plugins/coldcard/coldcard.py

@ -14,7 +14,7 @@ from electrum.plugin import Device, hook, runs_in_hwd_thread
from electrum.keystore import Hardware_KeyStore, KeyStoreWithMPK
from electrum.transaction import PartialTransaction
from electrum.wallet import Standard_Wallet, Multisig_Wallet, Abstract_Wallet
from electrum.util import bfh, bh2u, versiontuple, UserFacingException
from electrum.util import bfh, versiontuple, UserFacingException
from electrum.base_wizard import ScriptTypeNotSupported
from electrum.logging import get_logger

4
electrum/plugins/cosigner_pool/qt.py

@ -39,7 +39,7 @@ from electrum.bip32 import BIP32Node
from electrum.plugin import BasePlugin, hook
from electrum.i18n import _
from electrum.wallet import Multisig_Wallet, Abstract_Wallet
from electrum.util import bh2u, bfh
from electrum.util import bfh
from electrum.logging import Logger
from electrum.gui.qt.transaction_dialog import show_transaction, TxDialog
@ -156,7 +156,7 @@ class CosignerWallet(Logger):
for key, keystore in wallet.keystores.items():
xpub = keystore.get_master_public_key() # type: str
pubkey = BIP32Node.from_xkey(xpub).eckey.get_public_key_bytes(compressed=True)
_hash = bh2u(crypto.sha256d(pubkey))
_hash = crypto.sha256d(pubkey).hex()
if not keystore.is_watching_only():
self.keys.append((key, _hash))
else:

4
electrum/plugins/keepkey/keepkey.py

@ -3,7 +3,7 @@ import traceback
import sys
from typing import NamedTuple, Any, Optional, Dict, Union, List, Tuple, TYPE_CHECKING
from electrum.util import bfh, bh2u, UserCancelled, UserFacingException
from electrum.util import bfh, UserCancelled, UserFacingException
from electrum.bip32 import BIP32Node
from electrum import constants
from electrum.i18n import _
@ -331,7 +331,7 @@ class KeepKeyPlugin(HW_PluginBase):
signatures = client.sign_tx(self.get_coin_name(), inputs, outputs,
lock_time=tx.locktime, version=tx.version)[0]
sighash = Sighash.to_sigbytes(Sighash.ALL).hex()
signatures = [(bh2u(x) + sighash) for x in signatures]
signatures = [(x.hex() + sighash) for x in signatures]
tx.update_signatures(signatures)
@runs_in_hwd_thread

3
electrum/plugins/keepkey/qt.py

@ -12,7 +12,6 @@ from electrum.gui.qt.util import (WindowModalDialog, WWLabel, Buttons, CancelBut
OkButton, CloseButton)
from electrum.i18n import _
from electrum.plugin import hook
from electrum.util import bh2u
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
from ..hw_wallet.plugin import only_hook_if_libraries_available
@ -345,7 +344,7 @@ class SettingsDialog(WindowModalDialog):
def update(features):
self.features = features
set_label_enabled()
bl_hash = bh2u(features.bootloader_hash)
bl_hash = features.bootloader_hash.hex()
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
noyes = [_("No"), _("Yes")]
endis = [_("Enable Passphrases"), _("Disable Passphrases")]

4
electrum/plugins/revealer/revealer.py

@ -4,7 +4,7 @@ from hashlib import sha256
from typing import NamedTuple, Optional, Dict, Tuple
from electrum.plugin import BasePlugin
from electrum.util import to_bytes, bh2u, bfh
from electrum.util import to_bytes, bfh
from .hmac_drbg import DRBG
@ -92,7 +92,7 @@ class RevealerPlugin(BasePlugin):
@classmethod
def gen_random_versioned_seed(cls):
version = cls.LATEST_VERSION
hex_seed = bh2u(os.urandom(16))
hex_seed = os.urandom(16).hex()
checksum = cls.code_hashid(version + hex_seed)
return VersionedSeed(version=version.upper(),
seed=hex_seed.upper(),

3
electrum/plugins/safe_t/qt.py

@ -12,7 +12,6 @@ from electrum.gui.qt.util import (WindowModalDialog, WWLabel, Buttons, CancelBut
OkButton, CloseButton, getOpenFileName)
from electrum.i18n import _
from electrum.plugin import hook
from electrum.util import bh2u
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
from ..hw_wallet.plugin import only_hook_if_libraries_available
@ -221,7 +220,7 @@ class SettingsDialog(WindowModalDialog):
self.features = features
set_label_enabled()
if features.bootloader_hash:
bl_hash = bh2u(features.bootloader_hash)
bl_hash = features.bootloader_hash.hex()
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
else:
bl_hash = "N/A"

4
electrum/plugins/safe_t/safe_t.py

@ -3,7 +3,7 @@ import traceback
import sys
from typing import NamedTuple, Any, Optional, Dict, Union, List, Tuple, TYPE_CHECKING
from electrum.util import bfh, bh2u, versiontuple, UserCancelled, UserFacingException
from electrum.util import bfh, versiontuple, UserCancelled, UserFacingException
from electrum.bip32 import BIP32Node
from electrum import constants
from electrum.i18n import _
@ -301,7 +301,7 @@ class SafeTPlugin(HW_PluginBase):
signatures = client.sign_tx(self.get_coin_name(), inputs, outputs,
lock_time=tx.locktime, version=tx.version)[0]
sighash = Sighash.to_sigbytes(Sighash.ALL).hex()
signatures = [(bh2u(x) + sighash) for x in signatures]
signatures = [(x.hex() + sighash) for x in signatures]
tx.update_signatures(signatures)
@runs_in_hwd_thread

3
electrum/plugins/trezor/qt.py

@ -11,7 +11,6 @@ from electrum.gui.qt.util import (WindowModalDialog, WWLabel, Buttons, CancelBut
OkButton, CloseButton, PasswordLineEdit, getOpenFileName)
from electrum.i18n import _
from electrum.plugin import hook
from electrum.util import bh2u
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
from ..hw_wallet.plugin import only_hook_if_libraries_available
@ -487,7 +486,7 @@ class SettingsDialog(WindowModalDialog):
self.features = features
set_label_enabled()
if features.bootloader_hash:
bl_hash = bh2u(features.bootloader_hash)
bl_hash = features.bootloader_hash.hex()
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
else:
bl_hash = "N/A"

4
electrum/plugins/trezor/trezor.py

@ -2,7 +2,7 @@ import traceback
import sys
from typing import NamedTuple, Any, Optional, Dict, Union, List, Tuple, TYPE_CHECKING
from electrum.util import bfh, bh2u, versiontuple, UserCancelled, UserFacingException
from electrum.util import bfh, versiontuple, UserCancelled, UserFacingException
from electrum.bip32 import BIP32Node, convert_bip32_path_to_list_of_uint32 as parse_path
from electrum import constants
from electrum.i18n import _
@ -371,7 +371,7 @@ class TrezorPlugin(HW_PluginBase):
serialize=False,
prev_txes=prev_tx)
sighash = Sighash.to_sigbytes(Sighash.ALL).hex()
signatures = [(bh2u(x) + sighash) for x in signatures]
signatures = [(x.hex() + sighash) for x in signatures]
tx.update_signatures(signatures)
@runs_in_hwd_thread

6
electrum/scripts/ln_features.py

@ -14,7 +14,7 @@ from electrum.simple_config import SimpleConfig
from electrum import constants
from electrum.daemon import Daemon
from electrum.wallet import create_new_wallet
from electrum.util import create_and_start_event_loop, log_exceptions, bh2u, bfh
from electrum.util import create_and_start_event_loop, log_exceptions, bfh
from electrum.lnutil import LnFeatures
logger = get_logger(__name__)
@ -77,9 +77,9 @@ async def worker(work_queue: asyncio.Queue, results_queue: asyncio.Queue, flag):
# handle ipv4/ipv6
if ':' in addr[0]:
connect_str = f"{bh2u(work['pk'])}@[{addr.host}]:{addr.port}"
connect_str = f"{work['pk'].hex()}@[{addr.host}]:{addr.port}"
else:
connect_str = f"{bh2u(work['pk'])}@{addr.host}:{addr.port}"
connect_str = f"{work['pk'].hex()}@{addr.host}:{addr.port}"
print(f"worker connecting to {connect_str}")
try:

4
electrum/synchronizer.py

@ -32,7 +32,7 @@ from aiorpcx import run_in_thread, RPCError
from . import util
from .transaction import Transaction, PartialTransaction
from .util import bh2u, make_aiohttp_session, NetworkJobOnDefaultServer, random_shuffled_copy, OldTaskGroup
from .util import make_aiohttp_session, NetworkJobOnDefaultServer, random_shuffled_copy, OldTaskGroup
from .bitcoin import address_to_scripthash, is_address
from .logging import Logger
from .interface import GracefulDisconnect, NetworkTimeout
@ -51,7 +51,7 @@ def history_status(h):
status = ''
for tx_hash, height in h:
status += tx_hash + ':%d:' % height
return bh2u(hashlib.sha256(status.encode('ascii')).digest())
return hashlib.sha256(status.encode('ascii')).digest().hex()
class SynchronizerBase(NetworkJobOnDefaultServer):

20
electrum/tests/test_bitcoin.py

@ -18,7 +18,7 @@ from electrum.bip32 import (BIP32Node, convert_bip32_intpath_to_strpath,
normalize_bip32_derivation, is_all_public_derivation)
from electrum.crypto import sha256d, SUPPORTED_PW_HASH_VERSIONS
from electrum import ecc, crypto, constants
from electrum.util import bfh, bh2u, InvalidPassword, randrange
from electrum.util import bfh, InvalidPassword, randrange
from electrum.storage import WalletStorage
from electrum.keystore import xtype_from_derivation
@ -450,17 +450,17 @@ class Test_bitcoin(ElectrumTestCase):
def test_push_script(self):
# https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#push-operators
self.assertEqual(push_script(''), bh2u(bytes([opcodes.OP_0])))
self.assertEqual(push_script('07'), bh2u(bytes([opcodes.OP_7])))
self.assertEqual(push_script('10'), bh2u(bytes([opcodes.OP_16])))
self.assertEqual(push_script('81'), bh2u(bytes([opcodes.OP_1NEGATE])))
self.assertEqual(push_script(''), bytes([opcodes.OP_0]).hex())
self.assertEqual(push_script('07'), bytes([opcodes.OP_7]).hex())
self.assertEqual(push_script('10'), bytes([opcodes.OP_16]).hex())
self.assertEqual(push_script('81'), bytes([opcodes.OP_1NEGATE]).hex())
self.assertEqual(push_script('11'), '0111')
self.assertEqual(push_script(75 * '42'), '4b' + 75 * '42')
self.assertEqual(push_script(76 * '42'), bh2u(bytes([opcodes.OP_PUSHDATA1]) + bfh('4c' + 76 * '42')))
self.assertEqual(push_script(100 * '42'), bh2u(bytes([opcodes.OP_PUSHDATA1]) + bfh('64' + 100 * '42')))
self.assertEqual(push_script(255 * '42'), bh2u(bytes([opcodes.OP_PUSHDATA1]) + bfh('ff' + 255 * '42')))
self.assertEqual(push_script(256 * '42'), bh2u(bytes([opcodes.OP_PUSHDATA2]) + bfh('0001' + 256 * '42')))
self.assertEqual(push_script(520 * '42'), bh2u(bytes([opcodes.OP_PUSHDATA2]) + bfh('0802' + 520 * '42')))
self.assertEqual(push_script(76 * '42'), (bytes([opcodes.OP_PUSHDATA1]) + bfh('4c' + 76 * '42')).hex())
self.assertEqual(push_script(100 * '42'), (bytes([opcodes.OP_PUSHDATA1]) + bfh('64' + 100 * '42')).hex())
self.assertEqual(push_script(255 * '42'), (bytes([opcodes.OP_PUSHDATA1]) + bfh('ff' + 255 * '42')).hex())
self.assertEqual(push_script(256 * '42'), (bytes([opcodes.OP_PUSHDATA2]) + bfh('0001' + 256 * '42')).hex())
self.assertEqual(push_script(520 * '42'), (bytes([opcodes.OP_PUSHDATA2]) + bfh('0802' + 520 * '42')).hex())
def test_add_number_to_script(self):
# https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#numbers

2
electrum/tests/test_blockchain.py

@ -5,7 +5,7 @@ import os
from electrum import constants, blockchain
from electrum.simple_config import SimpleConfig
from electrum.blockchain import Blockchain, deserialize_header, hash_header
from electrum.util import bh2u, bfh, make_dir
from electrum.util import bfh, make_dir
from . import ElectrumTestCase

4
electrum/tests/test_lnpeer.py

@ -23,7 +23,7 @@ from electrum.ecc import ECPrivkey
from electrum import simple_config, lnutil
from electrum.lnaddr import lnencode, LnAddr, lndecode
from electrum.bitcoin import COIN, sha256
from electrum.util import bh2u, NetworkRetryManager, bfh, OldTaskGroup, EventListener
from electrum.util import NetworkRetryManager, bfh, OldTaskGroup, EventListener
from electrum.lnpeer import Peer
from electrum.lnutil import LNPeerAddr, Keypair, privkey_to_pubkey
from electrum.lnutil import PaymentFailure, LnFeatures, HTLCOwner
@ -1377,7 +1377,7 @@ class TestPeer(TestCaseForTestnet):
# create upfront shutdown script for bob, alice doesn't use upfront
# shutdown script
bob_uss_pub = lnutil.privkey_to_pubkey(os.urandom(32))
bob_uss_addr = bitcoin.pubkey_to_address('p2wpkh', bh2u(bob_uss_pub))
bob_uss_addr = bitcoin.pubkey_to_address('p2wpkh', bob_uss_pub.hex())
bob_uss = bfh(bitcoin.address_to_script(bob_uss_addr))
# bob commits to close to bob_uss

2
electrum/tests/test_lnrouter.py

@ -5,7 +5,7 @@ import shutil
import asyncio
from electrum import util
from electrum.util import bh2u, bfh
from electrum.util import bfh
from electrum.lnutil import ShortChannelID
from electrum.lnonion import (OnionHopsDataSingle, new_onion_packet,
process_onion_packet, _decode_onion_error, decode_onion_error,

6
electrum/tests/test_lnutil.py

@ -10,7 +10,7 @@ from electrum.lnutil import (RevocationStore, get_per_commitment_secret_from_see
get_compressed_pubkey_from_bech32, split_host_port, ConnStringFormatError,
ScriptHtlc, extract_nodeid, calc_fees_for_commitment_tx, UpdateAddHtlc, LnFeatures,
ln_compare_features, IncompatibleLightningFeatures, ChannelType)
from electrum.util import bh2u, bfh, MyEncoder
from electrum.util import bfh, MyEncoder
from electrum.transaction import Transaction, PartialTransaction, Sighash
from electrum.lnworker import LNWallet
@ -575,7 +575,7 @@ class TestLNUtil(ElectrumTestCase):
htlc_output_txid=our_commit_tx.txid(),
htlc_output_index=htlc_output_index,
amount_msat=amount_msat,
witness_script=bh2u(htlc))
witness_script=htlc.hex())
our_htlc_tx = make_htlc_tx(
cltv_expiry=cltv_timeout,
inputs=our_htlc_tx_inputs,
@ -724,7 +724,7 @@ class TestLNUtil(ElectrumTestCase):
assert type(privkey) is bytes
assert len(pubkey) == 33
assert len(privkey) == 33
tx.sign({bh2u(pubkey): (privkey[:-1], True)})
tx.sign({pubkey.hex(): (privkey[:-1], True)})
sighash = Sighash.to_sigbytes(Sighash.ALL).hex()
tx.add_signature_to_txin(txin_idx=0, signing_pubkey=remote_pubkey.hex(), sig=remote_signature + sighash)

10
electrum/tests/test_mnemonic.py

@ -6,7 +6,7 @@ from electrum import keystore
from electrum import mnemonic
from electrum import slip39
from electrum import old_mnemonic
from electrum.util import bh2u, bfh
from electrum.util import bfh
from electrum.mnemonic import is_new_seed, is_old_seed, seed_type
from electrum.version import SEED_PREFIX_SW, SEED_PREFIX
@ -104,20 +104,20 @@ class Test_NewMnemonic(ElectrumTestCase):
# note: not a valid electrum seed
seed = mnemonic.Mnemonic.mnemonic_to_seed(mnemonic='foobar', passphrase='none')
self.assertEqual('741b72fd15effece6bfe5a26a52184f66811bd2be363190e07a42cca442b1a5bb22b3ad0eb338197287e6d314866c7fba863ac65d3f156087a5052ebc7157fce',
bh2u(seed))
seed.hex())
def test_mnemonic_to_seed(self):
for test_name, test in SEED_TEST_CASES.items():
if test.words_hex is not None:
self.assertEqual(test.words_hex, bh2u(test.words.encode('utf8')), msg=test_name)
self.assertEqual(test.words_hex, test.words.encode('utf8').hex(), msg=test_name)
self.assertTrue(is_new_seed(test.words, prefix=test.seed_version), msg=test_name)
m = mnemonic.Mnemonic(lang=test.lang)
if test.entropy is not None:
self.assertEqual(test.entropy, m.mnemonic_decode(test.words), msg=test_name)
if test.passphrase_hex is not None:
self.assertEqual(test.passphrase_hex, bh2u(test.passphrase.encode('utf8')), msg=test_name)
self.assertEqual(test.passphrase_hex, test.passphrase.encode('utf8').hex(), msg=test_name)
seed = mnemonic.Mnemonic.mnemonic_to_seed(mnemonic=test.words, passphrase=test.passphrase)
self.assertEqual(test.bip32_seed, bh2u(seed), msg=test_name)
self.assertEqual(test.bip32_seed, seed.hex(), msg=test_name)
def test_random_seeds(self):
iters = 10

3
electrum/tests/test_network.py

@ -7,7 +7,6 @@ from electrum.simple_config import SimpleConfig
from electrum import blockchain
from electrum.interface import Interface, ServerAddr
from electrum.crypto import sha256
from electrum.util import bh2u
from electrum import util
from . import ElectrumTestCase
@ -105,7 +104,7 @@ class TestNetwork(ElectrumTestCase):
def mock_fork(self, bad_header):
forkpoint = bad_header['block_height']
b = blockchain.Blockchain(config=self.config, forkpoint=forkpoint, parent=None,
forkpoint_hash=bh2u(sha256(str(forkpoint))), prev_hash=bh2u(sha256(str(forkpoint-1))))
forkpoint_hash=sha256(str(forkpoint)).hex(), prev_hash=sha256(str(forkpoint-1)).hex())
return b
def test_chain_false_during_binary(self):

4
electrum/tests/test_transaction.py

@ -5,7 +5,7 @@ from electrum.transaction import (convert_raw_tx_to_hex, tx_from_any, Transactio
PartialTransaction, TxOutpoint, PartialTxInput,
PartialTxOutput, Sighash, match_script_against_template,
SCRIPTPUBKEY_TEMPLATE_ANYSEGWIT)
from electrum.util import bh2u, bfh
from electrum.util import bfh
from electrum.bitcoin import (deserialize_privkey, opcodes,
construct_script, construct_witness)
from electrum.ecc import ECPrivkey
@ -30,7 +30,7 @@ class TestBCDataStream(ElectrumTestCase):
with self.assertRaises(transaction.SerializationError):
s.write_compact_size(-1)
self.assertEqual(bh2u(s.input),
self.assertEqual(s.input.hex(),
'0001fcfdfd00fdfffffe00000100feffffffffff0000000001000000ffffffffffffffffff')
for v in values:
self.assertEqual(s.read_compact_size(), v)

6
electrum/tests/test_wallet_vertical.py

@ -14,7 +14,7 @@ from electrum.address_synchronizer import TX_HEIGHT_UNCONFIRMED, TX_HEIGHT_UNCON
from electrum.wallet import (sweep, Multisig_Wallet, Standard_Wallet, Imported_Wallet,
restore_wallet_from_text, Abstract_Wallet)
from electrum.util import (
bfh, bh2u, NotEnoughFunds, UnrelatedTransactionException,
bfh, NotEnoughFunds, UnrelatedTransactionException,
UserFacingException)
from electrum.transaction import (TxOutput, Transaction, PartialTransaction, PartialTxOutput,
PartialTxInput, tx_from_any, TxOutpoint)
@ -445,7 +445,7 @@ class TestWalletKeystoreAddressIntegrityForMainnet(ElectrumTestCase):
self.assertEqual(keystore.bip39_is_checksum_valid(seed_words), (True, True))
bip32_seed = keystore.bip39_to_seed(seed_words, '')
self.assertEqual('0df68c16e522eea9c1d8e090cfb2139c3b3a2abed78cbcb3e20be2c29185d3b8df4e8ce4e52a1206a688aeb88bfee249585b41a7444673d1f16c0d45755fa8b9',
bh2u(bip32_seed))
bip32_seed.hex())
def create_keystore_from_bip32seed(xtype):
ks = keystore.BIP32_KeyStore({})
@ -643,7 +643,7 @@ class TestWalletKeystoreAddressIntegrityForTestnet(TestCaseForTestnet):
self.assertEqual(keystore.bip39_is_checksum_valid(seed_words), (True, True))
bip32_seed = keystore.bip39_to_seed(seed_words, '')
self.assertEqual('0df68c16e522eea9c1d8e090cfb2139c3b3a2abed78cbcb3e20be2c29185d3b8df4e8ce4e52a1206a688aeb88bfee249585b41a7444673d1f16c0d45755fa8b9',
bh2u(bip32_seed))
bip32_seed.hex())
def create_keystore_from_bip32seed(xtype):
ks = keystore.BIP32_KeyStore({})

20
electrum/transaction.py

@ -42,7 +42,7 @@ import copy
from . import ecc, bitcoin, constants, segwit_addr, bip32
from .bip32 import BIP32Node
from .util import profiler, to_bytes, bh2u, bfh, chunks, is_hex_str, parse_max_spend
from .util import profiler, to_bytes, bfh, chunks, is_hex_str, parse_max_spend
from .bitcoin import (TYPE_ADDRESS, TYPE_SCRIPT, hash_160,
hash160_to_p2sh, hash160_to_p2pkh, hash_to_segwit_addr,
var_int, TOTAL_COIN_SUPPLY_LIMIT_IN_BTC, COIN,
@ -650,7 +650,7 @@ class Transaction:
self._cached_network_ser = raw.strip() if raw else None
assert is_hex_str(self._cached_network_ser)
elif isinstance(raw, (bytes, bytearray)):
self._cached_network_ser = bh2u(raw)
self._cached_network_ser = raw.hex()
else:
raise Exception(f"cannot initialize transaction from {raw}")
self._inputs = None # type: List[TxInput]
@ -863,7 +863,7 @@ class Transaction:
return multisig_script(pubkeys, txin.num_sig)
elif txin.script_type in ['p2pkh', 'p2wpkh', 'p2wpkh-p2sh']:
pubkey = pubkeys[0]
pkh = bh2u(hash_160(bfh(pubkey)))
pkh = hash_160(bfh(pubkey)).hex()
return bitcoin.pubkeyhash_to_p2pkh_script(pkh)
elif txin.script_type == 'p2pk':
pubkey = pubkeys[0]
@ -874,9 +874,9 @@ class Transaction:
def _calc_bip143_shared_txdigest_fields(self) -> BIP143SharedTxDigestFields:
inputs = self.inputs()
outputs = self.outputs()
hashPrevouts = bh2u(sha256d(b''.join(txin.prevout.serialize_to_network() for txin in inputs)))
hashSequence = bh2u(sha256d(bfh(''.join(int_to_hex(txin.nsequence, 4) for txin in inputs))))
hashOutputs = bh2u(sha256d(bfh(''.join(o.serialize_to_network().hex() for o in outputs))))
hashPrevouts = sha256d(b''.join(txin.prevout.serialize_to_network() for txin in inputs)).hex()
hashSequence = sha256d(bfh(''.join(int_to_hex(txin.nsequence, 4) for txin in inputs))).hex()
hashOutputs = sha256d(bfh(''.join(o.serialize_to_network().hex() for o in outputs))).hex()
return BIP143SharedTxDigestFields(hashPrevouts=hashPrevouts,
hashSequence=hashSequence,
hashOutputs=hashOutputs)
@ -949,7 +949,7 @@ class Transaction:
except UnknownTxinType:
# we might not know how to construct scriptSig for some scripts
return None
self._cached_txid = bh2u(sha256d(bfh(ser))[::-1])
self._cached_txid = sha256d(bfh(ser))[::-1].hex()
return self._cached_txid
def wtxid(self) -> Optional[str]:
@ -961,7 +961,7 @@ class Transaction:
except UnknownTxinType:
# we might not know how to construct scriptSig/witness for some scripts
return None
return bh2u(sha256d(bfh(ser))[::-1])
return sha256d(bfh(ser))[::-1].hex()
def add_info_from_wallet(self, wallet: 'Abstract_Wallet', **kwargs) -> None:
return # no-op
@ -1963,7 +1963,7 @@ class PartialTransaction(Transaction):
if (sighash & 0x1f) != Sighash.SINGLE and (sighash & 0x1f) != Sighash.NONE:
hashOutputs = bip143_shared_txdigest_fields.hashOutputs
elif (sighash & 0x1f) == Sighash.SINGLE and txin_index < len(outputs):
hashOutputs = bh2u(sha256d(outputs[txin_index].serialize_to_network()))
hashOutputs = sha256d(outputs[txin_index].serialize_to_network()).hex()
else:
hashOutputs = '00' * 32
outpoint = txin.prevout.serialize_to_network().hex()
@ -2006,7 +2006,7 @@ class PartialTransaction(Transaction):
bip143_shared_txdigest_fields=bip143_shared_txdigest_fields)))
privkey = ecc.ECPrivkey(privkey_bytes)
sig = privkey.sign_transaction(pre_hash)
sig = bh2u(sig) + Sighash.to_sigbytes(sighash).hex()
sig = sig.hex() + Sighash.to_sigbytes(sighash).hex()
return sig
def is_complete(self) -> bool:

13
electrum/util.py

@ -585,17 +585,6 @@ def to_bytes(something, encoding='utf8') -> bytes:
bfh = bytes.fromhex
def bh2u(x: bytes) -> str:
"""
str with hex representation of a bytes-like object
>>> x = bytes((1, 2, 10))
>>> bh2u(x)
'01020A'
"""
return x.hex()
def xor_bytes(a: bytes, b: bytes) -> bytes:
size = min(len(a), len(b))
return ((int.from_bytes(a[:size], "big") ^ int.from_bytes(b[:size], "big"))
@ -1036,7 +1025,7 @@ def parse_URI(uri: str, on_pr: Callable = None, *, loop=None) -> dict:
raise InvalidBitcoinURI(f"failed to parse 'exp' field: {repr(e)}") from e
if 'sig' in out:
try:
out['sig'] = bh2u(bitcoin.base_decode(out['sig'], base=58))
out['sig'] = bitcoin.base_decode(out['sig'], base=58).hex()
except Exception as e:
raise InvalidBitcoinURI(f"failed to parse 'sig' field: {repr(e)}") from e
if 'lightning' in out:

4
electrum/verifier.py

@ -26,7 +26,7 @@ from typing import Sequence, Optional, TYPE_CHECKING
import aiorpcx
from .util import bh2u, TxMinedInfo, NetworkJobOnDefaultServer
from .util import TxMinedInfo, NetworkJobOnDefaultServer
from .crypto import sha256d
from .bitcoin import hash_decode, hash_encode
from .transaction import Transaction
@ -153,7 +153,7 @@ class SPV(NetworkJobOnDefaultServer):
if len(item) != 32:
raise MerkleVerificationFailure('all merkle branch items have to 32 bytes long')
inner_node = (item + h) if (index & 1) else (h + item)
cls._raise_if_valid_tx(bh2u(inner_node))
cls._raise_if_valid_tx(inner_node.hex())
h = sha256d(inner_node)
index >>= 1
if index != 0:

2
electrum/wallet.py

@ -57,7 +57,7 @@ from .util import (NotEnoughFunds, UserCancelled, profiler, OldTaskGroup, ignore
format_satoshis, format_fee_satoshis, NoDynamicFeeEstimates,
WalletFileException, BitcoinException,
InvalidPassword, format_time, timestamp_to_datetime, Satoshis,
Fiat, bfh, bh2u, TxMinedInfo, quantize_feerate, create_bip21_uri, OrderedDictWithIndex, parse_max_spend)
Fiat, bfh, TxMinedInfo, quantize_feerate, create_bip21_uri, OrderedDictWithIndex, parse_max_spend)
from .simple_config import SimpleConfig, FEE_RATIO_HIGH_WARNING, FEERATE_WARNING_HIGH_FEE
from .bitcoin import COIN, TYPE_ADDRESS
from .bitcoin import is_address, address_to_script, is_minikey, relayfee, dust_threshold

6
electrum/x509.py

@ -28,7 +28,7 @@ import time
from datetime import datetime
from . import util
from .util import profiler, bh2u
from .util import profiler
from .logging import get_logger
@ -272,10 +272,10 @@ class X509(object):
# Subject Key Identifier
r = value.root()
value = value.get_value_of_type(r, 'OCTET STRING')
self.SKI = bh2u(value)
self.SKI = value.hex()
elif oid == '2.5.29.35':
# Authority Key Identifier
self.AKI = bh2u(value.get_sequence()[0])
self.AKI = value.get_sequence()[0].hex()
else:
pass

Loading…
Cancel
Save