use bytes.fromhex/hex builtins instead of binascii.hexlify/unhexlify

This commit is contained in:
Pavol Rusnak 2022-12-28 12:36:39 +01:00
parent 89aa4a1de9
commit a377381942
No known key found for this signature in database
GPG Key ID: 91F3B339B9A02A3D
10 changed files with 22 additions and 35 deletions

View File

@ -1,7 +1,6 @@
import hashlib
import re
import time
from binascii import unhexlify
from decimal import Decimal
from typing import List, NamedTuple, Optional
@ -108,7 +107,7 @@ def decode(pr: str) -> Invoice:
message = bytearray([ord(c) for c in hrp]) + data.tobytes()
sig = signature[0:64]
if invoice.payee:
key = VerifyingKey.from_string(unhexlify(invoice.payee), curve=SECP256k1)
key = VerifyingKey.from_string(bytes.fromhex(invoice.payee), curve=SECP256k1)
key.verify(sig, message, hashlib.sha256, sigdecode=sigdecode_string)
else:
keys = VerifyingKey.from_public_key_recovery(
@ -131,7 +130,7 @@ def encode(options):
if options["timestamp"]:
addr.date = int(options["timestamp"])
addr.paymenthash = unhexlify(options["paymenthash"])
addr.paymenthash = bytes.fromhex(options["paymenthash"])
if options["description"]:
addr.tags.append(("d", options["description"]))
@ -149,8 +148,8 @@ def encode(options):
while len(splits) >= 5:
route.append(
(
unhexlify(splits[0]),
unhexlify(splits[1]),
bytes.fromhex(splits[0]),
bytes.fromhex(splits[1]),
int(splits[2]),
int(splits[3]),
int(splits[4]),
@ -235,7 +234,7 @@ def lnencode(addr, privkey):
raise ValueError("Must include either 'd' or 'h'")
# We actually sign the hrp, then data (padded to 8 bits with zeroes).
privkey = secp256k1.PrivateKey(bytes(unhexlify(privkey)))
privkey = secp256k1.PrivateKey(bytes.fromhex(privkey))
sig = privkey.ecdsa_sign_recoverable(
bytearray([ord(c) for c in hrp]) + data.tobytes()
)
@ -261,7 +260,7 @@ class LnAddr(object):
def __str__(self):
return "LnAddr[{}, amount={}{} tags=[{}]]".format(
hexlify(self.pubkey.serialize()).decode("utf-8"),
bytes.hex(self.pubkey.serialize()).decode("utf-8"),
self.amount,
self.currency,
", ".join([k + "=" + str(v) for k, v in self.tags]),

View File

@ -1,6 +1,5 @@
import asyncio
import json
from binascii import unhexlify
from io import BytesIO
from typing import Dict, List, Optional, Tuple
from urllib.parse import parse_qs, urlparse
@ -308,7 +307,7 @@ async def perform_lnurlauth(
) -> Optional[LnurlErrorResponse]:
cb = urlparse(callback)
k1 = unhexlify(parse_qs(cb.query)["k1"][0])
k1 = bytes.fromhex(parse_qs(cb.query)["k1"][0])
key = wallet.wallet.lnurlauth_key(cb.netloc)

View File

@ -1,5 +1,4 @@
import asyncio
import binascii
import hashlib
import json
import time
@ -145,16 +144,14 @@ async def api_payments_create_invoice(data: CreateInvoiceData, wallet: Wallet):
if data.description_hash or data.unhashed_description:
try:
description_hash = (
binascii.unhexlify(data.description_hash)
if data.description_hash
else b""
bytes.fromhex(data.description_hash) if data.description_hash else b""
)
unhashed_description = (
binascii.unhexlify(data.unhashed_description)
bytes.fromhex(data.unhashed_description)
if data.unhashed_description
else b""
)
except binascii.Error:
except ValueError:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
detail="'description_hash' and 'unhashed_description' must be a valid hex strings",

View File

@ -2,7 +2,6 @@ import base64
import hashlib
import hmac
import urllib
from binascii import unhexlify
from http import HTTPStatus
from typing import Dict
@ -19,7 +18,7 @@ def generate_bleskomat_lnurl_signature(
payload: str, api_key_secret: str, api_key_encoding: str = "hex"
):
if api_key_encoding == "hex":
key = unhexlify(api_key_secret)
key = bytes.fromhex(api_key_secret)
elif api_key_encoding == "base64":
key = base64.b64decode(api_key_secret)
else:

View File

@ -1,6 +1,5 @@
import asyncio
import os
from binascii import hexlify, unhexlify
from hashlib import sha256
from typing import Awaitable, Union
@ -56,7 +55,7 @@ async def create_swap(data: CreateSubmarineSwap) -> SubmarineSwap:
raise
refund_privkey = ec.PrivateKey(os.urandom(32), True, net)
refund_pubkey_hex = hexlify(refund_privkey.sec()).decode("UTF-8")
refund_pubkey_hex = bytes.hex(refund_privkey.sec()).decode("UTF-8")
res = req_wrap(
"post",
@ -121,7 +120,7 @@ async def create_reverse_swap(
return False
claim_privkey = ec.PrivateKey(os.urandom(32), True, net)
claim_pubkey_hex = hexlify(claim_privkey.sec()).decode("UTF-8")
claim_pubkey_hex = bytes.hex(claim_privkey.sec()).decode("UTF-8")
preimage = os.urandom(32)
preimage_hash = sha256(preimage).hexdigest()
@ -311,12 +310,12 @@ async def create_onchain_tx(
sequence = 0xFFFFFFFE
else:
privkey = ec.PrivateKey.from_wif(swap.claim_privkey)
preimage = unhexlify(swap.preimage)
preimage = bytes.fromhex(swap.preimage)
onchain_address = swap.onchain_address
sequence = 0xFFFFFFFF
locktime = swap.timeout_block_height
redeem_script = unhexlify(swap.redeem_script)
redeem_script = bytes.fromhex(swap.redeem_script)
fees = get_fee_estimation()
@ -324,7 +323,7 @@ async def create_onchain_tx(
script_pubkey = script.address_to_scriptpubkey(onchain_address)
vin = [TransactionInput(unhexlify(txid), vout_cnt, sequence=sequence)]
vin = [TransactionInput(bytes.fromhex(txid), vout_cnt, sequence=sequence)]
vout = [TransactionOutput(vout_amount - fees, script_pubkey)]
tx = Transaction(vin=vin, vout=vout)

View File

@ -1,6 +1,5 @@
import asyncio
import json
from binascii import hexlify
import httpx
import websockets
@ -84,7 +83,7 @@ def get_mempool_blockheight() -> int:
async def send_onchain_tx(tx: Transaction):
raw = hexlify(tx.serialize())
raw = bytes.hex(tx.serialize())
logger.debug(f"Boltz - mempool sending onchain tx...")
req_wrap(
"post",

View File

@ -1,7 +1,6 @@
import os
import random
import time
from binascii import hexlify, unhexlify
from typing import Any, List, Optional, Union
from cashu.core.base import MintKeyset

View File

@ -1,10 +1,8 @@
from binascii import unhexlify
from lnbits.bolt11 import Invoice
def to_buffer(payment_hash: str):
return {"type": "Buffer", "data": [b for b in unhexlify(payment_hash)]}
return {"type": "Buffer", "data": [b for b in bytes.fromhex(payment_hash)]}
def decoded_as_lndhub(invoice: Invoice):

View File

@ -8,7 +8,6 @@ except ImportError: # pragma: nocover
import asyncio
import base64
import binascii
import hashlib
from os import environ, error
from typing import AsyncGenerator, Dict, Optional
@ -229,8 +228,8 @@ class LndWallet(Wallet):
try:
r_hash = hex_to_bytes(checking_id)
if len(r_hash) != 32:
raise binascii.Error
except binascii.Error:
raise ValueError
except ValueError:
# this may happen if we switch between backend wallets
# that use different checking_id formats
return PaymentStatus(None)
@ -250,8 +249,8 @@ class LndWallet(Wallet):
try:
r_hash = hex_to_bytes(checking_id)
if len(r_hash) != 32:
raise binascii.Error
except binascii.Error:
raise ValueError
except ValueError:
# this may happen if we switch between backend wallets
# that use different checking_id formats
return PaymentStatus(None)

View File

@ -1,5 +1,4 @@
import hashlib
from binascii import hexlify
import pytest
import pytest_asyncio