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

spesmilo / electrum / 5766584628674560

20 Aug 2025 05:57PM UTC coverage: 61.507% (-0.03%) from 61.535%
5766584628674560

Pull #10159

CirrusCI

SomberNight
logging: add config.LOGS_MAX_TOTAL_SIZE_BYTES: to limit size on disk
Pull Request #10159: logging: add config.LOGS_MAX_TOTAL_SIZE_BYTES: to limit size on disk

7 of 31 new or added lines in 2 files covered. (22.58%)

125 existing lines in 47 files now uncovered.

22810 of 37085 relevant lines covered (61.51%)

3.07 hits per line

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

14.48
/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
                   get_asyncio_loop)
45
from .invoices import Invoice, get_id_from_onchain_outputs
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
5✔
50
from .contacts import Contacts
5✔
51

52
if TYPE_CHECKING:
2✔
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

67
def load_ca_list():
5✔
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':
5✔
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
    # do x509/dnssec verification now. we still expect the caller to at least check pr.error!
109
    await pr.verify()
×
110
    return pr
×
111

112

113
class PaymentRequest:
5✔
114

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

322

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

350

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

359

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

410
    return x509_chain[0], ca
×
411

412

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

435

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

453

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

464

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