• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

spesmilo / electrum / 5735552722403328

16 May 2025 10:28AM UTC coverage: 59.722% (+0.002%) from 59.72%
5735552722403328

Pull #9833

CirrusCI

f321x
make lightning dns seed fetching async
Pull Request #9833: dns: use async dnspython interface

22 of 50 new or added lines in 7 files covered. (44.0%)

1107 existing lines in 11 files now uncovered.

21549 of 36082 relevant lines covered (59.72%)

2.39 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

14.36
/electrum/paymentrequest.py
1
#!/usr/bin/env python
2
#
3
# Electrum - lightweight Bitcoin client
4
# Copyright (C) 2014 Thomas Voegtlin
5
#
6
# Permission is hereby granted, free of charge, to any person
7
# obtaining a copy of this software and associated documentation files
8
# (the "Software"), to deal in the Software without restriction,
9
# including without limitation the rights to use, copy, modify, merge,
10
# publish, distribute, sublicense, and/or sell copies of the Software,
11
# and to permit persons to whom the Software is furnished to do so,
12
# subject to the following conditions:
13
#
14
# The above copyright notice and this permission notice shall be
15
# included in all copies or substantial portions of the Software.
16
#
17
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
21
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
22
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
23
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
# SOFTWARE.
25
import hashlib
4✔
26
import sys
4✔
27
import time
4✔
28
from typing import Optional, List, TYPE_CHECKING
4✔
29
import asyncio
4✔
30
import urllib.parse
4✔
31

32
import certifi
4✔
33
import aiohttp
4✔
34
import electrum_ecc as ecc
4✔
35

36

37
try:
4✔
38
    from . import paymentrequest_pb2 as pb2
4✔
39
except ImportError:
×
40
    sys.exit("Error: could not find paymentrequest_pb2.py. Create it with 'contrib/generate_payreqpb2.sh'")
×
41

42
from . import bitcoin, constants, util, transaction, x509, rsakey
4✔
43
from .util import (bfh, make_aiohttp_session, error_text_bytes_to_safe_str, get_running_loop,
4✔
44
                   get_asyncio_loop)
45
from .invoices import Invoice, get_id_from_onchain_outputs
4✔
46
from .bitcoin import address_to_script
4✔
47
from .transaction import PartialTxOutput
4✔
48
from .network import Network
4✔
49
from .logging import get_logger
4✔
50
from .contacts import Contacts
4✔
51

52
if TYPE_CHECKING:
4✔
53
    from .simple_config import SimpleConfig
×
54

55

56
_logger = get_logger(__name__)
4✔
57

58

59
REQUEST_HEADERS = {'Accept': 'application/bitcoin-paymentrequest', 'User-Agent': 'Electrum'}
4✔
60
ACK_HEADERS = {'Content-Type': 'application/bitcoin-payment', 'Accept': 'application/bitcoin-paymentack', 'User-Agent': 'Electrum'}
4✔
61

62
ca_path = certifi.where()
4✔
63
ca_list = None
4✔
64
ca_keyID = None
4✔
65

66

67
def load_ca_list():
4✔
68
    global ca_list, ca_keyID
69
    if ca_list is None:
×
70
        ca_list, ca_keyID = x509.load_certificates(ca_path)
×
71

72

73
async def get_payment_request(url: str) -> 'PaymentRequest':
4✔
74
    u = urllib.parse.urlparse(url)
×
75
    error = None
×
76
    if u.scheme in ('http', 'https'):
×
77
        resp_content = None
×
78
        try:
×
79
            proxy = Network.get_instance().proxy
×
80
            async with make_aiohttp_session(proxy, headers=REQUEST_HEADERS) as session:
×
81
                async with session.get(url) as response:
×
82
                    resp_content = await response.read()
×
83
                    response.raise_for_status()
×
84
                    # Guard against `bitcoin:`-URIs with invalid payment request URLs
85
                    if "Content-Type" not in response.headers \
×
86
                    or response.headers["Content-Type"] != "application/bitcoin-paymentrequest":
87
                        data = None
×
88
                        error = "payment URL not pointing to a payment request handling server"
×
89
                    else:
90
                        data = resp_content
×
91
                    data_len = len(data) if data is not None else None
×
92
                    _logger.info(f'fetched payment request {url} {data_len}')
×
93
        except (aiohttp.ClientError, asyncio.TimeoutError) as e:
×
94
            error = f"Error while contacting payment URL: {url}.\nerror type: {type(e)}"
×
95
            if isinstance(e, aiohttp.ClientResponseError):
×
96
                error += f"\nGot HTTP status code {e.status}."
×
97
                if resp_content:
×
98
                    error_text_received = error_text_bytes_to_safe_str(resp_content)
×
99
                    error_text_received = error_text_received[:400]
×
100
                    error_oneline = ' -- '.join(error.split('\n'))
×
101
                    _logger.info(f"{error_oneline} -- [DO NOT TRUST THIS MESSAGE] "
×
102
                                 f"{repr(e)} text: {error_text_received}")
103
            data = None
×
104
    else:
105
        data = None
×
106
        error = f"Unknown scheme for payment request. URL: {url}"
×
107
    pr = PaymentRequest(data, error=error)
×
108
    loop = get_running_loop()
×
109
    # do x509/dnssec verification now (in separate thread, to avoid blocking event loop).
110
    # we still expect the caller to at least check pr.error!
111
    await loop.run_in_executor(None, pr.verify)
×
112
    return pr
×
113

114

115
class PaymentRequest:
4✔
116

117
    def __init__(self, data: bytes, *, error=None):
4✔
118
        self.raw = data
×
119
        self.error = error  # type: Optional[str]
×
120
        self._verified_success = None  # caches result of _verify
×
121
        self._verified_success_msg = None  # type: Optional[str]
×
122
        self._parse(data)
×
123
        self.requestor = None # known after verify
×
124
        self.tx = None
×
125

126
    def __str__(self):
4✔
127
        return str(self.raw)
×
128

129
    def _parse(self, r: bytes):
4✔
130
        self.outputs = []  # type: List[PartialTxOutput]
×
131
        if self.error:
×
132
            return
×
133
        try:
×
134
            self.data = pb2.PaymentRequest()
×
135
            self.data.ParseFromString(r)
×
136
        except Exception:
×
137
            self.error = "cannot parse payment request"
×
138
            return
×
139
        self.details = pb2.PaymentDetails()
×
140
        self.details.ParseFromString(self.data.serialized_payment_details)
×
141
        pr_network = self.details.network
×
142
        client_network = 'test' if constants.net.TESTNET else 'main'
×
143
        if pr_network != client_network:
×
144
            self.error = (f'Payment request network "{pr_network}" does not'
×
145
                          f' match client network "{client_network}".')
146
            return
×
147
        for o in self.details.outputs:
×
148
            addr = transaction.get_address_from_output_script(o.script)
×
149
            if not addr:
×
150
                # TODO maybe rm restriction but then get_requestor and get_id need changes
151
                self.error = "only addresses are allowed as outputs"
×
152
                return
×
153
            self.outputs.append(PartialTxOutput.from_address_and_value(addr, o.amount))
×
154
        self.memo = self.details.memo
×
155
        self.payment_url = self.details.payment_url
×
156

157
    def verify(self) -> bool:
4✔
158
        # FIXME: we should enforce that this method was called before we attempt payment
159
        # note: this method might do network requests (at least for verify_dnssec)
160
        if self._verified_success is True:
×
161
            return True
×
162
        if self.error:
×
163
            return False
×
164
        if not self.raw:
×
165
            self.error = "Empty request"
×
166
            return False
×
167
        pr = pb2.PaymentRequest()
×
168
        try:
×
169
            pr.ParseFromString(self.raw)
×
170
        except Exception:
×
171
            self.error = "Error: Cannot parse payment request"
×
172
            return False
×
173
        if not pr.signature:
×
174
            # the address will be displayed as requestor
175
            self.requestor = None
×
176
            return True
×
177
        if pr.pki_type in ["x509+sha256", "x509+sha1"]:
×
178
            return self.verify_x509(pr)
×
179
        elif pr.pki_type in ["dnssec+btc", "dnssec+ecdsa"]:
×
NEW
180
            fut = asyncio.run_coroutine_threadsafe(self.verify_dnssec(pr), get_asyncio_loop())
×
NEW
181
            return fut.result()
×
182
        else:
183
            self.error = "ERROR: Unsupported PKI Type for Message Signature"
×
184
            return False
×
185

186
    def verify_x509(self, paymntreq):
4✔
187
        load_ca_list()
×
188
        if not ca_list:
×
189
            self.error = "Trusted certificate authorities list not found"
×
190
            return False
×
191
        cert = pb2.X509Certificates()
×
192
        cert.ParseFromString(paymntreq.pki_data)
×
193
        # verify the chain of certificates
194
        try:
×
195
            x, ca = verify_cert_chain(cert.certificate)
×
196
        except BaseException as e:
×
197
            _logger.exception('')
×
198
            self.error = str(e)
×
199
            return False
×
200
        # get requestor name
201
        self.requestor = x.get_common_name()
×
202
        if self.requestor.startswith('*.'):
×
203
            self.requestor = self.requestor[2:]
×
204
        # verify the BIP70 signature
205
        pubkey0 = rsakey.RSAKey(x.modulus, x.exponent)
×
206
        sig = paymntreq.signature
×
207
        paymntreq.signature = b''
×
208
        s = paymntreq.SerializeToString()
×
209
        sigBytes = bytearray(sig)
×
210
        msgBytes = bytearray(s)
×
211
        if paymntreq.pki_type == "x509+sha256":
×
212
            hashBytes = bytearray(hashlib.sha256(msgBytes).digest())
×
213
            verify = pubkey0.verify(sigBytes, x509.PREFIX_RSA_SHA256 + hashBytes)
×
214
        elif paymntreq.pki_type == "x509+sha1":
×
215
            verify = pubkey0.hashAndVerify(sigBytes, msgBytes)
×
216
        else:
217
            self.error = f"ERROR: unknown pki_type {paymntreq.pki_type} in Payment Request"
×
218
            return False
×
219
        if not verify:
×
220
            self.error = "ERROR: Invalid Signature for Payment Request Data"
×
221
            return False
×
222
        ### SIG Verified
223
        self._verified_success_msg = 'Signed by Trusted CA: ' + ca.get_common_name()
×
224
        self._verified_success = True
×
225
        return True
×
226

227
    async def verify_dnssec(self, pr):
4✔
228
        sig = pr.signature
×
229
        alias = pr.pki_data
×
NEW
230
        info: dict = await Contacts.resolve_openalias(alias)
×
231
        if info.get('validated') is not True:
×
232
            self.error = "Alias verification failed (DNSSEC)"
×
233
            return False
×
234
        if pr.pki_type == "dnssec+btc":
×
235
            self.requestor = alias
×
236
            address = info.get('address')
×
237
            pr.signature = b''
×
238
            message = pr.SerializeToString()
×
239
            if bitcoin.verify_usermessage_with_address(address, sig, message):
×
240
                self._verified_success_msg = 'Verified with DNSSEC'
×
241
                self._verified_success = True
×
242
                return True
×
243
            else:
244
                self.error = "verify failed"
×
245
                return False
×
246
        else:
247
            self.error = "unknown algo"
×
248
            return False
×
249

250
    def has_expired(self) -> Optional[bool]:
4✔
251
        if not hasattr(self, 'details'):
×
252
            return None
×
253
        return self.details.expires and self.details.expires < int(time.time())
×
254

255
    def get_time(self):
4✔
256
        return self.details.time
×
257

258
    def get_expiration_date(self):
4✔
259
        return self.details.expires
×
260

261
    def get_amount(self):
4✔
262
        return sum(map(lambda x:x.value, self.outputs))
×
263

264
    def get_address(self):
4✔
265
        o = self.outputs[0]
×
266
        addr = o.address
×
267
        assert addr
×
268
        return addr
×
269

270
    def get_requestor(self):
4✔
271
        return self.requestor if self.requestor else self.get_address()
×
272

273
    def get_verify_status(self) -> str:
4✔
274
        return (self.error or self._verified_success_msg) if self.requestor else "No Signature"
×
275

276
    def get_memo(self):
4✔
277
        return self.memo
×
278

279
    def get_name_for_export(self) -> Optional[str]:
4✔
280
        if not hasattr(self, 'details'):
×
281
            return None
×
282
        return get_id_from_onchain_outputs(self.outputs, timestamp=self.get_time())
×
283

284
    def get_outputs(self):
4✔
285
        return self.outputs[:]
×
286

287
    async def send_payment_and_receive_paymentack(self, raw_tx, refund_addr):
4✔
288
        pay_det = self.details
×
289
        if not self.details.payment_url:
×
290
            return False, "no url"
×
291
        paymnt = pb2.Payment()
×
292
        paymnt.merchant_data = pay_det.merchant_data
×
293
        paymnt.transactions.append(bfh(raw_tx))
×
294
        ref_out = paymnt.refund_to.add()
×
295
        ref_out.script = address_to_script(refund_addr)
×
296
        paymnt.memo = "Paid using Electrum"
×
297
        pm = paymnt.SerializeToString()
×
298
        payurl = urllib.parse.urlparse(pay_det.payment_url)
×
299
        resp_content = None
×
300
        try:
×
301
            proxy = Network.get_instance().proxy
×
302
            async with make_aiohttp_session(proxy, headers=ACK_HEADERS) as session:
×
303
                async with session.post(payurl.geturl(), data=pm) as response:
×
304
                    resp_content = await response.read()
×
305
                    response.raise_for_status()
×
306
                    try:
×
307
                        paymntack = pb2.PaymentACK()
×
308
                        paymntack.ParseFromString(resp_content)
×
309
                    except Exception:
×
310
                        return False, "PaymentACK could not be processed. Payment was sent; please manually verify that payment was received."
×
311
                    print(f"PaymentACK message received: {paymntack.memo}")
×
312
                    return True, paymntack.memo
×
313
        except aiohttp.ClientError as e:
×
314
            error = f"Payment Message/PaymentACK Failed:\nerror type: {type(e)}"
×
315
            if isinstance(e, aiohttp.ClientResponseError):
×
316
                error += f"\nGot HTTP status code {e.status}."
×
317
                if resp_content:
×
318
                    error_text_received = error_text_bytes_to_safe_str(resp_content)
×
319
                    error_text_received = error_text_received[:400]
×
320
                    error_oneline = ' -- '.join(error.split('\n'))
×
321
                    _logger.info(f"{error_oneline} -- [DO NOT TRUST THIS MESSAGE] "
×
322
                                 f"{repr(e)} text: {error_text_received}")
323
            return False, error
×
324

325

326
def make_unsigned_request(req: 'Invoice'):
4✔
327
    addr = req.get_address()
×
328
    time = req.time
×
329
    exp = req.exp
×
330
    if time and type(time) != int:
×
331
        time = 0
×
332
    if exp and type(exp) != int:
×
333
        exp = 0
×
334
    amount = req.get_amount_sat()
×
335
    if amount is None:
×
336
        amount = 0
×
337
    memo = req.message
×
338
    script = address_to_script(addr)
×
339
    outputs = [(script, amount)]
×
340
    pd = pb2.PaymentDetails()
×
341
    if constants.net.TESTNET:
×
342
        pd.network = 'test'
×
343
    for script, amount in outputs:
×
344
        pd.outputs.add(amount=amount, script=script)
×
345
    pd.time = time
×
346
    pd.expires = time + exp if exp else 0
×
347
    pd.memo = memo
×
348
    pr = pb2.PaymentRequest()
×
349
    pr.serialized_payment_details = pd.SerializeToString()
×
350
    pr.signature = util.to_bytes('')
×
351
    return pr
×
352

353

354
def sign_request_with_alias(pr, alias, alias_privkey):
4✔
355
    pr.pki_type = 'dnssec+btc'
×
356
    pr.pki_data = str(alias)
×
357
    message = pr.SerializeToString()
×
358
    ec_key = ecc.ECPrivkey(alias_privkey)
×
359
    compressed = bitcoin.is_compressed_privkey(alias_privkey)
×
360
    pr.signature = bitcoin.ecdsa_sign_usermessage(ec_key, message, is_compressed=compressed)
×
361

362

363
def verify_cert_chain(chain):
4✔
364
    """ Verify a chain of certificates. The last certificate is the CA"""
365
    load_ca_list()
×
366
    # parse the chain
367
    cert_num = len(chain)
×
368
    x509_chain = []
×
369
    for i in range(cert_num):
×
370
        x = x509.X509(bytearray(chain[i]))
×
371
        x509_chain.append(x)
×
372
        if i == 0:
×
373
            x.check_date()
×
374
        else:
375
            if not x.check_ca():
×
376
                raise Exception("ERROR: Supplied CA Certificate Error")
×
377
    if not cert_num > 1:
×
378
        raise Exception("ERROR: CA Certificate Chain Not Provided by Payment Processor")
×
379
    # if the root CA is not supplied, add it to the chain
380
    ca = x509_chain[cert_num-1]
×
381
    if ca.getFingerprint() not in ca_list:
×
382
        keyID = ca.get_issuer_keyID()
×
383
        f = ca_keyID.get(keyID)
×
384
        if f:
×
385
            root = ca_list[f]
×
386
            x509_chain.append(root)
×
387
        else:
388
            raise Exception("Supplied CA Not Found in Trusted CA Store.")
×
389
    # verify the chain of signatures
390
    cert_num = len(x509_chain)
×
391
    for i in range(1, cert_num):
×
392
        x = x509_chain[i]
×
393
        prev_x = x509_chain[i-1]
×
394
        algo, sig, data = prev_x.get_signature()
×
395
        sig = bytearray(sig)
×
396
        pubkey = rsakey.RSAKey(x.modulus, x.exponent)
×
397
        if algo == x509.ALGO_RSA_SHA1:
×
398
            verify = pubkey.hashAndVerify(sig, data)
×
399
        elif algo == x509.ALGO_RSA_SHA256:
×
400
            hashBytes = bytearray(hashlib.sha256(data).digest())
×
401
            verify = pubkey.verify(sig, x509.PREFIX_RSA_SHA256 + hashBytes)
×
402
        elif algo == x509.ALGO_RSA_SHA384:
×
403
            hashBytes = bytearray(hashlib.sha384(data).digest())
×
404
            verify = pubkey.verify(sig, x509.PREFIX_RSA_SHA384 + hashBytes)
×
405
        elif algo == x509.ALGO_RSA_SHA512:
×
406
            hashBytes = bytearray(hashlib.sha512(data).digest())
×
407
            verify = pubkey.verify(sig, x509.PREFIX_RSA_SHA512 + hashBytes)
×
408
        else:
409
            raise Exception("Algorithm not supported: {}".format(algo))
×
410
        if not verify:
×
411
            raise Exception("Certificate not Signed by Provided CA Certificate Chain")
×
412

413
    return x509_chain[0], ca
×
414

415

416
def check_ssl_config(config: 'SimpleConfig'):
4✔
417
    from . import pem
×
418
    key_path = config.SSL_KEYFILE_PATH
×
419
    cert_path = config.SSL_CERTFILE_PATH
×
420
    with open(key_path, 'r', encoding='utf-8') as f:
×
421
        params = pem.parse_private_key(f.read())
×
422
    with open(cert_path, 'r', encoding='utf-8') as f:
×
423
        s = f.read()
×
424
    bList = pem.dePemList(s, "CERTIFICATE")
×
425
    # verify chain
426
    x, ca = verify_cert_chain(bList)
×
427
    # verify that privkey and pubkey match
428
    privkey = rsakey.RSAKey(*params)
×
429
    pubkey = rsakey.RSAKey(x.modulus, x.exponent)
×
430
    assert x.modulus == params[0]
×
431
    assert x.exponent == params[1]
×
432
    # return requestor
433
    requestor = x.get_common_name()
×
434
    if requestor.startswith('*.'):
×
435
        requestor = requestor[2:]
×
436
    return requestor
×
437

438

439
def sign_request_with_x509(pr, key_path, cert_path):
4✔
440
    from . import pem
×
441
    with open(key_path, 'r', encoding='utf-8') as f:
×
442
        params = pem.parse_private_key(f.read())
×
443
        privkey = rsakey.RSAKey(*params)
×
444
    with open(cert_path, 'r', encoding='utf-8') as f:
×
445
        s = f.read()
×
446
        bList = pem.dePemList(s, "CERTIFICATE")
×
447
    certificates = pb2.X509Certificates()
×
448
    certificates.certificate.extend(map(bytes, bList))
×
449
    pr.pki_type = 'x509+sha256'
×
450
    pr.pki_data = certificates.SerializeToString()
×
451
    msgBytes = bytearray(pr.SerializeToString())
×
452
    hashBytes = bytearray(hashlib.sha256(msgBytes).digest())
×
453
    sig = privkey.sign(x509.PREFIX_RSA_SHA256 + hashBytes)
×
454
    pr.signature = bytes(sig)
×
455

456

457
def serialize_request(req):  # FIXME this is broken
4✔
458
    pr = make_unsigned_request(req)
×
459
    signature = req.get('sig')
×
460
    requestor = req.get('name')
×
461
    if requestor and signature:
×
462
        pr.signature = bfh(signature)
×
463
        pr.pki_type = 'dnssec+btc'
×
464
        pr.pki_data = str(requestor)
×
465
    return pr
×
466

467

468
def make_request(config: 'SimpleConfig', req: 'Invoice'):
4✔
469
    pr = make_unsigned_request(req)
×
470
    key_path = config.SSL_KEYFILE_PATH
×
471
    cert_path = config.SSL_CERTFILE_PATH
×
472
    if key_path and cert_path:
×
473
        sign_request_with_x509(pr, key_path, cert_path)
×
474
    return pr
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc