Browse Source

whitespace, code style

master
Sander van Grieken 3 years ago
parent
commit
ac341d9565
  1. 32
      electrum/payment_identifier.py

32
electrum/payment_identifier.py

@ -2,7 +2,7 @@ import asyncio
import urllib import urllib
import re import re
from decimal import Decimal, InvalidOperation from decimal import Decimal, InvalidOperation
from typing import NamedTuple, Optional, Callable, Any, Sequence from typing import NamedTuple, Optional, Callable, Any, Sequence, List
from urllib.parse import urlparse from urllib.parse import urlparse
from . import bitcoin from . import bitcoin
@ -16,6 +16,7 @@ from .bitcoin import COIN, TOTAL_COIN_SUPPLY_LIMIT_IN_BTC, opcodes, construct_sc
from .lnaddr import lndecode, LnDecodeException, LnInvoiceException from .lnaddr import lndecode, LnDecodeException, LnInvoiceException
from .lnutil import IncompatibleOrInsaneFeatures from .lnutil import IncompatibleOrInsaneFeatures
def maybe_extract_lightning_payment_identifier(data: str) -> Optional[str]: def maybe_extract_lightning_payment_identifier(data: str) -> Optional[str]:
data = data.strip() # whitespaces data = data.strip() # whitespaces
data = data.lower() data = data.lower()
@ -36,7 +37,8 @@ BITCOIN_BIP21_URI_SCHEME = 'bitcoin'
LIGHTNING_URI_SCHEME = 'lightning' LIGHTNING_URI_SCHEME = 'lightning'
class InvalidBitcoinURI(Exception): pass class InvalidBitcoinURI(Exception):
pass
def parse_bip21_URI(uri: str) -> dict: def parse_bip21_URI(uri: str) -> dict:
@ -122,7 +124,6 @@ def parse_bip21_URI(uri: str) -> dict:
return out return out
def create_bip21_uri(addr, amount_sat: Optional[int], message: Optional[str], def create_bip21_uri(addr, amount_sat: Optional[int], message: Optional[str],
*, extra_query_params: Optional[dict] = None) -> str: *, extra_query_params: Optional[dict] = None) -> str:
if not bitcoin.is_address(addr): if not bitcoin.is_address(addr):
@ -131,9 +132,9 @@ def create_bip21_uri(addr, amount_sat: Optional[int], message: Optional[str],
extra_query_params = {} extra_query_params = {}
query = [] query = []
if amount_sat: if amount_sat:
query.append('amount=%s'%format_satoshis_plain(amount_sat)) query.append('amount=%s' % format_satoshis_plain(amount_sat))
if message: if message:
query.append('message=%s'%urllib.parse.quote(message)) query.append('message=%s' % urllib.parse.quote(message))
for k, v in extra_query_params.items(): for k, v in extra_query_params.items():
if not isinstance(k, str) or k != urllib.parse.quote(k): if not isinstance(k, str) or k != urllib.parse.quote(k):
raise Exception(f"illegal key for URI: {repr(k)}") raise Exception(f"illegal key for URI: {repr(k)}")
@ -145,12 +146,11 @@ def create_bip21_uri(addr, amount_sat: Optional[int], message: Optional[str],
path=addr, path=addr,
params='', params='',
query='&'.join(query), query='&'.join(query),
fragment='', fragment=''
) )
return str(urllib.parse.urlunparse(p)) return str(urllib.parse.urlunparse(p))
def is_uri(data: str) -> bool: def is_uri(data: str) -> bool:
data = data.lower() data = data.lower()
if (data.startswith(LIGHTNING_URI_SCHEME + ":") or if (data.startswith(LIGHTNING_URI_SCHEME + ":") or
@ -159,19 +159,21 @@ def is_uri(data: str) -> bool:
return False return False
class FailedToParsePaymentIdentifier(Exception): class FailedToParsePaymentIdentifier(Exception):
pass pass
class PayToLineError(NamedTuple): class PayToLineError(NamedTuple):
line_content: str line_content: str
exc: Exception exc: Exception
idx: int = 0 # index of line idx: int = 0 # index of line
is_multiline: bool = False is_multiline: bool = False
RE_ALIAS = r'(.*?)\s*\<([0-9A-Za-z]{1,})\>' RE_ALIAS = r'(.*?)\s*\<([0-9A-Za-z]{1,})\>'
RE_EMAIL = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b' RE_EMAIL = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b'
class PaymentIdentifier(Logger): class PaymentIdentifier(Logger):
""" """
Takes: Takes:
@ -235,7 +237,7 @@ class PaymentIdentifier(Logger):
text = text.strip() text = text.strip()
if not text: if not text:
return return
if outputs:= self._parse_as_multiline(text): if outputs := self._parse_as_multiline(text):
self._type = 'multiline' self._type = 'multiline'
self.multiline_outputs = outputs self.multiline_outputs = outputs
elif invoice_or_lnurl := maybe_extract_lightning_payment_identifier(text): elif invoice_or_lnurl := maybe_extract_lightning_payment_identifier(text):
@ -286,7 +288,7 @@ class PaymentIdentifier(Logger):
# filter out empty lines # filter out empty lines
lines = text.split('\n') lines = text.split('\n')
lines = [i for i in lines if i] lines = [i for i in lines if i]
is_multiline = len(lines)>1 is_multiline = len(lines) > 1
outputs = [] # type: List[PartialTxOutput] outputs = [] # type: List[PartialTxOutput]
errors = [] errors = []
total = 0 total = 0
@ -357,7 +359,7 @@ class PaymentIdentifier(Logger):
def parse_address(self, line): def parse_address(self, line):
r = line.strip() r = line.strip()
m = re.match('^'+RE_ALIAS+'$', r) m = re.match('^' + RE_ALIAS + '$', r)
address = str(m.group(2) if m else r) address = str(m.group(2) if m else r)
assert bitcoin.is_address(address) assert bitcoin.is_address(address)
return address return address
@ -447,12 +449,12 @@ class PaymentIdentifier(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 = lnaddr.pubkey.serialize().hex() 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
break break
else: else:
description = '' description = ''
amount = lnaddr.get_amount_sat() amount = lnaddr.get_amount_sat()
return pubkey, amount, description return pubkey, amount, description
@ -502,7 +504,7 @@ class PaymentIdentifier(Logger):
on_success(self) on_success(self)
@log_exceptions @log_exceptions
async def round_2(self, on_success, amount_sat:int=None, comment=None): async def round_2(self, on_success, amount_sat: int = None, comment: str = None):
from .invoices import Invoice from .invoices import Invoice
if self.lnurl: if self.lnurl:
if not (self.lnurl_data.min_sendable_sat <= amount_sat <= self.lnurl_data.max_sendable_sat): if not (self.lnurl_data.min_sendable_sat <= amount_sat <= self.lnurl_data.max_sendable_sat):
@ -510,7 +512,7 @@ class PaymentIdentifier(Logger):
return return
if self.lnurl_data.comment_allowed == 0: if self.lnurl_data.comment_allowed == 0:
comment = None comment = None
params = {'amount': amount_sat * 1000 } params = {'amount': amount_sat * 1000}
if comment: if comment:
params['comment'] = comment params['comment'] = comment
try: try:

Loading…
Cancel
Save