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

spesmilo / electrum / 4656953357500416

02 Apr 2025 09:35AM UTC coverage: 61.073% (-0.002%) from 61.075%
4656953357500416

Pull #9671

CirrusCI

accumulator
lnworker: add parameter include_disconnected for get_channels_for_receiving(),
allowing less strict filtering when building route hints (i.e. likely usable soon-ish)
Pull Request #9671: lnworker: take peer_state into account in get_channels_for_receiving

3 of 4 new or added lines in 1 file covered. (75.0%)

435 existing lines in 6 files now uncovered.

21351 of 34960 relevant lines covered (61.07%)

3.05 hits per line

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

14.63
/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
5✔
26
import sys
5✔
27
import time
5✔
28
from typing import Optional, List, TYPE_CHECKING
5✔
29
import asyncio
5✔
30
import urllib.parse
5✔
31

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

36

37
try:
5✔
38
    from . import paymentrequest_pb2 as pb2
5✔
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
5✔
43
from .util import bfh, make_aiohttp_session, error_text_bytes_to_safe_str, get_running_loop
5✔
44
from .invoices import Invoice, get_id_from_onchain_outputs
5✔
45
from .crypto import sha256
5✔
46
from .bitcoin import address_to_script
5✔
47
from .transaction import PartialTxOutput
5✔
48
from .network import Network
5✔
49
from .logging import get_logger, Logger
5✔
50
from .contacts import Contacts
5✔
51

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

55

56
_logger = get_logger(__name__)
5✔
57

58

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

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

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

71

72

73

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

115

116
class PaymentRequest:
5✔
117

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

127
    def __str__(self):
5✔
UNCOV
128
        return str(self.raw)
×
129

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

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

186
    def verify_x509(self, paymntreq):
5✔
187
        load_ca_list()
×
188
        if not ca_list:
×
189
            self.error = "Trusted certificate authorities list not found"
×
190
            return False
×
UNCOV
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('')
×
UNCOV
198
            self.error = str(e)
×
199
            return False
×
200
        # get requestor name
201
        self.requestor = x.get_common_name()
×
UNCOV
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)
×
UNCOV
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:
×
UNCOV
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()
×
UNCOV
224
        self._verified_success = True
×
UNCOV
225
        return True
×
226

227
    def verify_dnssec(self, pr):
5✔
228
        sig = pr.signature
×
229
        alias = pr.pki_data
×
230
        info = 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'
×
UNCOV
241
                self._verified_success = True
×
242
                return True
×
243
            else:
UNCOV
244
                self.error = "verify failed"
×
245
                return False
×
246
        else:
UNCOV
247
            self.error = "unknown algo"
×
UNCOV
248
            return False
×
249

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

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

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

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

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

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

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

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

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

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

287
    async def send_payment_and_receive_paymentack(self, raw_tx, refund_addr):
5✔
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]
×
UNCOV
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}")
UNCOV
323
            return False, error
×
324

325

326
def make_unsigned_request(req: 'Invoice'):
5✔
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()
×
UNCOV
350
    pr.signature = util.to_bytes('')
×
UNCOV
351
    return pr
×
352

353

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

362

363
def verify_cert_chain(chain):
5✔
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)
×
UNCOV
372
        if i == 0:
×
373
            x.check_date()
×
374
        else:
375
            if not x.check_ca():
×
376
                raise Exception("ERROR: Supplied CA Certificate Error")
×
UNCOV
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:
×
UNCOV
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:
×
UNCOV
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))
×
UNCOV
410
        if not verify:
×
411
            raise Exception("Certificate not Signed by Provided CA Certificate Chain")
×
412

UNCOV
413
    return x509_chain[0], ca
×
414

415

416
def check_ssl_config(config: 'SimpleConfig'):
5✔
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:
×
UNCOV
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)
×
UNCOV
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('*.'):
×
UNCOV
435
        requestor = requestor[2:]
×
UNCOV
436
    return requestor
×
437

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

455

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

466

467
def make_request(config: 'SimpleConfig', req: 'Invoice'):
5✔
468
    pr = make_unsigned_request(req)
×
469
    key_path = config.SSL_KEYFILE_PATH
×
470
    cert_path = config.SSL_CERTFILE_PATH
×
471
    if key_path and cert_path:
×
472
        sign_request_with_x509(pr, key_path, cert_path)
×
UNCOV
473
    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