util: kill bh2u
no longer useful, and the name is so confusing...
This commit is contained in:
+1
-1
@@ -5,7 +5,7 @@
|
|||||||
import hashlib
|
import hashlib
|
||||||
from typing import List, Tuple, NamedTuple, Union, Iterable, Sequence, Optional
|
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 constants
|
||||||
from . import ecc
|
from . import ecc
|
||||||
from .crypto import hash_160, hmac_oneshot
|
from .crypto import hash_160, hmac_oneshot
|
||||||
|
|||||||
+10
-10
@@ -28,7 +28,7 @@ from typing import List, Tuple, TYPE_CHECKING, Optional, Union, Sequence
|
|||||||
import enum
|
import enum
|
||||||
from enum import IntEnum, 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 version
|
||||||
from . import segwit_addr
|
from . import segwit_addr
|
||||||
from . import constants
|
from . import constants
|
||||||
@@ -198,7 +198,7 @@ class opcodes(IntEnum):
|
|||||||
|
|
||||||
|
|
||||||
def rev_hex(s: str) -> str:
|
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:
|
def int_to_hex(i: int, length: int=1) -> str:
|
||||||
@@ -238,7 +238,7 @@ def script_num_to_hex(i: int) -> str:
|
|||||||
elif neg:
|
elif neg:
|
||||||
result[-1] |= 0x80
|
result[-1] |= 0x80
|
||||||
|
|
||||||
return bh2u(result)
|
return result.hex()
|
||||||
|
|
||||||
|
|
||||||
def var_int(i: int) -> str:
|
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:
|
if data_len == 0 or data_len == 1 and data[0] == 0:
|
||||||
return opcodes.OP_0.hex()
|
return opcodes.OP_0.hex()
|
||||||
elif data_len == 1 and data[0] <= 16:
|
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:
|
elif data_len == 1 and data[0] == 0x81:
|
||||||
return opcodes.OP_1NEGATE.hex()
|
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:
|
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:
|
if type(item) is int:
|
||||||
item = script_num_to_hex(item)
|
item = script_num_to_hex(item)
|
||||||
elif isinstance(item, (bytes, bytearray)):
|
elif isinstance(item, (bytes, bytearray)):
|
||||||
item = bh2u(item)
|
item = item.hex()
|
||||||
else:
|
else:
|
||||||
assert is_hex_str(item)
|
assert is_hex_str(item)
|
||||||
witness += witness_push(item)
|
witness += witness_push(item)
|
||||||
@@ -366,7 +366,7 @@ def dust_threshold(network: 'Network' = None) -> int:
|
|||||||
|
|
||||||
|
|
||||||
def hash_encode(x: bytes) -> str:
|
def hash_encode(x: bytes) -> str:
|
||||||
return bh2u(x[::-1])
|
return x[::-1].hex()
|
||||||
|
|
||||||
|
|
||||||
def hash_decode(x: str) -> bytes:
|
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)])
|
return construct_script([witver, bytes(witprog)])
|
||||||
addrtype, hash_160_ = b58_address_to_hash160(addr)
|
addrtype, hash_160_ = b58_address_to_hash160(addr)
|
||||||
if addrtype == net.ADDRTYPE_P2PKH:
|
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:
|
elif addrtype == net.ADDRTYPE_P2SH:
|
||||||
script = construct_script([opcodes.OP_HASH160, hash_160_, opcodes.OP_EQUAL])
|
script = construct_script([opcodes.OP_HASH160, hash_160_, opcodes.OP_EQUAL])
|
||||||
else:
|
else:
|
||||||
@@ -519,7 +519,7 @@ def address_to_scripthash(addr: str, *, net=None) -> str:
|
|||||||
|
|
||||||
def script_to_scripthash(script: str) -> str:
|
def script_to_scripthash(script: str) -> str:
|
||||||
h = sha256(bfh(script))[0:32]
|
h = sha256(bfh(script))[0:32]
|
||||||
return bh2u(bytes(reversed(h)))
|
return h[::-1].hex()
|
||||||
|
|
||||||
def public_key_to_p2pk_script(pubkey: str) -> str:
|
def public_key_to_p2pk_script(pubkey: str) -> str:
|
||||||
return construct_script([pubkey, opcodes.OP_CHECKSIG])
|
return construct_script([pubkey, opcodes.OP_CHECKSIG])
|
||||||
@@ -613,7 +613,7 @@ def DecodeBase58Check(psz: Union[bytes, str]) -> bytes:
|
|||||||
csum_found = vchRet[-4:]
|
csum_found = vchRet[-4:]
|
||||||
csum_calculated = sha256d(payload)[0:4]
|
csum_calculated = sha256d(payload)[0:4]
|
||||||
if csum_calculated != csum_found:
|
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:
|
else:
|
||||||
return payload
|
return payload
|
||||||
|
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ from . import util
|
|||||||
from .bitcoin import hash_encode, int_to_hex, rev_hex
|
from .bitcoin import hash_encode, int_to_hex, rev_hex
|
||||||
from .crypto import sha256d
|
from .crypto import sha256d
|
||||||
from . import constants
|
from . import constants
|
||||||
from .util import bfh, bh2u, with_lock
|
from .util import bfh, with_lock
|
||||||
from .simple_config import SimpleConfig
|
from .simple_config import SimpleConfig
|
||||||
from .logging import get_logger, Logger
|
from .logging import get_logger, Logger
|
||||||
|
|
||||||
@@ -408,7 +408,7 @@ class Blockchain(Logger):
|
|||||||
# swap parameters
|
# swap parameters
|
||||||
self.parent, parent.parent = parent.parent, self # type: Optional[Blockchain], Optional[Blockchain]
|
self.parent, parent.parent = parent.parent, self # type: Optional[Blockchain], Optional[Blockchain]
|
||||||
self.forkpoint, parent.forkpoint = parent.forkpoint, self.forkpoint
|
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
|
self._prev_hash, parent._prev_hash = parent._prev_hash, self._prev_hash
|
||||||
# parent's new name
|
# parent's new name
|
||||||
os.replace(child_old_name, parent.path())
|
os.replace(child_old_name, parent.path())
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ from aiorpcx import NetAddress
|
|||||||
|
|
||||||
from .sql_db import SqlDB, sql
|
from .sql_db import SqlDB, sql
|
||||||
from . import constants, util
|
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 .logging import Logger
|
||||||
from .lnutil import (LNPeerAddr, format_short_channel_id, ShortChannelID,
|
from .lnutil import (LNPeerAddr, format_short_channel_id, ShortChannelID,
|
||||||
validate_features, IncompatibleOrInsaneFeatures, InvalidGossipMsg)
|
validate_features, IncompatibleOrInsaneFeatures, InvalidGossipMsg)
|
||||||
@@ -396,7 +396,7 @@ class ChannelDB(SqlDB):
|
|||||||
if short_channel_id in self._channels:
|
if short_channel_id in self._channels:
|
||||||
continue
|
continue
|
||||||
if constants.net.rev_genesis_bytes() != msg['chain_hash']:
|
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
|
continue
|
||||||
try:
|
try:
|
||||||
channel_info = ChannelInfo.from_msg(msg)
|
channel_info = ChannelInfo.from_msg(msg)
|
||||||
|
|||||||
@@ -41,7 +41,7 @@ from typing import Optional, TYPE_CHECKING, Dict, List
|
|||||||
import os
|
import os
|
||||||
|
|
||||||
from .import util, ecc
|
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)
|
is_hash256_str, is_hex_str, to_bytes, parse_max_spend)
|
||||||
from . import bitcoin
|
from . import bitcoin
|
||||||
from .bitcoin import is_address, hash_160, COIN
|
from .bitcoin import is_address, hash_160, COIN
|
||||||
@@ -1126,7 +1126,7 @@ class Commands:
|
|||||||
@command('wl')
|
@command('wl')
|
||||||
async def nodeid(self, wallet: Abstract_Wallet = None):
|
async def nodeid(self, wallet: Abstract_Wallet = None):
|
||||||
listen_addr = self.config.get('lightning_listen')
|
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')
|
@command('wl')
|
||||||
async def list_channels(self, wallet: Abstract_Wallet = None):
|
async def list_channels(self, wallet: Abstract_Wallet = None):
|
||||||
@@ -1142,7 +1142,7 @@ class Commands:
|
|||||||
'channel_point': chan.funding_outpoint.to_str(),
|
'channel_point': chan.funding_outpoint.to_str(),
|
||||||
'state': chan.get_state().name,
|
'state': chan.get_state().name,
|
||||||
'peer_state': chan.peer_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,
|
'local_balance': chan.balance(LOCAL)//1000,
|
||||||
'remote_balance': chan.balance(REMOTE)//1000,
|
'remote_balance': chan.balance(REMOTE)//1000,
|
||||||
'local_ctn': chan.get_latest_ctn(LOCAL),
|
'local_ctn': chan.get_latest_ctn(LOCAL),
|
||||||
|
|||||||
+2
-2
@@ -32,7 +32,7 @@ from ctypes import (
|
|||||||
CFUNCTYPE, POINTER, cast
|
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 .crypto import (sha256d, aes_encrypt_with_iv, aes_decrypt_with_iv, hmac_oneshot)
|
||||||
from . import constants
|
from . import constants
|
||||||
from .logging import get_logger
|
from .logging import get_logger
|
||||||
@@ -221,7 +221,7 @@ class ECPubkey(object):
|
|||||||
return header + x + y
|
return header + x + y
|
||||||
|
|
||||||
def get_public_key_hex(self, compressed=True) -> str:
|
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]]:
|
def point(self) -> Tuple[Optional[int], Optional[int]]:
|
||||||
x = self.x()
|
x = self.x()
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ from kivy.lang import Builder
|
|||||||
from kivy.factory import Factory
|
from kivy.factory import Factory
|
||||||
from kivy.uix.popup import Popup
|
from kivy.uix.popup import Popup
|
||||||
|
|
||||||
from electrum.util import bh2u
|
|
||||||
from electrum.logging import Logger
|
from electrum.logging import Logger
|
||||||
from electrum.lnutil import LOCAL, REMOTE, format_short_channel_id
|
from electrum.lnutil import LOCAL, REMOTE, format_short_channel_id
|
||||||
from electrum.lnchannel import AbstractChannel, Channel, ChannelState, ChanCloseOption
|
from electrum.lnchannel import AbstractChannel, Channel, ChannelState, ChanCloseOption
|
||||||
@@ -465,8 +464,8 @@ class ChannelDetailsPopup(Popup, Logger):
|
|||||||
self.app = app
|
self.app = app
|
||||||
self.chan = chan
|
self.chan = chan
|
||||||
self.title = _('Channel details')
|
self.title = _('Channel details')
|
||||||
self.node_id = bh2u(chan.node_id)
|
self.node_id = chan.node_id.hex()
|
||||||
self.channel_id = bh2u(chan.channel_id)
|
self.channel_id = chan.channel_id.hex()
|
||||||
self.funding_txid = chan.funding_outpoint.txid
|
self.funding_txid = chan.funding_outpoint.txid
|
||||||
self.short_id = format_short_channel_id(chan.short_channel_id)
|
self.short_id = format_short_channel_id(chan.short_channel_id)
|
||||||
self.capacity = self.app.format_amount_and_units(chan.get_capacity())
|
self.capacity = self.app.format_amount_and_units(chan.get_capacity())
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ from kivy.factory import Factory
|
|||||||
from electrum.gui import messages
|
from electrum.gui import messages
|
||||||
from electrum.gui.kivy.i18n import _
|
from electrum.gui.kivy.i18n import _
|
||||||
from electrum.lnaddr import lndecode
|
from electrum.lnaddr import lndecode
|
||||||
from electrum.util import bh2u
|
|
||||||
from electrum.bitcoin import COIN
|
from electrum.bitcoin import COIN
|
||||||
import electrum.simple_config as config
|
import electrum.simple_config as config
|
||||||
from electrum.logging import Logger
|
from electrum.logging import Logger
|
||||||
@@ -150,7 +149,7 @@ class LightningOpenChannelDialog(Factory.Popup, Logger):
|
|||||||
if not fee:
|
if not fee:
|
||||||
fee = config.FEERATE_FALLBACK_STATIC_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.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:
|
if self.msg:
|
||||||
self.app.show_info(self.msg)
|
self.app.show_info(self.msg)
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from PyQt5.QtWidgets import QLabel, QLineEdit, QHBoxLayout, QGridLayout
|
|||||||
|
|
||||||
from electrum.util import EventListener
|
from electrum.util import EventListener
|
||||||
from electrum.i18n import _
|
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.lnutil import format_short_channel_id, LOCAL, REMOTE, UpdateAddHtlc, Direction
|
||||||
from electrum.lnchannel import htlcsum, Channel, AbstractChannel, HTLCWithStatus
|
from electrum.lnchannel import htlcsum, Channel, AbstractChannel, HTLCWithStatus
|
||||||
from electrum.lnaddr import LnAddr, lndecode
|
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 = 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(_('Amount')),HTLCItem(self.format_msat(i.amount_msat))])
|
||||||
it.appendRow([HTLCItem(_('CLTV expiry')),HTLCItem(str(i.cltv_expiry))])
|
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
|
return it
|
||||||
|
|
||||||
def make_model(self, htlcs: Sequence[HTLCWithStatus]) -> QtGui.QStandardItemModel:
|
def make_model(self, htlcs: Sequence[HTLCWithStatus]) -> QtGui.QStandardItemModel:
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ from PyQt5.QtWidgets import (QMenu, QHBoxLayout, QLabel, QVBoxLayout, QGridLayou
|
|||||||
QToolTip)
|
QToolTip)
|
||||||
from PyQt5.QtGui import QFont, QStandardItem, QBrush, QPainter, QIcon, QHelpEvent
|
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.i18n import _
|
||||||
from electrum.lnchannel import AbstractChannel, PeerState, ChannelBackup, Channel, ChannelState, ChanCloseOption
|
from electrum.lnchannel import AbstractChannel, PeerState, ChannelBackup, Channel, ChannelState, ChanCloseOption
|
||||||
from electrum.wallet import Abstract_Wallet
|
from electrum.wallet import Abstract_Wallet
|
||||||
|
|||||||
@@ -57,7 +57,7 @@ from electrum.plugin import run_hook, BasePlugin
|
|||||||
from electrum.i18n import _
|
from electrum.i18n import _
|
||||||
from electrum.util import (format_time, get_asyncio_loop,
|
from electrum.util import (format_time, get_asyncio_loop,
|
||||||
UserCancelled, profiler,
|
UserCancelled, profiler,
|
||||||
bh2u, bfh, InvalidPassword,
|
bfh, InvalidPassword,
|
||||||
UserFacingException, FailedToParsePaymentIdentifier,
|
UserFacingException, FailedToParsePaymentIdentifier,
|
||||||
get_new_wallet_name, send_exception_to_crash_reporter,
|
get_new_wallet_name, send_exception_to_crash_reporter,
|
||||||
AddTransactionException, BITCOIN_BIP21_URI_SCHEME, os_chmod)
|
AddTransactionException, BITCOIN_BIP21_URI_SCHEME, os_chmod)
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ from electrum import util, paymentrequest
|
|||||||
from electrum import lnutil
|
from electrum import lnutil
|
||||||
from electrum.plugin import run_hook
|
from electrum.plugin import run_hook
|
||||||
from electrum.i18n import _
|
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,
|
InvalidBitcoinURI, maybe_extract_lightning_payment_identifier, NotEnoughFunds,
|
||||||
NoDynamicFeeEstimates, InvoiceError, parse_max_spend)
|
NoDynamicFeeEstimates, InvoiceError, parse_max_spend)
|
||||||
from electrum.invoices import PR_PAID, Invoice
|
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}")
|
self.show_error(_("Invoice requires unknown or incompatible Lightning feature") + f":\n{e!r}")
|
||||||
return
|
return
|
||||||
|
|
||||||
pubkey = bh2u(lnaddr.pubkey.serialize())
|
pubkey = lnaddr.pubkey.serialize().hex()
|
||||||
for k,v in lnaddr.tags:
|
for k,v in lnaddr.tags:
|
||||||
if k == 'd':
|
if k == 'd':
|
||||||
description = v
|
description = v
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ from .crypto import (pw_decode, pw_encode, sha256, sha256d, PW_HASH_VERSION_LATE
|
|||||||
SUPPORTED_PW_HASH_VERSIONS, UnsupportedPasswordHashVersion, hash_160,
|
SUPPORTED_PW_HASH_VERSIONS, UnsupportedPasswordHashVersion, hash_160,
|
||||||
CiphertextFormatError)
|
CiphertextFormatError)
|
||||||
from .util import (InvalidPassword, WalletFileException,
|
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 .mnemonic import Mnemonic, Wordlist, seed_type, is_seed
|
||||||
from .plugin import run_hook
|
from .plugin import run_hook
|
||||||
from .logging import Logger
|
from .logging import Logger
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ import attr
|
|||||||
|
|
||||||
from . import ecc
|
from . import ecc
|
||||||
from . import constants, util
|
from . import constants, util
|
||||||
from .util import bfh, bh2u, chunks, TxMinedInfo
|
from .util import bfh, chunks, TxMinedInfo
|
||||||
from .invoices import PR_PAID
|
from .invoices import PR_PAID
|
||||||
from .bitcoin import redeem_script_to_address
|
from .bitcoin import redeem_script_to_address
|
||||||
from .crypto import sha256, sha256d
|
from .crypto import sha256, sha256d
|
||||||
@@ -1525,8 +1525,8 @@ class Channel(AbstractChannel):
|
|||||||
},
|
},
|
||||||
local_amount_msat=self.balance(LOCAL),
|
local_amount_msat=self.balance(LOCAL),
|
||||||
remote_amount_msat=self.balance(REMOTE) if not drop_remote else 0,
|
remote_amount_msat=self.balance(REMOTE) if not drop_remote else 0,
|
||||||
local_script=bh2u(local_script),
|
local_script=local_script.hex(),
|
||||||
remote_script=bh2u(remote_script),
|
remote_script=remote_script.hex(),
|
||||||
htlcs=[],
|
htlcs=[],
|
||||||
dust_limit_sat=self.config[LOCAL].dust_limit_sat)
|
dust_limit_sat=self.config[LOCAL].dust_limit_sat)
|
||||||
|
|
||||||
@@ -1552,7 +1552,7 @@ class Channel(AbstractChannel):
|
|||||||
def force_close_tx(self) -> PartialTransaction:
|
def force_close_tx(self) -> PartialTransaction:
|
||||||
tx = self.get_latest_commitment(LOCAL)
|
tx = self.get_latest_commitment(LOCAL)
|
||||||
assert self.signature_fits(tx)
|
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 = self.config[LOCAL].current_commitment_signature
|
||||||
remote_sig = ecc.der_sig_from_sig_string(remote_sig) + Sighash.to_sigbytes(Sighash.ALL)
|
remote_sig = ecc.der_sig_from_sig_string(remote_sig) + Sighash.to_sigbytes(Sighash.ALL)
|
||||||
tx.add_signature_to_txin(txin_idx=0,
|
tx.add_signature_to_txin(txin_idx=0,
|
||||||
|
|||||||
+1
-1
@@ -3,7 +3,7 @@ from typing import Optional, Sequence, Tuple, List, Dict, TYPE_CHECKING, Set
|
|||||||
import threading
|
import threading
|
||||||
|
|
||||||
from .lnutil import SENT, RECEIVED, LOCAL, REMOTE, HTLCOwner, UpdateAddHtlc, Direction, FeeUpdate
|
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:
|
if TYPE_CHECKING:
|
||||||
from .json_db import StoredDict
|
from .json_db import StoredDict
|
||||||
|
|||||||
+1
-1
@@ -30,7 +30,7 @@ from enum import IntEnum
|
|||||||
|
|
||||||
from . import ecc
|
from . import ecc
|
||||||
from .crypto import sha256, hmac_oneshot, chacha20_encrypt
|
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,
|
from .lnutil import (get_ecdh, PaymentFailure, NUM_MAX_HOPS_IN_PAYMENT_PATH,
|
||||||
NUM_MAX_EDGES_IN_PAYMENT_PATH, ShortChannelID, OnionFailureCodeMetaFlag)
|
NUM_MAX_EDGES_IN_PAYMENT_PATH, ShortChannelID, OnionFailureCodeMetaFlag)
|
||||||
from .lnmsg import OnionWireSerializer, read_bigsize_int, write_bigsize_int
|
from .lnmsg import OnionWireSerializer, read_bigsize_int, write_bigsize_int
|
||||||
|
|||||||
+7
-7
@@ -21,7 +21,7 @@ from . import bitcoin, util
|
|||||||
from . import ecc
|
from . import ecc
|
||||||
from .ecc import sig_string_from_r_and_s, der_sig_from_sig_string
|
from .ecc import sig_string_from_r_and_s, der_sig_from_sig_string
|
||||||
from . import constants
|
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)
|
UnrelatedTransactionException)
|
||||||
from . import transaction
|
from . import transaction
|
||||||
from .bitcoin import make_op_return
|
from .bitcoin import make_op_return
|
||||||
@@ -1020,7 +1020,7 @@ class Peer(Logger):
|
|||||||
|
|
||||||
# -> funding signed
|
# -> funding signed
|
||||||
funding_idx = funding_created['funding_output_index']
|
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)
|
channel_id, funding_txid_bytes = channel_id_from_funding_tx(funding_txid, funding_idx)
|
||||||
constraints = ChannelConstraints(
|
constraints = ChannelConstraints(
|
||||||
capacity=funding_sat,
|
capacity=funding_sat,
|
||||||
@@ -1157,7 +1157,7 @@ class Peer(Logger):
|
|||||||
if our_pcs != their_claim_of_our_last_per_commitment_secret:
|
if our_pcs != their_claim_of_our_last_per_commitment_secret:
|
||||||
self.logger.error(
|
self.logger.error(
|
||||||
f"channel_reestablish ({chan.get_id_for_log()}): "
|
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
|
return False
|
||||||
assert chan.is_static_remotekey_enabled()
|
assert chan.is_static_remotekey_enabled()
|
||||||
return True
|
return True
|
||||||
@@ -1167,7 +1167,7 @@ class Peer(Logger):
|
|||||||
if they_are_ahead:
|
if they_are_ahead:
|
||||||
self.logger.warning(
|
self.logger.warning(
|
||||||
f"channel_reestablish ({chan.get_id_for_log()}): "
|
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
|
# 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_data_loss_protect_remote_pcp(their_next_local_ctn - 1, their_local_pcp)
|
||||||
chan.set_state(ChannelState.WE_ARE_TOXIC)
|
chan.set_state(ChannelState.WE_ARE_TOXIC)
|
||||||
@@ -1311,7 +1311,7 @@ class Peer(Logger):
|
|||||||
self.mark_open(chan)
|
self.mark_open(chan)
|
||||||
|
|
||||||
def on_channel_ready(self, chan: Channel, payload):
|
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
|
# save remote alias for use in invoices
|
||||||
scid_alias = payload.get('channel_ready_tlvs', {}).get('short_channel_id', {}).get('alias')
|
scid_alias = payload.get('channel_ready_tlvs', {}).get('short_channel_id', {}).get('alias')
|
||||||
if scid_alias:
|
if scid_alias:
|
||||||
@@ -2185,11 +2185,11 @@ class Peer(Logger):
|
|||||||
closing_tx.add_signature_to_txin(
|
closing_tx.add_signature_to_txin(
|
||||||
txin_idx=0,
|
txin_idx=0,
|
||||||
signing_pubkey=chan.config[LOCAL].multisig_key.pubkey.hex(),
|
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(
|
closing_tx.add_signature_to_txin(
|
||||||
txin_idx=0,
|
txin_idx=0,
|
||||||
signing_pubkey=chan.config[REMOTE].multisig_key.pubkey.hex(),
|
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
|
# save local transaction and set state
|
||||||
try:
|
try:
|
||||||
self.lnworker.wallet.adb.add_transaction(closing_tx)
|
self.lnworker.wallet.adb.add_transaction(closing_tx)
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ from threading import RLock
|
|||||||
import attr
|
import attr
|
||||||
from math import inf
|
from math import inf
|
||||||
|
|
||||||
from .util import profiler, with_lock, bh2u
|
from .util import profiler, with_lock
|
||||||
from .logging import Logger
|
from .logging import Logger
|
||||||
from .lnutil import (NUM_MAX_EDGES_IN_PAYMENT_PATH, ShortChannelID, LnFeatures,
|
from .lnutil import (NUM_MAX_EDGES_IN_PAYMENT_PATH, ShortChannelID, LnFeatures,
|
||||||
NBLOCK_CLTV_EXPIRY_TOO_FAR_INTO_FUTURE)
|
NBLOCK_CLTV_EXPIRY_TOO_FAR_INTO_FUTURE)
|
||||||
|
|||||||
+12
-12
@@ -5,7 +5,7 @@
|
|||||||
from typing import Optional, Dict, List, Tuple, TYPE_CHECKING, NamedTuple, Callable
|
from typing import Optional, Dict, List, Tuple, TYPE_CHECKING, NamedTuple, Callable
|
||||||
from enum import Enum, auto
|
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 .bitcoin import redeem_script_to_address, dust_threshold, construct_witness
|
||||||
from .invoices import PR_PAID
|
from .invoices import PR_PAID
|
||||||
from . import ecc
|
from . import ecc
|
||||||
@@ -52,8 +52,8 @@ def create_sweeptxs_for_watchtower(chan: 'Channel', ctx: Transaction, per_commit
|
|||||||
txs = []
|
txs = []
|
||||||
# to_local
|
# to_local
|
||||||
revocation_pubkey = ecc.ECPrivkey(other_revocation_privkey).get_public_key_bytes(compressed=True)
|
revocation_pubkey = ecc.ECPrivkey(other_revocation_privkey).get_public_key_bytes(compressed=True)
|
||||||
witness_script = bh2u(make_commitment_output_to_local_witness_script(
|
witness_script = make_commitment_output_to_local_witness_script(
|
||||||
revocation_pubkey, to_self_delay, this_delayed_pubkey))
|
revocation_pubkey, to_self_delay, this_delayed_pubkey).hex()
|
||||||
to_local_address = redeem_script_to_address('p2wsh', witness_script)
|
to_local_address = redeem_script_to_address('p2wsh', witness_script)
|
||||||
output_idxs = ctx.get_output_idxs_from_address(to_local_address)
|
output_idxs = ctx.get_output_idxs_from_address(to_local_address)
|
||||||
if output_idxs:
|
if output_idxs:
|
||||||
@@ -119,8 +119,8 @@ def create_sweeptx_for_their_revoked_ctx(
|
|||||||
txs = []
|
txs = []
|
||||||
# to_local
|
# to_local
|
||||||
revocation_pubkey = ecc.ECPrivkey(other_revocation_privkey).get_public_key_bytes(compressed=True)
|
revocation_pubkey = ecc.ECPrivkey(other_revocation_privkey).get_public_key_bytes(compressed=True)
|
||||||
witness_script = bh2u(make_commitment_output_to_local_witness_script(
|
witness_script = make_commitment_output_to_local_witness_script(
|
||||||
revocation_pubkey, to_self_delay, this_delayed_pubkey))
|
revocation_pubkey, to_self_delay, this_delayed_pubkey).hex()
|
||||||
to_local_address = redeem_script_to_address('p2wsh', witness_script)
|
to_local_address = redeem_script_to_address('p2wsh', witness_script)
|
||||||
output_idxs = ctx.get_output_idxs_from_address(to_local_address)
|
output_idxs = ctx.get_output_idxs_from_address(to_local_address)
|
||||||
if output_idxs:
|
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)
|
this_delayed_pubkey = derive_pubkey(this_conf.delayed_basepoint.pubkey, pcp)
|
||||||
# same witness script as to_local
|
# same witness script as to_local
|
||||||
revocation_pubkey = ecc.ECPrivkey(other_revocation_privkey).get_public_key_bytes(compressed=True)
|
revocation_pubkey = ecc.ECPrivkey(other_revocation_privkey).get_public_key_bytes(compressed=True)
|
||||||
witness_script = bh2u(make_commitment_output_to_local_witness_script(
|
witness_script = make_commitment_output_to_local_witness_script(
|
||||||
revocation_pubkey, to_self_delay, this_delayed_pubkey))
|
revocation_pubkey, to_self_delay, this_delayed_pubkey).hex()
|
||||||
htlc_address = redeem_script_to_address('p2wsh', witness_script)
|
htlc_address = redeem_script_to_address('p2wsh', witness_script)
|
||||||
# check that htlc_tx is a htlc
|
# check that htlc_tx is a htlc
|
||||||
if htlc_tx.outputs()[0].address != htlc_address:
|
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'),
|
our_htlc_privkey = derive_privkey(secret=int.from_bytes(our_conf.htlc_basepoint.privkey, 'big'),
|
||||||
per_commitment_point=our_pcp).to_bytes(32, 'big')
|
per_commitment_point=our_pcp).to_bytes(32, 'big')
|
||||||
our_localdelayed_pubkey = our_localdelayed_privkey.get_public_key_bytes(compressed=True)
|
our_localdelayed_pubkey = our_localdelayed_privkey.get_public_key_bytes(compressed=True)
|
||||||
to_local_witness_script = bh2u(make_commitment_output_to_local_witness_script(
|
to_local_witness_script = make_commitment_output_to_local_witness_script(
|
||||||
their_revocation_pubkey, to_self_delay, our_localdelayed_pubkey))
|
their_revocation_pubkey, to_self_delay, our_localdelayed_pubkey).hex()
|
||||||
to_local_address = redeem_script_to_address('p2wsh', to_local_witness_script)
|
to_local_address = redeem_script_to_address('p2wsh', to_local_witness_script)
|
||||||
# test if this is our_ctx
|
# test if this is our_ctx
|
||||||
found_to_local = bool(ctx.get_output_idxs_from_address(to_local_address))
|
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
|
# to_local and to_remote addresses
|
||||||
our_revocation_pubkey = derive_blinded_pubkey(our_conf.revocation_basepoint.pubkey, their_pcp)
|
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)
|
their_delayed_pubkey = derive_pubkey(their_conf.delayed_basepoint.pubkey, their_pcp)
|
||||||
witness_script = bh2u(make_commitment_output_to_local_witness_script(
|
witness_script = make_commitment_output_to_local_witness_script(
|
||||||
our_revocation_pubkey, our_conf.to_self_delay, their_delayed_pubkey))
|
our_revocation_pubkey, our_conf.to_self_delay, their_delayed_pubkey).hex()
|
||||||
to_local_address = redeem_script_to_address('p2wsh', witness_script)
|
to_local_address = redeem_script_to_address('p2wsh', witness_script)
|
||||||
# test if this is their ctx
|
# test if this is their ctx
|
||||||
found_to_local = bool(ctx.get_output_idxs_from_address(to_local_address))
|
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,
|
commit=ctx,
|
||||||
htlc=htlc,
|
htlc=htlc,
|
||||||
ctx_output_idx=ctx_output_idx,
|
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)
|
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))
|
local_htlc_sig = bfh(htlc_tx.sign_txin(0, local_htlc_privkey))
|
||||||
txin = htlc_tx.inputs()[0]
|
txin = htlc_tx.inputs()[0]
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ from .crypto import sha256, hmac_oneshot, chacha20_poly1305_encrypt, chacha20_po
|
|||||||
from .lnutil import (get_ecdh, privkey_to_pubkey, LightningPeerConnectionClosed,
|
from .lnutil import (get_ecdh, privkey_to_pubkey, LightningPeerConnectionClosed,
|
||||||
HandshakeFailed, LNPeerAddr)
|
HandshakeFailed, LNPeerAddr)
|
||||||
from . import ecc
|
from . import ecc
|
||||||
from .util import bh2u, MySocksProxy
|
from .util import MySocksProxy
|
||||||
|
|
||||||
|
|
||||||
class HandshakeState(object):
|
class HandshakeState(object):
|
||||||
|
|||||||
+13
-13
@@ -11,7 +11,7 @@ import re
|
|||||||
import attr
|
import attr
|
||||||
from aiorpcx import NetAddress
|
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 list_enabled_bits
|
||||||
from .util import ShortID as ShortChannelID
|
from .util import ShortID as ShortChannelID
|
||||||
from .util import format_short_id as format_short_channel_id
|
from .util import format_short_id as format_short_channel_id
|
||||||
@@ -430,7 +430,7 @@ class RevocationStore:
|
|||||||
this_bucket = self.buckets[i]
|
this_bucket = self.buckets[i]
|
||||||
e = shachain_derive(new_element, this_bucket.index)
|
e = shachain_derive(new_element, this_bucket.index)
|
||||||
if e != this_bucket:
|
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.buckets[bucket] = new_element
|
||||||
self.storage['index'] = index - 1
|
self.storage['index'] = index - 1
|
||||||
|
|
||||||
@@ -474,7 +474,7 @@ def shachain_derive(element, to_index):
|
|||||||
to_index)
|
to_index)
|
||||||
|
|
||||||
ShachainElement = namedtuple("ShachainElement", ["secret", "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:
|
def get_per_commitment_secret_from_seed(seed: bytes, i: int, bits: int = 48) -> bytes:
|
||||||
"""Generate per commitment secret."""
|
"""Generate per commitment secret."""
|
||||||
@@ -528,7 +528,7 @@ def make_htlc_tx_output(amount_msat, local_feerate, revocationpubkey, local_dela
|
|||||||
delayed_pubkey=local_delayedpubkey,
|
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
|
weight = HTLC_SUCCESS_WEIGHT if success else HTLC_TIMEOUT_WEIGHT
|
||||||
fee = local_feerate * weight
|
fee = local_feerate * weight
|
||||||
fee = fee // 1000 * 1000
|
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,
|
local_htlc_pubkey=htlc_pubkey,
|
||||||
payment_hash=payment_hash,
|
payment_hash=payment_hash,
|
||||||
cltv_expiry=cltv_expiry)
|
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)
|
candidates = ctx.get_output_idxs_from_address(htlc_address)
|
||||||
return {output_idx for output_idx in candidates
|
return {output_idx for output_idx in candidates
|
||||||
if ctx.outputs()[output_idx].value == htlc.amount_msat // 1000}
|
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(
|
htlc_tx_inputs = make_htlc_tx_inputs(
|
||||||
commit.txid(), ctx_output_idx,
|
commit.txid(), ctx_output_idx,
|
||||||
amount_msat=amount_msat,
|
amount_msat=amount_msat,
|
||||||
witness_script=bh2u(preimage_script))
|
witness_script=preimage_script.hex())
|
||||||
if is_htlc_success:
|
if is_htlc_success:
|
||||||
cltv_expiry = 0
|
cltv_expiry = 0
|
||||||
htlc_tx = make_htlc_tx(cltv_expiry=cltv_expiry, inputs=htlc_tx_inputs, output=htlc_tx_output)
|
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,
|
def make_funding_input(local_funding_pubkey: bytes, remote_funding_pubkey: bytes,
|
||||||
funding_pos: int, funding_txid: str, funding_sat: int) -> PartialTxInput:
|
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
|
# commitment tx input
|
||||||
prevout = TxOutpoint(txid=bfh(funding_txid), out_idx=funding_pos)
|
prevout = TxOutpoint(txid=bfh(funding_txid), out_idx=funding_pos)
|
||||||
c_input = PartialTxInput(prevout=prevout)
|
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]
|
non_htlc_outputs = [to_local, to_remote]
|
||||||
htlc_outputs = []
|
htlc_outputs = []
|
||||||
for script, htlc in htlcs:
|
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)),
|
htlc_outputs.append(PartialTxOutput(scriptpubkey=bfh(address_to_script(addr)),
|
||||||
value=htlc.amount_msat // 1000))
|
value=htlc.amount_msat // 1000))
|
||||||
|
|
||||||
@@ -985,13 +985,13 @@ def make_commitment_output_to_local_witness_script(
|
|||||||
def make_commitment_output_to_local_address(
|
def make_commitment_output_to_local_address(
|
||||||
revocation_pubkey: bytes, to_self_delay: int, delayed_pubkey: bytes) -> str:
|
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)
|
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:
|
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):
|
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 = tx.inputs()[0].part_sigs[local_config.multisig_key.pubkey]
|
||||||
sig_64 = sig_string_from_der_sig(sig[:-1])
|
sig_64 = sig_string_from_der_sig(sig[:-1])
|
||||||
return sig_64
|
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)
|
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:
|
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)
|
return transaction.multisig_script(pubkeys, 2)
|
||||||
|
|
||||||
|
|
||||||
@@ -1450,7 +1450,7 @@ def extract_nodeid(connect_contents: str) -> Tuple[bytes, str]:
|
|||||||
# invoice?
|
# invoice?
|
||||||
invoice = lndecode(connect_contents)
|
invoice = lndecode(connect_contents)
|
||||||
nodeid_bytes = invoice.pubkey.serialize()
|
nodeid_bytes = invoice.pubkey.serialize()
|
||||||
nodeid_hex = bh2u(nodeid_bytes)
|
nodeid_hex = nodeid_bytes.hex()
|
||||||
except:
|
except:
|
||||||
# node id as hex?
|
# node id as hex?
|
||||||
nodeid_hex = connect_contents
|
nodeid_hex = connect_contents
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ import aiorpcx
|
|||||||
from . import bitcoin
|
from . import bitcoin
|
||||||
from . import ecc
|
from . import ecc
|
||||||
from . import constants
|
from . import constants
|
||||||
from .util import bh2u, bfh, NetworkJobOnDefaultServer
|
from .util import bfh, NetworkJobOnDefaultServer
|
||||||
from .lnutil import funding_output_script_from_keys, ShortChannelID
|
from .lnutil import funding_output_script_from_keys, ShortChannelID
|
||||||
from .verifier import verify_tx_is_in_block, MerkleVerificationFailure
|
from .verifier import verify_tx_is_in_block, MerkleVerificationFailure
|
||||||
from .transaction import Transaction
|
from .transaction import Transaction
|
||||||
@@ -105,7 +105,7 @@ class LNChannelVerifier(NetworkJobOnDefaultServer):
|
|||||||
continue
|
continue
|
||||||
self.started_verifying_channel.add(short_channel_id)
|
self.started_verifying_channel.add(short_channel_id)
|
||||||
await self.taskgroup.spawn(self.verify_channel(block_height, 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):
|
async def verify_channel(self, block_height: int, short_channel_id: ShortChannelID):
|
||||||
# we are verifying channel announcements as they are from untrusted ln peers.
|
# we are verifying channel announcements as they are from untrusted ln peers.
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ from typing import NamedTuple, Dict
|
|||||||
from . import util
|
from . import util
|
||||||
from .sql_db import SqlDB, sql
|
from .sql_db import SqlDB, sql
|
||||||
from .wallet_db import WalletDB
|
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 .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 Transaction, TxOutpoint
|
||||||
from .transaction import match_script_against_template
|
from .transaction import match_script_against_template
|
||||||
@@ -69,7 +69,7 @@ class SweepStore(SqlDB):
|
|||||||
def get_sweep_tx(self, funding_outpoint, prevout):
|
def get_sweep_tx(self, funding_outpoint, prevout):
|
||||||
c = self.conn.cursor()
|
c = self.conn.cursor()
|
||||||
c.execute("SELECT tx FROM sweep_txs WHERE funding_outpoint=? AND prevout=?", (funding_outpoint, prevout))
|
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
|
@sql
|
||||||
def list_sweep_tx(self):
|
def list_sweep_tx(self):
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ from .transaction import Transaction
|
|||||||
from .transaction import get_script_type_from_output_script
|
from .transaction import get_script_type_from_output_script
|
||||||
from .crypto import sha256
|
from .crypto import sha256
|
||||||
from .bip32 import BIP32Node
|
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 .crypto import chacha20_encrypt, chacha20_decrypt
|
||||||
from .util import ignore_exceptions, make_aiohttp_session
|
from .util import ignore_exceptions, make_aiohttp_session
|
||||||
from .util import timestamp_to_datetime, random_shuffled_copy
|
from .util import timestamp_to_datetime, random_shuffled_copy
|
||||||
@@ -499,12 +499,12 @@ class LNWorker(Logger, EventListener, NetworkRetryManager[LNPeerAddr]):
|
|||||||
if self.uses_trampoline():
|
if self.uses_trampoline():
|
||||||
addr = trampolines_by_id().get(node_id)
|
addr = trampolines_by_id().get(node_id)
|
||||||
if not addr:
|
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
|
host, port = addr.host, addr.port
|
||||||
else:
|
else:
|
||||||
addrs = self.channel_db.get_node_addresses(node_id)
|
addrs = self.channel_db.get_node_addresses(node_id)
|
||||||
if not addrs:
|
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))
|
host, port, timestamp = self.choose_preferred_address(list(addrs))
|
||||||
port = int(port)
|
port = int(port)
|
||||||
# Try DNS-resolving the host (if needed). This is simply so that
|
# 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)
|
tx_height = self.wallet.adb.get_tx_height(funding_txid)
|
||||||
self._labels_cache[funding_txid] = _('Open channel') + ' ' + chan.get_id_for_log()
|
self._labels_cache[funding_txid] = _('Open channel') + ' ' + chan.get_id_for_log()
|
||||||
item = {
|
item = {
|
||||||
'channel_id': bh2u(chan.channel_id),
|
'channel_id': chan.channel_id.hex(),
|
||||||
'type': 'channel_opening',
|
'type': 'channel_opening',
|
||||||
'label': self.get_label_for_txid(funding_txid),
|
'label': self.get_label_for_txid(funding_txid),
|
||||||
'txid': funding_txid,
|
'txid': funding_txid,
|
||||||
@@ -912,7 +912,7 @@ class LNWallet(LNWorker):
|
|||||||
tx_height = self.wallet.adb.get_tx_height(closing_txid)
|
tx_height = self.wallet.adb.get_tx_height(closing_txid)
|
||||||
self._labels_cache[closing_txid] = _('Close channel') + ' ' + chan.get_id_for_log()
|
self._labels_cache[closing_txid] = _('Close channel') + ' ' + chan.get_id_for_log()
|
||||||
item = {
|
item = {
|
||||||
'channel_id': bh2u(chan.channel_id),
|
'channel_id': chan.channel_id.hex(),
|
||||||
'txid': closing_txid,
|
'txid': closing_txid,
|
||||||
'label': self.get_label_for_txid(closing_txid),
|
'label': self.get_label_for_txid(closing_txid),
|
||||||
'type': 'channel_closure',
|
'type': 'channel_closure',
|
||||||
@@ -1309,7 +1309,7 @@ class LNWallet(LNWorker):
|
|||||||
code, data = failure_msg.code, failure_msg.data
|
code, data = failure_msg.code, failure_msg.data
|
||||||
self.logger.info(f"UPDATE_FAIL_HTLC. code={repr(code)}. "
|
self.logger.info(f"UPDATE_FAIL_HTLC. code={repr(code)}. "
|
||||||
f"decoded_data={failure_msg.decode_data()}. data={data.hex()!r}")
|
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:
|
if code == OnionFailureCode.MPP_TIMEOUT:
|
||||||
raise PaymentFailure(failure_msg.code_name())
|
raise PaymentFailure(failure_msg.code_name())
|
||||||
# trampoline
|
# trampoline
|
||||||
@@ -1847,12 +1847,12 @@ class LNWallet(LNWorker):
|
|||||||
|
|
||||||
def save_preimage(self, payment_hash: bytes, preimage: bytes, *, write_to_disk: bool = True):
|
def save_preimage(self, payment_hash: bytes, preimage: bytes, *, write_to_disk: bool = True):
|
||||||
assert sha256(preimage) == payment_hash
|
assert sha256(preimage) == payment_hash
|
||||||
self.preimages[bh2u(payment_hash)] = bh2u(preimage)
|
self.preimages[payment_hash.hex()] = preimage.hex()
|
||||||
if write_to_disk:
|
if write_to_disk:
|
||||||
self.wallet.save_db()
|
self.wallet.save_db()
|
||||||
|
|
||||||
def get_preimage(self, payment_hash: bytes) -> Optional[bytes]:
|
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
|
return bfh(r) if r else None
|
||||||
|
|
||||||
def get_payment_info(self, payment_hash: bytes) -> Optional[PaymentInfo]:
|
def get_payment_info(self, payment_hash: bytes) -> Optional[PaymentInfo]:
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ import string
|
|||||||
from typing import Sequence, Dict
|
from typing import Sequence, Dict
|
||||||
from types import MappingProxyType
|
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 .crypto import hmac_oneshot
|
||||||
from . import version
|
from . import version
|
||||||
from .logging import Logger
|
from .logging import Logger
|
||||||
@@ -224,7 +224,7 @@ class Mnemonic(Logger):
|
|||||||
|
|
||||||
def is_new_seed(x: str, prefix=version.SEED_PREFIX) -> bool:
|
def is_new_seed(x: str, prefix=version.SEED_PREFIX) -> bool:
|
||||||
x = normalize_text(x)
|
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)
|
return s.startswith(prefix)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ except ImportError:
|
|||||||
sys.exit("Error: could not find paymentrequest_pb2.py. Create it with 'contrib/generate_payreqpb2.sh'")
|
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 . 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 .invoices import Invoice, get_id_from_onchain_outputs
|
||||||
from .crypto import sha256
|
from .crypto import sha256
|
||||||
from .bitcoin import address_to_script
|
from .bitcoin import address_to_script
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ from electrum.i18n import _
|
|||||||
from electrum.keystore import Hardware_KeyStore
|
from electrum.keystore import Hardware_KeyStore
|
||||||
from electrum.transaction import PartialTransaction, Sighash
|
from electrum.transaction import PartialTransaction, Sighash
|
||||||
from electrum.wallet import Standard_Wallet, Multisig_Wallet, Deterministic_Wallet
|
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.base_wizard import ScriptTypeNotSupported, BaseWizard
|
||||||
from electrum.logging import get_logger
|
from electrum.logging import get_logger
|
||||||
from electrum.plugin import Device, DeviceInfo, runs_in_hwd_thread
|
from electrum.plugin import Device, DeviceInfo, runs_in_hwd_thread
|
||||||
@@ -524,7 +524,7 @@ class BitBox02Client(HardwareClientBase):
|
|||||||
if len(sigs) != len(tx.inputs()):
|
if len(sigs) != len(tx.inputs()):
|
||||||
raise Exception("Incorrect number of inputs signed.") # Should never occur
|
raise Exception("Incorrect number of inputs signed.") # Should never occur
|
||||||
sighash = Sighash.to_sigbytes(Sighash.ALL).hex()
|
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)
|
tx.update_signatures(signatures)
|
||||||
|
|
||||||
def sign_message(self, keypath: str, message: bytes, script_type: str) -> bytes:
|
def sign_message(self, keypath: str, message: bytes, script_type: str) -> bytes:
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ from electrum.plugin import Device, hook, runs_in_hwd_thread
|
|||||||
from electrum.keystore import Hardware_KeyStore, KeyStoreWithMPK
|
from electrum.keystore import Hardware_KeyStore, KeyStoreWithMPK
|
||||||
from electrum.transaction import PartialTransaction
|
from electrum.transaction import PartialTransaction
|
||||||
from electrum.wallet import Standard_Wallet, Multisig_Wallet, Abstract_Wallet
|
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.base_wizard import ScriptTypeNotSupported
|
||||||
from electrum.logging import get_logger
|
from electrum.logging import get_logger
|
||||||
|
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ from electrum.bip32 import BIP32Node
|
|||||||
from electrum.plugin import BasePlugin, hook
|
from electrum.plugin import BasePlugin, hook
|
||||||
from electrum.i18n import _
|
from electrum.i18n import _
|
||||||
from electrum.wallet import Multisig_Wallet, Abstract_Wallet
|
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.logging import Logger
|
||||||
|
|
||||||
from electrum.gui.qt.transaction_dialog import show_transaction, TxDialog
|
from electrum.gui.qt.transaction_dialog import show_transaction, TxDialog
|
||||||
@@ -156,7 +156,7 @@ class CosignerWallet(Logger):
|
|||||||
for key, keystore in wallet.keystores.items():
|
for key, keystore in wallet.keystores.items():
|
||||||
xpub = keystore.get_master_public_key() # type: str
|
xpub = keystore.get_master_public_key() # type: str
|
||||||
pubkey = BIP32Node.from_xkey(xpub).eckey.get_public_key_bytes(compressed=True)
|
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():
|
if not keystore.is_watching_only():
|
||||||
self.keys.append((key, _hash))
|
self.keys.append((key, _hash))
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import traceback
|
|||||||
import sys
|
import sys
|
||||||
from typing import NamedTuple, Any, Optional, Dict, Union, List, Tuple, TYPE_CHECKING
|
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.bip32 import BIP32Node
|
||||||
from electrum import constants
|
from electrum import constants
|
||||||
from electrum.i18n import _
|
from electrum.i18n import _
|
||||||
@@ -331,7 +331,7 @@ class KeepKeyPlugin(HW_PluginBase):
|
|||||||
signatures = client.sign_tx(self.get_coin_name(), inputs, outputs,
|
signatures = client.sign_tx(self.get_coin_name(), inputs, outputs,
|
||||||
lock_time=tx.locktime, version=tx.version)[0]
|
lock_time=tx.locktime, version=tx.version)[0]
|
||||||
sighash = Sighash.to_sigbytes(Sighash.ALL).hex()
|
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)
|
tx.update_signatures(signatures)
|
||||||
|
|
||||||
@runs_in_hwd_thread
|
@runs_in_hwd_thread
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ from electrum.gui.qt.util import (WindowModalDialog, WWLabel, Buttons, CancelBut
|
|||||||
OkButton, CloseButton)
|
OkButton, CloseButton)
|
||||||
from electrum.i18n import _
|
from electrum.i18n import _
|
||||||
from electrum.plugin import hook
|
from electrum.plugin import hook
|
||||||
from electrum.util import bh2u
|
|
||||||
|
|
||||||
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
|
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
|
||||||
from ..hw_wallet.plugin import only_hook_if_libraries_available
|
from ..hw_wallet.plugin import only_hook_if_libraries_available
|
||||||
@@ -345,7 +344,7 @@ class SettingsDialog(WindowModalDialog):
|
|||||||
def update(features):
|
def update(features):
|
||||||
self.features = features
|
self.features = features
|
||||||
set_label_enabled()
|
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:]])
|
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
|
||||||
noyes = [_("No"), _("Yes")]
|
noyes = [_("No"), _("Yes")]
|
||||||
endis = [_("Enable Passphrases"), _("Disable Passphrases")]
|
endis = [_("Enable Passphrases"), _("Disable Passphrases")]
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from hashlib import sha256
|
|||||||
from typing import NamedTuple, Optional, Dict, Tuple
|
from typing import NamedTuple, Optional, Dict, Tuple
|
||||||
|
|
||||||
from electrum.plugin import BasePlugin
|
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
|
from .hmac_drbg import DRBG
|
||||||
|
|
||||||
@@ -92,7 +92,7 @@ class RevealerPlugin(BasePlugin):
|
|||||||
@classmethod
|
@classmethod
|
||||||
def gen_random_versioned_seed(cls):
|
def gen_random_versioned_seed(cls):
|
||||||
version = cls.LATEST_VERSION
|
version = cls.LATEST_VERSION
|
||||||
hex_seed = bh2u(os.urandom(16))
|
hex_seed = os.urandom(16).hex()
|
||||||
checksum = cls.code_hashid(version + hex_seed)
|
checksum = cls.code_hashid(version + hex_seed)
|
||||||
return VersionedSeed(version=version.upper(),
|
return VersionedSeed(version=version.upper(),
|
||||||
seed=hex_seed.upper(),
|
seed=hex_seed.upper(),
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ from electrum.gui.qt.util import (WindowModalDialog, WWLabel, Buttons, CancelBut
|
|||||||
OkButton, CloseButton, getOpenFileName)
|
OkButton, CloseButton, getOpenFileName)
|
||||||
from electrum.i18n import _
|
from electrum.i18n import _
|
||||||
from electrum.plugin import hook
|
from electrum.plugin import hook
|
||||||
from electrum.util import bh2u
|
|
||||||
|
|
||||||
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
|
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
|
||||||
from ..hw_wallet.plugin import only_hook_if_libraries_available
|
from ..hw_wallet.plugin import only_hook_if_libraries_available
|
||||||
@@ -221,7 +220,7 @@ class SettingsDialog(WindowModalDialog):
|
|||||||
self.features = features
|
self.features = features
|
||||||
set_label_enabled()
|
set_label_enabled()
|
||||||
if features.bootloader_hash:
|
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:]])
|
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
|
||||||
else:
|
else:
|
||||||
bl_hash = "N/A"
|
bl_hash = "N/A"
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import traceback
|
|||||||
import sys
|
import sys
|
||||||
from typing import NamedTuple, Any, Optional, Dict, Union, List, Tuple, TYPE_CHECKING
|
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.bip32 import BIP32Node
|
||||||
from electrum import constants
|
from electrum import constants
|
||||||
from electrum.i18n import _
|
from electrum.i18n import _
|
||||||
@@ -301,7 +301,7 @@ class SafeTPlugin(HW_PluginBase):
|
|||||||
signatures = client.sign_tx(self.get_coin_name(), inputs, outputs,
|
signatures = client.sign_tx(self.get_coin_name(), inputs, outputs,
|
||||||
lock_time=tx.locktime, version=tx.version)[0]
|
lock_time=tx.locktime, version=tx.version)[0]
|
||||||
sighash = Sighash.to_sigbytes(Sighash.ALL).hex()
|
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)
|
tx.update_signatures(signatures)
|
||||||
|
|
||||||
@runs_in_hwd_thread
|
@runs_in_hwd_thread
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ from electrum.gui.qt.util import (WindowModalDialog, WWLabel, Buttons, CancelBut
|
|||||||
OkButton, CloseButton, PasswordLineEdit, getOpenFileName)
|
OkButton, CloseButton, PasswordLineEdit, getOpenFileName)
|
||||||
from electrum.i18n import _
|
from electrum.i18n import _
|
||||||
from electrum.plugin import hook
|
from electrum.plugin import hook
|
||||||
from electrum.util import bh2u
|
|
||||||
|
|
||||||
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
|
from ..hw_wallet.qt import QtHandlerBase, QtPluginBase
|
||||||
from ..hw_wallet.plugin import only_hook_if_libraries_available
|
from ..hw_wallet.plugin import only_hook_if_libraries_available
|
||||||
@@ -487,7 +486,7 @@ class SettingsDialog(WindowModalDialog):
|
|||||||
self.features = features
|
self.features = features
|
||||||
set_label_enabled()
|
set_label_enabled()
|
||||||
if features.bootloader_hash:
|
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:]])
|
bl_hash = "\n".join([bl_hash[:32], bl_hash[32:]])
|
||||||
else:
|
else:
|
||||||
bl_hash = "N/A"
|
bl_hash = "N/A"
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import traceback
|
|||||||
import sys
|
import sys
|
||||||
from typing import NamedTuple, Any, Optional, Dict, Union, List, Tuple, TYPE_CHECKING
|
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.bip32 import BIP32Node, convert_bip32_path_to_list_of_uint32 as parse_path
|
||||||
from electrum import constants
|
from electrum import constants
|
||||||
from electrum.i18n import _
|
from electrum.i18n import _
|
||||||
@@ -371,7 +371,7 @@ class TrezorPlugin(HW_PluginBase):
|
|||||||
serialize=False,
|
serialize=False,
|
||||||
prev_txes=prev_tx)
|
prev_txes=prev_tx)
|
||||||
sighash = Sighash.to_sigbytes(Sighash.ALL).hex()
|
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)
|
tx.update_signatures(signatures)
|
||||||
|
|
||||||
@runs_in_hwd_thread
|
@runs_in_hwd_thread
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ from electrum.simple_config import SimpleConfig
|
|||||||
from electrum import constants
|
from electrum import constants
|
||||||
from electrum.daemon import Daemon
|
from electrum.daemon import Daemon
|
||||||
from electrum.wallet import create_new_wallet
|
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
|
from electrum.lnutil import LnFeatures
|
||||||
|
|
||||||
logger = get_logger(__name__)
|
logger = get_logger(__name__)
|
||||||
@@ -77,9 +77,9 @@ async def worker(work_queue: asyncio.Queue, results_queue: asyncio.Queue, flag):
|
|||||||
|
|
||||||
# handle ipv4/ipv6
|
# handle ipv4/ipv6
|
||||||
if ':' in addr[0]:
|
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:
|
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}")
|
print(f"worker connecting to {connect_str}")
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -32,7 +32,7 @@ from aiorpcx import run_in_thread, RPCError
|
|||||||
|
|
||||||
from . import util
|
from . import util
|
||||||
from .transaction import Transaction, PartialTransaction
|
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 .bitcoin import address_to_scripthash, is_address
|
||||||
from .logging import Logger
|
from .logging import Logger
|
||||||
from .interface import GracefulDisconnect, NetworkTimeout
|
from .interface import GracefulDisconnect, NetworkTimeout
|
||||||
@@ -51,7 +51,7 @@ def history_status(h):
|
|||||||
status = ''
|
status = ''
|
||||||
for tx_hash, height in h:
|
for tx_hash, height in h:
|
||||||
status += tx_hash + ':%d:' % height
|
status += tx_hash + ':%d:' % height
|
||||||
return bh2u(hashlib.sha256(status.encode('ascii')).digest())
|
return hashlib.sha256(status.encode('ascii')).digest().hex()
|
||||||
|
|
||||||
|
|
||||||
class SynchronizerBase(NetworkJobOnDefaultServer):
|
class SynchronizerBase(NetworkJobOnDefaultServer):
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ from electrum.bip32 import (BIP32Node, convert_bip32_intpath_to_strpath,
|
|||||||
normalize_bip32_derivation, is_all_public_derivation)
|
normalize_bip32_derivation, is_all_public_derivation)
|
||||||
from electrum.crypto import sha256d, SUPPORTED_PW_HASH_VERSIONS
|
from electrum.crypto import sha256d, SUPPORTED_PW_HASH_VERSIONS
|
||||||
from electrum import ecc, crypto, constants
|
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.storage import WalletStorage
|
||||||
from electrum.keystore import xtype_from_derivation
|
from electrum.keystore import xtype_from_derivation
|
||||||
|
|
||||||
@@ -450,17 +450,17 @@ class Test_bitcoin(ElectrumTestCase):
|
|||||||
|
|
||||||
def test_push_script(self):
|
def test_push_script(self):
|
||||||
# https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#push-operators
|
# 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(''), bytes([opcodes.OP_0]).hex())
|
||||||
self.assertEqual(push_script('07'), bh2u(bytes([opcodes.OP_7])))
|
self.assertEqual(push_script('07'), bytes([opcodes.OP_7]).hex())
|
||||||
self.assertEqual(push_script('10'), bh2u(bytes([opcodes.OP_16])))
|
self.assertEqual(push_script('10'), bytes([opcodes.OP_16]).hex())
|
||||||
self.assertEqual(push_script('81'), bh2u(bytes([opcodes.OP_1NEGATE])))
|
self.assertEqual(push_script('81'), bytes([opcodes.OP_1NEGATE]).hex())
|
||||||
self.assertEqual(push_script('11'), '0111')
|
self.assertEqual(push_script('11'), '0111')
|
||||||
self.assertEqual(push_script(75 * '42'), '4b' + 75 * '42')
|
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(76 * '42'), (bytes([opcodes.OP_PUSHDATA1]) + bfh('4c' + 76 * '42')).hex())
|
||||||
self.assertEqual(push_script(100 * '42'), bh2u(bytes([opcodes.OP_PUSHDATA1]) + bfh('64' + 100 * '42')))
|
self.assertEqual(push_script(100 * '42'), (bytes([opcodes.OP_PUSHDATA1]) + bfh('64' + 100 * '42')).hex())
|
||||||
self.assertEqual(push_script(255 * '42'), bh2u(bytes([opcodes.OP_PUSHDATA1]) + bfh('ff' + 255 * '42')))
|
self.assertEqual(push_script(255 * '42'), (bytes([opcodes.OP_PUSHDATA1]) + bfh('ff' + 255 * '42')).hex())
|
||||||
self.assertEqual(push_script(256 * '42'), bh2u(bytes([opcodes.OP_PUSHDATA2]) + bfh('0001' + 256 * '42')))
|
self.assertEqual(push_script(256 * '42'), (bytes([opcodes.OP_PUSHDATA2]) + bfh('0001' + 256 * '42')).hex())
|
||||||
self.assertEqual(push_script(520 * '42'), bh2u(bytes([opcodes.OP_PUSHDATA2]) + bfh('0802' + 520 * '42')))
|
self.assertEqual(push_script(520 * '42'), (bytes([opcodes.OP_PUSHDATA2]) + bfh('0802' + 520 * '42')).hex())
|
||||||
|
|
||||||
def test_add_number_to_script(self):
|
def test_add_number_to_script(self):
|
||||||
# https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#numbers
|
# https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#numbers
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import os
|
|||||||
from electrum import constants, blockchain
|
from electrum import constants, blockchain
|
||||||
from electrum.simple_config import SimpleConfig
|
from electrum.simple_config import SimpleConfig
|
||||||
from electrum.blockchain import Blockchain, deserialize_header, hash_header
|
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
|
from . import ElectrumTestCase
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ from electrum.ecc import ECPrivkey
|
|||||||
from electrum import simple_config, lnutil
|
from electrum import simple_config, lnutil
|
||||||
from electrum.lnaddr import lnencode, LnAddr, lndecode
|
from electrum.lnaddr import lnencode, LnAddr, lndecode
|
||||||
from electrum.bitcoin import COIN, sha256
|
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.lnpeer import Peer
|
||||||
from electrum.lnutil import LNPeerAddr, Keypair, privkey_to_pubkey
|
from electrum.lnutil import LNPeerAddr, Keypair, privkey_to_pubkey
|
||||||
from electrum.lnutil import PaymentFailure, LnFeatures, HTLCOwner
|
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
|
# create upfront shutdown script for bob, alice doesn't use upfront
|
||||||
# shutdown script
|
# shutdown script
|
||||||
bob_uss_pub = lnutil.privkey_to_pubkey(os.urandom(32))
|
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_uss = bfh(bitcoin.address_to_script(bob_uss_addr))
|
||||||
|
|
||||||
# bob commits to close to bob_uss
|
# bob commits to close to bob_uss
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import shutil
|
|||||||
import asyncio
|
import asyncio
|
||||||
|
|
||||||
from electrum import util
|
from electrum import util
|
||||||
from electrum.util import bh2u, bfh
|
from electrum.util import bfh
|
||||||
from electrum.lnutil import ShortChannelID
|
from electrum.lnutil import ShortChannelID
|
||||||
from electrum.lnonion import (OnionHopsDataSingle, new_onion_packet,
|
from electrum.lnonion import (OnionHopsDataSingle, new_onion_packet,
|
||||||
process_onion_packet, _decode_onion_error, decode_onion_error,
|
process_onion_packet, _decode_onion_error, decode_onion_error,
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ from electrum.lnutil import (RevocationStore, get_per_commitment_secret_from_see
|
|||||||
get_compressed_pubkey_from_bech32, split_host_port, ConnStringFormatError,
|
get_compressed_pubkey_from_bech32, split_host_port, ConnStringFormatError,
|
||||||
ScriptHtlc, extract_nodeid, calc_fees_for_commitment_tx, UpdateAddHtlc, LnFeatures,
|
ScriptHtlc, extract_nodeid, calc_fees_for_commitment_tx, UpdateAddHtlc, LnFeatures,
|
||||||
ln_compare_features, IncompatibleLightningFeatures, ChannelType)
|
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.transaction import Transaction, PartialTransaction, Sighash
|
||||||
from electrum.lnworker import LNWallet
|
from electrum.lnworker import LNWallet
|
||||||
|
|
||||||
@@ -575,7 +575,7 @@ class TestLNUtil(ElectrumTestCase):
|
|||||||
htlc_output_txid=our_commit_tx.txid(),
|
htlc_output_txid=our_commit_tx.txid(),
|
||||||
htlc_output_index=htlc_output_index,
|
htlc_output_index=htlc_output_index,
|
||||||
amount_msat=amount_msat,
|
amount_msat=amount_msat,
|
||||||
witness_script=bh2u(htlc))
|
witness_script=htlc.hex())
|
||||||
our_htlc_tx = make_htlc_tx(
|
our_htlc_tx = make_htlc_tx(
|
||||||
cltv_expiry=cltv_timeout,
|
cltv_expiry=cltv_timeout,
|
||||||
inputs=our_htlc_tx_inputs,
|
inputs=our_htlc_tx_inputs,
|
||||||
@@ -724,7 +724,7 @@ class TestLNUtil(ElectrumTestCase):
|
|||||||
assert type(privkey) is bytes
|
assert type(privkey) is bytes
|
||||||
assert len(pubkey) == 33
|
assert len(pubkey) == 33
|
||||||
assert len(privkey) == 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()
|
sighash = Sighash.to_sigbytes(Sighash.ALL).hex()
|
||||||
tx.add_signature_to_txin(txin_idx=0, signing_pubkey=remote_pubkey.hex(), sig=remote_signature + sighash)
|
tx.add_signature_to_txin(txin_idx=0, signing_pubkey=remote_pubkey.hex(), sig=remote_signature + sighash)
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ from electrum import keystore
|
|||||||
from electrum import mnemonic
|
from electrum import mnemonic
|
||||||
from electrum import slip39
|
from electrum import slip39
|
||||||
from electrum import old_mnemonic
|
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.mnemonic import is_new_seed, is_old_seed, seed_type
|
||||||
from electrum.version import SEED_PREFIX_SW, SEED_PREFIX
|
from electrum.version import SEED_PREFIX_SW, SEED_PREFIX
|
||||||
|
|
||||||
@@ -104,20 +104,20 @@ class Test_NewMnemonic(ElectrumTestCase):
|
|||||||
# note: not a valid electrum seed
|
# note: not a valid electrum seed
|
||||||
seed = mnemonic.Mnemonic.mnemonic_to_seed(mnemonic='foobar', passphrase='none')
|
seed = mnemonic.Mnemonic.mnemonic_to_seed(mnemonic='foobar', passphrase='none')
|
||||||
self.assertEqual('741b72fd15effece6bfe5a26a52184f66811bd2be363190e07a42cca442b1a5bb22b3ad0eb338197287e6d314866c7fba863ac65d3f156087a5052ebc7157fce',
|
self.assertEqual('741b72fd15effece6bfe5a26a52184f66811bd2be363190e07a42cca442b1a5bb22b3ad0eb338197287e6d314866c7fba863ac65d3f156087a5052ebc7157fce',
|
||||||
bh2u(seed))
|
seed.hex())
|
||||||
|
|
||||||
def test_mnemonic_to_seed(self):
|
def test_mnemonic_to_seed(self):
|
||||||
for test_name, test in SEED_TEST_CASES.items():
|
for test_name, test in SEED_TEST_CASES.items():
|
||||||
if test.words_hex is not None:
|
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)
|
self.assertTrue(is_new_seed(test.words, prefix=test.seed_version), msg=test_name)
|
||||||
m = mnemonic.Mnemonic(lang=test.lang)
|
m = mnemonic.Mnemonic(lang=test.lang)
|
||||||
if test.entropy is not None:
|
if test.entropy is not None:
|
||||||
self.assertEqual(test.entropy, m.mnemonic_decode(test.words), msg=test_name)
|
self.assertEqual(test.entropy, m.mnemonic_decode(test.words), msg=test_name)
|
||||||
if test.passphrase_hex is not None:
|
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)
|
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):
|
def test_random_seeds(self):
|
||||||
iters = 10
|
iters = 10
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ from electrum.simple_config import SimpleConfig
|
|||||||
from electrum import blockchain
|
from electrum import blockchain
|
||||||
from electrum.interface import Interface, ServerAddr
|
from electrum.interface import Interface, ServerAddr
|
||||||
from electrum.crypto import sha256
|
from electrum.crypto import sha256
|
||||||
from electrum.util import bh2u
|
|
||||||
from electrum import util
|
from electrum import util
|
||||||
|
|
||||||
from . import ElectrumTestCase
|
from . import ElectrumTestCase
|
||||||
@@ -105,7 +104,7 @@ class TestNetwork(ElectrumTestCase):
|
|||||||
def mock_fork(self, bad_header):
|
def mock_fork(self, bad_header):
|
||||||
forkpoint = bad_header['block_height']
|
forkpoint = bad_header['block_height']
|
||||||
b = blockchain.Blockchain(config=self.config, forkpoint=forkpoint, parent=None,
|
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
|
return b
|
||||||
|
|
||||||
def test_chain_false_during_binary(self):
|
def test_chain_false_during_binary(self):
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from electrum.transaction import (convert_raw_tx_to_hex, tx_from_any, Transactio
|
|||||||
PartialTransaction, TxOutpoint, PartialTxInput,
|
PartialTransaction, TxOutpoint, PartialTxInput,
|
||||||
PartialTxOutput, Sighash, match_script_against_template,
|
PartialTxOutput, Sighash, match_script_against_template,
|
||||||
SCRIPTPUBKEY_TEMPLATE_ANYSEGWIT)
|
SCRIPTPUBKEY_TEMPLATE_ANYSEGWIT)
|
||||||
from electrum.util import bh2u, bfh
|
from electrum.util import bfh
|
||||||
from electrum.bitcoin import (deserialize_privkey, opcodes,
|
from electrum.bitcoin import (deserialize_privkey, opcodes,
|
||||||
construct_script, construct_witness)
|
construct_script, construct_witness)
|
||||||
from electrum.ecc import ECPrivkey
|
from electrum.ecc import ECPrivkey
|
||||||
@@ -30,7 +30,7 @@ class TestBCDataStream(ElectrumTestCase):
|
|||||||
with self.assertRaises(transaction.SerializationError):
|
with self.assertRaises(transaction.SerializationError):
|
||||||
s.write_compact_size(-1)
|
s.write_compact_size(-1)
|
||||||
|
|
||||||
self.assertEqual(bh2u(s.input),
|
self.assertEqual(s.input.hex(),
|
||||||
'0001fcfdfd00fdfffffe00000100feffffffffff0000000001000000ffffffffffffffffff')
|
'0001fcfdfd00fdfffffe00000100feffffffffff0000000001000000ffffffffffffffffff')
|
||||||
for v in values:
|
for v in values:
|
||||||
self.assertEqual(s.read_compact_size(), v)
|
self.assertEqual(s.read_compact_size(), v)
|
||||||
|
|||||||
@@ -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,
|
from electrum.wallet import (sweep, Multisig_Wallet, Standard_Wallet, Imported_Wallet,
|
||||||
restore_wallet_from_text, Abstract_Wallet)
|
restore_wallet_from_text, Abstract_Wallet)
|
||||||
from electrum.util import (
|
from electrum.util import (
|
||||||
bfh, bh2u, NotEnoughFunds, UnrelatedTransactionException,
|
bfh, NotEnoughFunds, UnrelatedTransactionException,
|
||||||
UserFacingException)
|
UserFacingException)
|
||||||
from electrum.transaction import (TxOutput, Transaction, PartialTransaction, PartialTxOutput,
|
from electrum.transaction import (TxOutput, Transaction, PartialTransaction, PartialTxOutput,
|
||||||
PartialTxInput, tx_from_any, TxOutpoint)
|
PartialTxInput, tx_from_any, TxOutpoint)
|
||||||
@@ -445,7 +445,7 @@ class TestWalletKeystoreAddressIntegrityForMainnet(ElectrumTestCase):
|
|||||||
self.assertEqual(keystore.bip39_is_checksum_valid(seed_words), (True, True))
|
self.assertEqual(keystore.bip39_is_checksum_valid(seed_words), (True, True))
|
||||||
bip32_seed = keystore.bip39_to_seed(seed_words, '')
|
bip32_seed = keystore.bip39_to_seed(seed_words, '')
|
||||||
self.assertEqual('0df68c16e522eea9c1d8e090cfb2139c3b3a2abed78cbcb3e20be2c29185d3b8df4e8ce4e52a1206a688aeb88bfee249585b41a7444673d1f16c0d45755fa8b9',
|
self.assertEqual('0df68c16e522eea9c1d8e090cfb2139c3b3a2abed78cbcb3e20be2c29185d3b8df4e8ce4e52a1206a688aeb88bfee249585b41a7444673d1f16c0d45755fa8b9',
|
||||||
bh2u(bip32_seed))
|
bip32_seed.hex())
|
||||||
|
|
||||||
def create_keystore_from_bip32seed(xtype):
|
def create_keystore_from_bip32seed(xtype):
|
||||||
ks = keystore.BIP32_KeyStore({})
|
ks = keystore.BIP32_KeyStore({})
|
||||||
@@ -643,7 +643,7 @@ class TestWalletKeystoreAddressIntegrityForTestnet(TestCaseForTestnet):
|
|||||||
self.assertEqual(keystore.bip39_is_checksum_valid(seed_words), (True, True))
|
self.assertEqual(keystore.bip39_is_checksum_valid(seed_words), (True, True))
|
||||||
bip32_seed = keystore.bip39_to_seed(seed_words, '')
|
bip32_seed = keystore.bip39_to_seed(seed_words, '')
|
||||||
self.assertEqual('0df68c16e522eea9c1d8e090cfb2139c3b3a2abed78cbcb3e20be2c29185d3b8df4e8ce4e52a1206a688aeb88bfee249585b41a7444673d1f16c0d45755fa8b9',
|
self.assertEqual('0df68c16e522eea9c1d8e090cfb2139c3b3a2abed78cbcb3e20be2c29185d3b8df4e8ce4e52a1206a688aeb88bfee249585b41a7444673d1f16c0d45755fa8b9',
|
||||||
bh2u(bip32_seed))
|
bip32_seed.hex())
|
||||||
|
|
||||||
def create_keystore_from_bip32seed(xtype):
|
def create_keystore_from_bip32seed(xtype):
|
||||||
ks = keystore.BIP32_KeyStore({})
|
ks = keystore.BIP32_KeyStore({})
|
||||||
|
|||||||
+10
-10
@@ -42,7 +42,7 @@ import copy
|
|||||||
|
|
||||||
from . import ecc, bitcoin, constants, segwit_addr, bip32
|
from . import ecc, bitcoin, constants, segwit_addr, bip32
|
||||||
from .bip32 import BIP32Node
|
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,
|
from .bitcoin import (TYPE_ADDRESS, TYPE_SCRIPT, hash_160,
|
||||||
hash160_to_p2sh, hash160_to_p2pkh, hash_to_segwit_addr,
|
hash160_to_p2sh, hash160_to_p2pkh, hash_to_segwit_addr,
|
||||||
var_int, TOTAL_COIN_SUPPLY_LIMIT_IN_BTC, COIN,
|
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
|
self._cached_network_ser = raw.strip() if raw else None
|
||||||
assert is_hex_str(self._cached_network_ser)
|
assert is_hex_str(self._cached_network_ser)
|
||||||
elif isinstance(raw, (bytes, bytearray)):
|
elif isinstance(raw, (bytes, bytearray)):
|
||||||
self._cached_network_ser = bh2u(raw)
|
self._cached_network_ser = raw.hex()
|
||||||
else:
|
else:
|
||||||
raise Exception(f"cannot initialize transaction from {raw}")
|
raise Exception(f"cannot initialize transaction from {raw}")
|
||||||
self._inputs = None # type: List[TxInput]
|
self._inputs = None # type: List[TxInput]
|
||||||
@@ -863,7 +863,7 @@ class Transaction:
|
|||||||
return multisig_script(pubkeys, txin.num_sig)
|
return multisig_script(pubkeys, txin.num_sig)
|
||||||
elif txin.script_type in ['p2pkh', 'p2wpkh', 'p2wpkh-p2sh']:
|
elif txin.script_type in ['p2pkh', 'p2wpkh', 'p2wpkh-p2sh']:
|
||||||
pubkey = pubkeys[0]
|
pubkey = pubkeys[0]
|
||||||
pkh = bh2u(hash_160(bfh(pubkey)))
|
pkh = hash_160(bfh(pubkey)).hex()
|
||||||
return bitcoin.pubkeyhash_to_p2pkh_script(pkh)
|
return bitcoin.pubkeyhash_to_p2pkh_script(pkh)
|
||||||
elif txin.script_type == 'p2pk':
|
elif txin.script_type == 'p2pk':
|
||||||
pubkey = pubkeys[0]
|
pubkey = pubkeys[0]
|
||||||
@@ -874,9 +874,9 @@ class Transaction:
|
|||||||
def _calc_bip143_shared_txdigest_fields(self) -> BIP143SharedTxDigestFields:
|
def _calc_bip143_shared_txdigest_fields(self) -> BIP143SharedTxDigestFields:
|
||||||
inputs = self.inputs()
|
inputs = self.inputs()
|
||||||
outputs = self.outputs()
|
outputs = self.outputs()
|
||||||
hashPrevouts = bh2u(sha256d(b''.join(txin.prevout.serialize_to_network() for txin in inputs)))
|
hashPrevouts = sha256d(b''.join(txin.prevout.serialize_to_network() for txin in inputs)).hex()
|
||||||
hashSequence = bh2u(sha256d(bfh(''.join(int_to_hex(txin.nsequence, 4) for txin in inputs))))
|
hashSequence = sha256d(bfh(''.join(int_to_hex(txin.nsequence, 4) for txin in inputs))).hex()
|
||||||
hashOutputs = bh2u(sha256d(bfh(''.join(o.serialize_to_network().hex() for o in outputs))))
|
hashOutputs = sha256d(bfh(''.join(o.serialize_to_network().hex() for o in outputs))).hex()
|
||||||
return BIP143SharedTxDigestFields(hashPrevouts=hashPrevouts,
|
return BIP143SharedTxDigestFields(hashPrevouts=hashPrevouts,
|
||||||
hashSequence=hashSequence,
|
hashSequence=hashSequence,
|
||||||
hashOutputs=hashOutputs)
|
hashOutputs=hashOutputs)
|
||||||
@@ -949,7 +949,7 @@ class Transaction:
|
|||||||
except UnknownTxinType:
|
except UnknownTxinType:
|
||||||
# we might not know how to construct scriptSig for some scripts
|
# we might not know how to construct scriptSig for some scripts
|
||||||
return None
|
return None
|
||||||
self._cached_txid = bh2u(sha256d(bfh(ser))[::-1])
|
self._cached_txid = sha256d(bfh(ser))[::-1].hex()
|
||||||
return self._cached_txid
|
return self._cached_txid
|
||||||
|
|
||||||
def wtxid(self) -> Optional[str]:
|
def wtxid(self) -> Optional[str]:
|
||||||
@@ -961,7 +961,7 @@ class Transaction:
|
|||||||
except UnknownTxinType:
|
except UnknownTxinType:
|
||||||
# we might not know how to construct scriptSig/witness for some scripts
|
# we might not know how to construct scriptSig/witness for some scripts
|
||||||
return None
|
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:
|
def add_info_from_wallet(self, wallet: 'Abstract_Wallet', **kwargs) -> None:
|
||||||
return # no-op
|
return # no-op
|
||||||
@@ -1963,7 +1963,7 @@ class PartialTransaction(Transaction):
|
|||||||
if (sighash & 0x1f) != Sighash.SINGLE and (sighash & 0x1f) != Sighash.NONE:
|
if (sighash & 0x1f) != Sighash.SINGLE and (sighash & 0x1f) != Sighash.NONE:
|
||||||
hashOutputs = bip143_shared_txdigest_fields.hashOutputs
|
hashOutputs = bip143_shared_txdigest_fields.hashOutputs
|
||||||
elif (sighash & 0x1f) == Sighash.SINGLE and txin_index < len(outputs):
|
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:
|
else:
|
||||||
hashOutputs = '00' * 32
|
hashOutputs = '00' * 32
|
||||||
outpoint = txin.prevout.serialize_to_network().hex()
|
outpoint = txin.prevout.serialize_to_network().hex()
|
||||||
@@ -2006,7 +2006,7 @@ class PartialTransaction(Transaction):
|
|||||||
bip143_shared_txdigest_fields=bip143_shared_txdigest_fields)))
|
bip143_shared_txdigest_fields=bip143_shared_txdigest_fields)))
|
||||||
privkey = ecc.ECPrivkey(privkey_bytes)
|
privkey = ecc.ECPrivkey(privkey_bytes)
|
||||||
sig = privkey.sign_transaction(pre_hash)
|
sig = privkey.sign_transaction(pre_hash)
|
||||||
sig = bh2u(sig) + Sighash.to_sigbytes(sighash).hex()
|
sig = sig.hex() + Sighash.to_sigbytes(sighash).hex()
|
||||||
return sig
|
return sig
|
||||||
|
|
||||||
def is_complete(self) -> bool:
|
def is_complete(self) -> bool:
|
||||||
|
|||||||
+1
-12
@@ -585,17 +585,6 @@ def to_bytes(something, encoding='utf8') -> bytes:
|
|||||||
bfh = bytes.fromhex
|
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:
|
def xor_bytes(a: bytes, b: bytes) -> bytes:
|
||||||
size = min(len(a), len(b))
|
size = min(len(a), len(b))
|
||||||
return ((int.from_bytes(a[:size], "big") ^ int.from_bytes(b[:size], "big"))
|
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
|
raise InvalidBitcoinURI(f"failed to parse 'exp' field: {repr(e)}") from e
|
||||||
if 'sig' in out:
|
if 'sig' in out:
|
||||||
try:
|
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:
|
except Exception as e:
|
||||||
raise InvalidBitcoinURI(f"failed to parse 'sig' field: {repr(e)}") from e
|
raise InvalidBitcoinURI(f"failed to parse 'sig' field: {repr(e)}") from e
|
||||||
if 'lightning' in out:
|
if 'lightning' in out:
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ from typing import Sequence, Optional, TYPE_CHECKING
|
|||||||
|
|
||||||
import aiorpcx
|
import aiorpcx
|
||||||
|
|
||||||
from .util import bh2u, TxMinedInfo, NetworkJobOnDefaultServer
|
from .util import TxMinedInfo, NetworkJobOnDefaultServer
|
||||||
from .crypto import sha256d
|
from .crypto import sha256d
|
||||||
from .bitcoin import hash_decode, hash_encode
|
from .bitcoin import hash_decode, hash_encode
|
||||||
from .transaction import Transaction
|
from .transaction import Transaction
|
||||||
@@ -153,7 +153,7 @@ class SPV(NetworkJobOnDefaultServer):
|
|||||||
if len(item) != 32:
|
if len(item) != 32:
|
||||||
raise MerkleVerificationFailure('all merkle branch items have to 32 bytes long')
|
raise MerkleVerificationFailure('all merkle branch items have to 32 bytes long')
|
||||||
inner_node = (item + h) if (index & 1) else (h + item)
|
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)
|
h = sha256d(inner_node)
|
||||||
index >>= 1
|
index >>= 1
|
||||||
if index != 0:
|
if index != 0:
|
||||||
|
|||||||
+1
-1
@@ -57,7 +57,7 @@ from .util import (NotEnoughFunds, UserCancelled, profiler, OldTaskGroup, ignore
|
|||||||
format_satoshis, format_fee_satoshis, NoDynamicFeeEstimates,
|
format_satoshis, format_fee_satoshis, NoDynamicFeeEstimates,
|
||||||
WalletFileException, BitcoinException,
|
WalletFileException, BitcoinException,
|
||||||
InvalidPassword, format_time, timestamp_to_datetime, Satoshis,
|
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 .simple_config import SimpleConfig, FEE_RATIO_HIGH_WARNING, FEERATE_WARNING_HIGH_FEE
|
||||||
from .bitcoin import COIN, TYPE_ADDRESS
|
from .bitcoin import COIN, TYPE_ADDRESS
|
||||||
from .bitcoin import is_address, address_to_script, is_minikey, relayfee, dust_threshold
|
from .bitcoin import is_address, address_to_script, is_minikey, relayfee, dust_threshold
|
||||||
|
|||||||
+3
-3
@@ -28,7 +28,7 @@ import time
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from . import util
|
from . import util
|
||||||
from .util import profiler, bh2u
|
from .util import profiler
|
||||||
from .logging import get_logger
|
from .logging import get_logger
|
||||||
|
|
||||||
|
|
||||||
@@ -272,10 +272,10 @@ class X509(object):
|
|||||||
# Subject Key Identifier
|
# Subject Key Identifier
|
||||||
r = value.root()
|
r = value.root()
|
||||||
value = value.get_value_of_type(r, 'OCTET STRING')
|
value = value.get_value_of_type(r, 'OCTET STRING')
|
||||||
self.SKI = bh2u(value)
|
self.SKI = value.hex()
|
||||||
elif oid == '2.5.29.35':
|
elif oid == '2.5.29.35':
|
||||||
# Authority Key Identifier
|
# Authority Key Identifier
|
||||||
self.AKI = bh2u(value.get_sequence()[0])
|
self.AKI = value.get_sequence()[0].hex()
|
||||||
else:
|
else:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user