remove unnecessary argument encoding from bytes.decode() and str.encode()

the encoding parameter defaults to utf-8, so it's not needed
This commit is contained in:
Pavol Rusnak 2022-12-29 16:50:05 +01:00
parent c9b02a6470
commit 3d0c66f0f6
No known key found for this signature in database
GPG Key ID: 91F3B339B9A02A3D
20 changed files with 31 additions and 33 deletions

View File

@ -74,7 +74,7 @@ def decode(pr: str) -> Invoice:
data_length = len(tagdata) / 5 data_length = len(tagdata) / 5
if tag == "d": if tag == "d":
invoice.description = _trim_to_bytes(tagdata).decode("utf-8") invoice.description = _trim_to_bytes(tagdata).decode()
elif tag == "h" and data_length == 52: elif tag == "h" and data_length == 52:
invoice.description_hash = _trim_to_bytes(tagdata).hex() invoice.description_hash = _trim_to_bytes(tagdata).hex()
elif tag == "p" and data_length == 52: elif tag == "p" and data_length == 52:
@ -260,7 +260,7 @@ class LnAddr(object):
def __str__(self): def __str__(self):
return "LnAddr[{}, amount={}{} tags=[{}]]".format( return "LnAddr[{}, amount={}{} tags=[{}]]".format(
bytes.hex(self.pubkey.serialize()).decode("utf-8"), bytes.hex(self.pubkey.serialize()).decode(),
self.amount, self.amount,
self.currency, self.currency,
", ".join([k + "=" + str(v) for k, v in self.tags]), ", ".join([k + "=" + str(v) for k, v in self.tags]),

View File

@ -46,8 +46,8 @@ class Wallet(BaseModel):
return "" return ""
def lnurlauth_key(self, domain: str) -> SigningKey: def lnurlauth_key(self, domain: str) -> SigningKey:
hashing_key = hashlib.sha256(self.id.encode("utf-8")).digest() hashing_key = hashlib.sha256(self.id.encode()).digest()
linking_key = hmac.digest(hashing_key, domain.encode("utf-8"), "sha256") linking_key = hmac.digest(hashing_key, domain.encode(), "sha256")
return SigningKey.from_string( return SigningKey.from_string(
linking_key, curve=SECP256k1, hashfunc=hashlib.sha256 linking_key, curve=SECP256k1, hashfunc=hashlib.sha256

View File

@ -536,7 +536,7 @@ async def api_lnurlscan(code: str, wallet: WalletTypeInfo = Depends(get_key_type
params.update( params.update(
description_hash=hashlib.sha256( description_hash=hashlib.sha256(
data["metadata"].encode("utf-8") data["metadata"].encode()
).hexdigest() ).hexdigest()
) )
metadata = json.loads(data["metadata"]) metadata = json.loads(data["metadata"])

View File

@ -213,7 +213,7 @@ async def lnurlp_callback(
memo=f"Refund {hit_id}", memo=f"Refund {hit_id}",
unhashed_description=LnurlPayMetadata( unhashed_description=LnurlPayMetadata(
json.dumps([["text/plain", "Refund"]]) json.dumps([["text/plain", "Refund"]])
).encode("utf-8"), ).encode(),
extra={"refund": hit_id}, extra={"refund": hit_id},
) )

View File

@ -55,7 +55,7 @@ async def create_swap(data: CreateSubmarineSwap) -> SubmarineSwap:
raise raise
refund_privkey = ec.PrivateKey(os.urandom(32), True, net) refund_privkey = ec.PrivateKey(os.urandom(32), True, net)
refund_pubkey_hex = bytes.hex(refund_privkey.sec()).decode("UTF-8") refund_pubkey_hex = bytes.hex(refund_privkey.sec()).decode()
res = req_wrap( res = req_wrap(
"post", "post",
@ -120,7 +120,7 @@ async def create_reverse_swap(
return False return False
claim_privkey = ec.PrivateKey(os.urandom(32), True, net) claim_privkey = ec.PrivateKey(os.urandom(32), True, net)
claim_pubkey_hex = bytes.hex(claim_privkey.sec()).decode("UTF-8") claim_pubkey_hex = bytes.hex(claim_privkey.sec()).decode()
preimage = os.urandom(32) preimage = os.urandom(32)
preimage_hash = sha256(preimage).hexdigest() preimage_hash = sha256(preimage).hexdigest()

View File

@ -75,7 +75,7 @@ async def lnurl_callback(
memo=cp.lnurl_title, memo=cp.lnurl_title,
unhashed_description=( unhashed_description=(
LnurlPayMetadata(json.dumps([["text/plain", str(cp.lnurl_title)]])) LnurlPayMetadata(json.dumps([["text/plain", str(cp.lnurl_title)]]))
).encode("utf-8"), ).encode(),
extra={"tag": "copilot", "copilotid": cp.id, "comment": comment}, extra={"tag": "copilot", "copilotid": cp.id, "comment": comment},
) )
payResponse = {"pr": payment_request, "routes": []} payResponse = {"pr": payment_request, "routes": []}

View File

@ -90,7 +90,7 @@ async def lnurl_callback(
wallet_id=ls.wallet, wallet_id=ls.wallet,
amount=int(amount_received / 1000), amount=int(amount_received / 1000),
memo=await track.fullname(), memo=await track.fullname(),
unhashed_description=(await track.lnurlpay_metadata()).encode("utf-8"), unhashed_description=(await track.lnurlpay_metadata()).encode(),
extra={"tag": "livestream", "track": track.id, "comment": comment}, extra={"tag": "livestream", "track": track.id, "comment": comment},
) )

View File

@ -72,7 +72,7 @@ async def lnurl_callback(address_id, amount: int = Query(...)):
"amount": int(amount_received / 1000), "amount": int(amount_received / 1000),
"description_hash": ( "description_hash": (
await address.lnurlpay_metadata(domain=domain.domain) await address.lnurlpay_metadata(domain=domain.domain)
).encode("utf-8"), ).encode(),
"extra": {"tag": f"Payment to {address.username}@{domain.domain}"}, "extra": {"tag": f"Payment to {address.username}@{domain.domain}"},
}, },
timeout=40, timeout=40,

View File

@ -23,7 +23,7 @@ async def check_wallet(
) )
t = api_key_header_auth.split(" ")[1] t = api_key_header_auth.split(" ")[1]
_, token = b64decode(t).decode("utf-8").split(":") _, token = b64decode(t).decode().split(":")
return await get_key_type(r, api_key_header=token) return await get_key_type(r, api_key_header=token)

View File

@ -35,9 +35,9 @@ async def lndhub_auth(data: AuthData):
token = ( token = (
data.refresh_token data.refresh_token
if data.refresh_token if data.refresh_token
else urlsafe_b64encode( else urlsafe_b64encode((data.login + ":" + data.password).encode()).decode(
(data.login + ":" + data.password).encode("utf-8") "ascii"
).decode("ascii") )
) )
return {"refresh_token": token, "access_token": token} return {"refresh_token": token, "access_token": token}

View File

@ -246,7 +246,7 @@ async def lnurl_callback(
wallet_id=device.wallet, wallet_id=device.wallet,
amount=int(lnurldevicepayment.sats / 1000), amount=int(lnurldevicepayment.sats / 1000),
memo=device.id + " PIN " + str(lnurldevicepayment.pin), memo=device.id + " PIN " + str(lnurldevicepayment.pin),
unhashed_description=device.lnurlpay_metadata.encode("utf-8"), unhashed_description=device.lnurlpay_metadata.encode(),
extra={ extra={
"tag": "Switch", "tag": "Switch",
"pin": str(lnurldevicepayment.pin), "pin": str(lnurldevicepayment.pin),
@ -267,7 +267,7 @@ async def lnurl_callback(
wallet_id=device.wallet, wallet_id=device.wallet,
amount=int(lnurldevicepayment.sats / 1000), amount=int(lnurldevicepayment.sats / 1000),
memo=device.title, memo=device.title,
unhashed_description=device.lnurlpay_metadata.encode("utf-8"), unhashed_description=device.lnurlpay_metadata.encode(),
extra={"tag": "PoS"}, extra={"tag": "PoS"},
) )
lnurldevicepayment = await update_lnurldevicepayment( lnurldevicepayment = await update_lnurldevicepayment(

View File

@ -87,7 +87,7 @@ async def api_lnurl_callback(request: Request, link_id):
wallet_id=link.wallet, wallet_id=link.wallet,
amount=int(amount_received / 1000), amount=int(amount_received / 1000),
memo=link.description, memo=link.description,
unhashed_description=link.lnurlpay_metadata.encode("utf-8"), unhashed_description=link.lnurlpay_metadata.encode(),
extra={ extra={
"tag": "lnurlp", "tag": "lnurlp",
"link": link.id, "link": link.id,

View File

@ -73,7 +73,7 @@ async def lnurl_callback(request: Request, item_id: int):
wallet_id=shop.wallet, wallet_id=shop.wallet,
amount=int(amount_received / 1000), amount=int(amount_received / 1000),
memo=item.name, memo=item.name,
unhashed_description=(await item.lnurlpay_metadata()).encode("utf-8"), unhashed_description=(await item.lnurlpay_metadata()).encode(),
extra={"tag": "offlineshop", "item": item.id}, extra={"tag": "offlineshop", "item": item.id},
) )
except Exception as exc: except Exception as exc:

View File

@ -76,7 +76,7 @@ async def api_lnurlp_callback(
wallet_id=link.wallet, wallet_id=link.wallet,
amount=int(amount_received / 1000), amount=int(amount_received / 1000),
memo="Satsdice bet", memo="Satsdice bet",
unhashed_description=link.lnurlpay_metadata.encode("utf-8"), unhashed_description=link.lnurlpay_metadata.encode(),
extra={"tag": "satsdice", "link": link.id, "comment": "comment"}, extra={"tag": "satsdice", "link": link.id, "comment": "comment"},
) )

View File

@ -6,11 +6,11 @@ def decode(lnurl: str) -> str:
assert data assert data
bech32_data = convertbits(data, 5, 8, False) bech32_data = convertbits(data, 5, 8, False)
assert bech32_data assert bech32_data
return bytes(bech32_data).decode("utf-8") return bytes(bech32_data).decode()
def encode(url: str) -> str: def encode(url: str) -> str:
bech32_data = convertbits(url.encode("utf-8"), 8, 5, True) bech32_data = convertbits(url.encode(), 8, 5, True)
assert bech32_data assert bech32_data
lnurl = bech32_encode("lnurl", bech32_data) lnurl = bech32_encode("lnurl", bech32_data)
return lnurl.upper() return lnurl.upper()

View File

@ -96,7 +96,7 @@ class CoreLightningWallet(Wallet):
r = self.ln.invoice( r = self.ln.invoice(
msatoshi=msat, msatoshi=msat,
label=label, label=label,
description=unhashed_description.decode("utf-8") description=unhashed_description.decode()
if unhashed_description if unhashed_description
else memo, else memo,
exposeprivatechannels=True, exposeprivatechannels=True,

View File

@ -44,7 +44,7 @@ class EclairWallet(Wallet):
self.ws_url = f"ws://{urllib.parse.urlsplit(self.url).netloc}/ws" self.ws_url = f"ws://{urllib.parse.urlsplit(self.url).netloc}/ws"
passw = settings.eclair_pass passw = settings.eclair_pass
encodedAuth = base64.b64encode(f":{passw}".encode("utf-8")) encodedAuth = base64.b64encode(f":{passw}".encode())
auth = str(encodedAuth, "utf-8") auth = str(encodedAuth, "utf-8")
self.auth = {"Authorization": f"Basic {auth}"} self.auth = {"Authorization": f"Basic {auth}"}

View File

@ -23,8 +23,8 @@ class FakeWallet(Wallet):
secret: str = settings.fake_wallet_secret secret: str = settings.fake_wallet_secret
privkey: str = hashlib.pbkdf2_hmac( privkey: str = hashlib.pbkdf2_hmac(
"sha256", "sha256",
secret.encode("utf-8"), secret.encode(),
("FakeWallet").encode("utf-8"), ("FakeWallet").encode(),
2048, 2048,
32, 32,
).hex() ).hex()
@ -68,9 +68,7 @@ class FakeWallet(Wallet):
data["description"] = memo data["description"] = memo
randomHash = ( randomHash = (
data["privkey"][:6] data["privkey"][:6]
+ hashlib.sha256(str(random.getrandbits(256)).encode("utf-8")).hexdigest()[ + hashlib.sha256(str(random.getrandbits(256)).encode()).hexdigest()[6:]
6:
]
) )
data["paymenthash"] = randomHash data["paymenthash"] = randomHash
payment_request = encode(data) payment_request = encode(data)

View File

@ -71,7 +71,7 @@ def b64_to_bytes(checking_id: str) -> bytes:
def bytes_to_b64(r_hash: bytes) -> str: def bytes_to_b64(r_hash: bytes) -> str:
return base64.b64encode(r_hash).decode("utf-8").replace("/", "_") return base64.b64encode(r_hash).decode().replace("/", "_")
def hex_to_b64(hex_str: str) -> str: def hex_to_b64(hex_str: str) -> str:

View File

@ -215,7 +215,7 @@ async def test_api_payment_with_key(invoice, inkey_headers_from):
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_create_invoice_with_description_hash(client, inkey_headers_to): async def test_create_invoice_with_description_hash(client, inkey_headers_to):
data = await get_random_invoice_data() data = await get_random_invoice_data()
descr_hash = hashlib.sha256("asdasdasd".encode("utf-8")).hexdigest() descr_hash = hashlib.sha256("asdasdasd".encode()).hexdigest()
data["description_hash"] = descr_hash data["description_hash"] = descr_hash
response = await client.post( response = await client.post(
@ -232,8 +232,8 @@ async def test_create_invoice_with_description_hash(client, inkey_headers_to):
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_create_invoice_with_unhashed_description(client, inkey_headers_to): async def test_create_invoice_with_unhashed_description(client, inkey_headers_to):
data = await get_random_invoice_data() data = await get_random_invoice_data()
descr_hash = hashlib.sha256("asdasdasd".encode("utf-8")).hexdigest() descr_hash = hashlib.sha256("asdasdasd".encode()).hexdigest()
data["unhashed_description"] = "asdasdasd".encode("utf-8").hex() data["unhashed_description"] = "asdasdasd".encode().hex()
response = await client.post( response = await client.post(
"/api/v1/payments", json=data, headers=inkey_headers_to "/api/v1/payments", json=data, headers=inkey_headers_to