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

spesmilo / electrum / 5823920433004544

25 Mar 2025 03:50PM UTC coverage: 61.075% (-0.001%) from 61.076%
5823920433004544

push

CirrusCI

accumulator
small fixes, imports, whitespace

2 of 2 new or added lines in 1 file covered. (100.0%)

1 existing line in 1 file now uncovered.

21350 of 34957 relevant lines covered (61.08%)

3.05 hits per line

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

14.4
/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 .bitcoin import address_to_script
5✔
46
from .transaction import PartialTxOutput
5✔
47
from .network import Network
5✔
48
from .logging import get_logger
5✔
49
from .contacts import Contacts
5✔
50

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

54

55
_logger = get_logger(__name__)
5✔
56

57

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

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

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

113

114
class PaymentRequest:
5✔
115

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

125
    def __str__(self):
5✔
126
        return str(self.raw)
×
127

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

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

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

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

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

253
    def get_time(self):
5✔
254
        return self.details.time
×
255

256
    def get_expiration_date(self):
5✔
257
        return self.details.expires
×
258

259
    def get_amount(self):
5✔
260
        return sum(map(lambda x:x.value, self.outputs))
×
261

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

268
    def get_requestor(self):
5✔
269
        return self.requestor if self.requestor else self.get_address()
×
270

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

274
    def get_memo(self):
5✔
275
        return self.memo
×
276

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

282
    def get_outputs(self):
5✔
283
        return self.outputs[:]
×
284

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

323

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

351

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

360

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

411
    return x509_chain[0], ca
×
412

413

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

436

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

454

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

465

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