-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutil.py
2119 lines (1738 loc) · 71.1 KB
/
util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Electrum - lightweight Bitcoin client
# Copyright (C) 2011 Thomas Voegtlin
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import binascii
import os, sys, re, json
from collections import defaultdict, OrderedDict
from typing import (NamedTuple, Union, TYPE_CHECKING, Tuple, Optional, Callable, Any,
Sequence, Dict, Generic, TypeVar, List, Iterable, Set)
from datetime import datetime
import decimal
from decimal import Decimal
import traceback
import urllib
import threading
import hmac
import stat
import locale
import asyncio
import urllib.request, urllib.parse, urllib.error
import builtins
import json
import time
from typing import NamedTuple, Optional
import ssl
import ipaddress
from ipaddress import IPv4Address, IPv6Address
import random
import secrets
import functools
from abc import abstractmethod, ABC
import socket
import attr
import aiohttp
from aiohttp_socks import ProxyConnector, ProxyType
import aiorpcx
import certifi
import dns.resolver
from .i18n import _
from .logging import get_logger, Logger
if TYPE_CHECKING:
from .network import Network
from .interface import Interface
from .simple_config import SimpleConfig
from .paymentrequest import PaymentRequest
_logger = get_logger(__name__)
def inv_dict(d):
return {v: k for k, v in d.items()}
def all_subclasses(cls) -> Set:
"""Return all (transitive) subclasses of cls."""
res = set(cls.__subclasses__())
for sub in res.copy():
res |= all_subclasses(sub)
return res
ca_path = certifi.where()
base_units = {'BTC':8, 'mBTC':5, 'bits':2, 'sat':0}
base_units_inverse = inv_dict(base_units)
base_units_list = ['BTC', 'mBTC', 'bits', 'sat'] # list(dict) does not guarantee order
DECIMAL_POINT_DEFAULT = 5 # mBTC
class UnknownBaseUnit(Exception): pass
def decimal_point_to_base_unit_name(dp: int) -> str:
# e.g. 8 -> "BTC"
try:
return base_units_inverse[dp]
except KeyError:
raise UnknownBaseUnit(dp) from None
def base_unit_name_to_decimal_point(unit_name: str) -> int:
# e.g. "BTC" -> 8
try:
return base_units[unit_name]
except KeyError:
raise UnknownBaseUnit(unit_name) from None
def parse_max_spend(amt: Any) -> Optional[int]:
"""Checks if given amount is "spend-max"-like.
Returns None or the positive integer weight for "max". Never raises.
When creating invoices and on-chain txs, the user can specify to send "max".
This is done by setting the amount to '!'. Splitting max between multiple
tx outputs is also possible, and custom weights (positive ints) can also be used.
For example, to send 40% of all coins to address1, and 60% to address2:
```
address1, 2!
address2, 3!
```
"""
if not (isinstance(amt, str) and amt and amt[-1] == '!'):
return None
if amt == '!':
return 1
x = amt[:-1]
try:
x = int(x)
except ValueError:
return None
if x > 0:
return x
return None
class NotEnoughFunds(Exception):
def __str__(self):
return _("Insufficient funds")
class NoDynamicFeeEstimates(Exception):
def __str__(self):
return _('Dynamic fee estimates not available')
class BelowDustLimit(Exception):
pass
class InvalidPassword(Exception):
def __init__(self, message: Optional[str] = None):
self.message = message
def __str__(self):
if self.message is None:
return _("Incorrect password")
else:
return str(self.message)
class AddTransactionException(Exception):
pass
class UnrelatedTransactionException(AddTransactionException):
def __str__(self):
return _("Transaction is unrelated to this wallet.")
class FileImportFailed(Exception):
def __init__(self, message=''):
self.message = str(message)
def __str__(self):
return _("Failed to import from file.") + "\n" + self.message
class FileExportFailed(Exception):
def __init__(self, message=''):
self.message = str(message)
def __str__(self):
return _("Failed to export to file.") + "\n" + self.message
class WalletFileException(Exception): pass
class BitcoinException(Exception): pass
class UserFacingException(Exception):
"""Exception that contains information intended to be shown to the user."""
class InvoiceError(UserFacingException): pass
# Throw this exception to unwind the stack like when an error occurs.
# However unlike other exceptions the user won't be informed.
class UserCancelled(Exception):
'''An exception that is suppressed from the user'''
pass
def to_decimal(x: Union[str, float, int, Decimal]) -> Decimal:
# helper function mainly for float->Decimal conversion, i.e.:
# >>> Decimal(41754.681)
# Decimal('41754.680999999996856786310672760009765625')
# >>> Decimal("41754.681")
# Decimal('41754.681')
if isinstance(x, Decimal):
return x
return Decimal(str(x))
# note: this is not a NamedTuple as then its json encoding cannot be customized
class Satoshis(object):
__slots__ = ('value',)
def __new__(cls, value):
self = super(Satoshis, cls).__new__(cls)
# note: 'value' sometimes has msat precision
self.value = value
return self
def __repr__(self):
return f'Satoshis({self.value})'
def __str__(self):
# note: precision is truncated to satoshis here
return format_satoshis(self.value)
def __eq__(self, other):
return self.value == other.value
def __ne__(self, other):
return not (self == other)
def __add__(self, other):
return Satoshis(self.value + other.value)
# note: this is not a NamedTuple as then its json encoding cannot be customized
class Fiat(object):
__slots__ = ('value', 'ccy')
def __new__(cls, value: Optional[Decimal], ccy: str):
self = super(Fiat, cls).__new__(cls)
self.ccy = ccy
if not isinstance(value, (Decimal, type(None))):
raise TypeError(f"value should be Decimal or None, not {type(value)}")
self.value = value
return self
def __repr__(self):
return 'Fiat(%s)'% self.__str__()
def __str__(self):
if self.value is None or self.value.is_nan():
return _('No Data')
else:
return "{:.2f}".format(self.value)
def to_ui_string(self):
if self.value is None or self.value.is_nan():
return _('No Data')
else:
return "{:.2f}".format(self.value) + ' ' + self.ccy
def __eq__(self, other):
if not isinstance(other, Fiat):
return False
if self.ccy != other.ccy:
return False
if isinstance(self.value, Decimal) and isinstance(other.value, Decimal) \
and self.value.is_nan() and other.value.is_nan():
return True
return self.value == other.value
def __ne__(self, other):
return not (self == other)
def __add__(self, other):
assert self.ccy == other.ccy
return Fiat(self.value + other.value, self.ccy)
class MyEncoder(json.JSONEncoder):
def default(self, obj):
# note: this does not get called for namedtuples :( https://bugs.python.org/issue30343
from .transaction import Transaction, TxOutput
from .lnutil import UpdateAddHtlc
if isinstance(obj, UpdateAddHtlc):
return obj.to_tuple()
if isinstance(obj, Transaction):
return obj.serialize()
if isinstance(obj, TxOutput):
return obj.to_legacy_tuple()
if isinstance(obj, Satoshis):
return str(obj)
if isinstance(obj, Fiat):
return str(obj)
if isinstance(obj, Decimal):
return str(obj)
if isinstance(obj, datetime):
return obj.isoformat(' ')[:-3]
if isinstance(obj, set):
return list(obj)
if isinstance(obj, bytes): # for nametuples in lnchannel
return obj.hex()
if hasattr(obj, 'to_json') and callable(obj.to_json):
return obj.to_json()
return super(MyEncoder, self).default(obj)
class ThreadJob(Logger):
"""A job that is run periodically from a thread's main loop. run() is
called from that thread's context.
"""
def __init__(self):
Logger.__init__(self)
def run(self):
"""Called periodically from the thread"""
pass
class DebugMem(ThreadJob):
'''A handy class for debugging GC memory leaks'''
def __init__(self, classes, interval=30):
ThreadJob.__init__(self)
self.next_time = 0
self.classes = classes
self.interval = interval
def mem_stats(self):
import gc
self.logger.info("Start memscan")
gc.collect()
objmap = defaultdict(list)
for obj in gc.get_objects():
for class_ in self.classes:
if isinstance(obj, class_):
objmap[class_].append(obj)
for class_, objs in objmap.items():
self.logger.info(f"{class_.__name__}: {len(objs)}")
self.logger.info("Finish memscan")
def run(self):
if time.time() > self.next_time:
self.mem_stats()
self.next_time = time.time() + self.interval
class DaemonThread(threading.Thread, Logger):
""" daemon thread that terminates cleanly """
LOGGING_SHORTCUT = 'd'
def __init__(self):
threading.Thread.__init__(self)
Logger.__init__(self)
self.parent_thread = threading.current_thread()
self.running = False
self.running_lock = threading.Lock()
self.job_lock = threading.Lock()
self.jobs = []
self.stopped_event = threading.Event() # set when fully stopped
def add_jobs(self, jobs):
with self.job_lock:
self.jobs.extend(jobs)
def run_jobs(self):
# Don't let a throwing job disrupt the thread, future runs of
# itself, or other jobs. This is useful protection against
# malformed or malicious server responses
with self.job_lock:
for job in self.jobs:
try:
job.run()
except Exception as e:
self.logger.exception('')
def remove_jobs(self, jobs):
with self.job_lock:
for job in jobs:
self.jobs.remove(job)
def start(self):
with self.running_lock:
self.running = True
return threading.Thread.start(self)
def is_running(self):
with self.running_lock:
return self.running and self.parent_thread.is_alive()
def stop(self):
with self.running_lock:
self.running = False
def on_stop(self):
if 'ANDROID_DATA' in os.environ:
import jnius
jnius.detach()
self.logger.info("jnius detach")
self.logger.info("stopped")
self.stopped_event.set()
def print_stderr(*args):
args = [str(item) for item in args]
sys.stderr.write(" ".join(args) + "\n")
sys.stderr.flush()
def print_msg(*args):
# Stringify args
args = [str(item) for item in args]
sys.stdout.write(" ".join(args) + "\n")
sys.stdout.flush()
def json_encode(obj):
try:
s = json.dumps(obj, sort_keys = True, indent = 4, cls=MyEncoder)
except TypeError:
s = repr(obj)
return s
def json_decode(x):
try:
return json.loads(x, parse_float=Decimal)
except:
return x
def json_normalize(x):
# note: The return value of commands, when going through the JSON-RPC interface,
# is json-encoded. The encoder used there cannot handle some types, e.g. electrum.util.Satoshis.
# note: We should not simply do "json_encode(x)" here, as then later x would get doubly json-encoded.
# see #5868
return json_decode(json_encode(x))
# taken from Django Source Code
def constant_time_compare(val1, val2):
"""Return True if the two strings are equal, False otherwise."""
return hmac.compare_digest(to_bytes(val1, 'utf8'), to_bytes(val2, 'utf8'))
# decorator that prints execution time
_profiler_logger = _logger.getChild('profiler')
def profiler(func):
def do_profile(args, kw_args):
name = func.__qualname__
t0 = time.time()
o = func(*args, **kw_args)
t = time.time() - t0
_profiler_logger.debug(f"{name} {t:,.4f} sec")
return o
return lambda *args, **kw_args: do_profile(args, kw_args)
def android_ext_dir():
from android.storage import primary_external_storage_path
return primary_external_storage_path()
def android_backup_dir():
pkgname = get_android_package_name()
d = os.path.join(android_ext_dir(), pkgname)
if not os.path.exists(d):
os.mkdir(d)
return d
def android_data_dir():
import jnius
PythonActivity = jnius.autoclass('org.kivy.android.PythonActivity')
return PythonActivity.mActivity.getFilesDir().getPath() + '/data'
def ensure_sparse_file(filename):
# On modern Linux, no need to do anything.
# On Windows, need to explicitly mark file.
if os.name == "nt":
try:
os.system('fsutil sparse setflag "{}" 1'.format(filename))
except Exception as e:
_logger.info(f'error marking file {filename} as sparse: {e}')
def get_headers_dir(config):
return config.path
def assert_datadir_available(config_path):
path = config_path
if os.path.exists(path):
return
else:
raise FileNotFoundError(
'Electrum datadir does not exist. Was it deleted while running?' + '\n' +
'Should be at {}'.format(path))
def assert_file_in_datadir_available(path, config_path):
if os.path.exists(path):
return
else:
assert_datadir_available(config_path)
raise FileNotFoundError(
'Cannot find file but datadir is there.' + '\n' +
'Should be at {}'.format(path))
def standardize_path(path):
return os.path.normcase(
os.path.realpath(
os.path.abspath(
os.path.expanduser(
path
))))
def get_new_wallet_name(wallet_folder: str) -> str:
"""Returns a file basename for a new wallet to be used.
Can raise OSError.
"""
i = 1
while True:
filename = "wallet_%d" % i
if filename in os.listdir(wallet_folder):
i += 1
else:
break
return filename
def is_android_debug_apk() -> bool:
is_android = 'ANDROID_DATA' in os.environ
if not is_android:
return False
from jnius import autoclass
pkgname = get_android_package_name()
build_config = autoclass(f"{pkgname}.BuildConfig")
return bool(build_config.DEBUG)
def get_android_package_name() -> str:
is_android = 'ANDROID_DATA' in os.environ
assert is_android
from jnius import autoclass
from android.config import ACTIVITY_CLASS_NAME
activity = autoclass(ACTIVITY_CLASS_NAME).mActivity
pkgname = str(activity.getPackageName())
return pkgname
def assert_bytes(*args):
"""
porting helper, assert args type
"""
try:
for x in args:
assert isinstance(x, (bytes, bytearray))
except:
print('assert bytes failed', list(map(type, args)))
raise
def assert_str(*args):
"""
porting helper, assert args type
"""
for x in args:
assert isinstance(x, str)
def to_string(x, enc) -> str:
if isinstance(x, (bytes, bytearray)):
return x.decode(enc)
if isinstance(x, str):
return x
else:
raise TypeError("Not a string or bytes like object")
def to_bytes(something, encoding='utf8') -> bytes:
"""
cast string to bytes() like object, but for python2 support it's bytearray copy
"""
if isinstance(something, bytes):
return something
if isinstance(something, str):
return something.encode(encoding)
elif isinstance(something, bytearray):
return bytes(something)
else:
raise TypeError("Not a string or bytes like object")
bfh = bytes.fromhex
def xor_bytes(a: bytes, b: bytes) -> bytes:
size = min(len(a), len(b))
return ((int.from_bytes(a[:size], "big") ^ int.from_bytes(b[:size], "big"))
.to_bytes(size, "big"))
def user_dir():
if "ELECTRUMDIR" in os.environ:
return os.environ["ELECTRUMDIR"]
elif 'ANDROID_DATA' in os.environ:
return android_data_dir()
elif os.name == 'posix':
return os.path.join(os.environ["HOME"], ".electrum")
elif "APPDATA" in os.environ:
return os.path.join(os.environ["APPDATA"], "Electrum")
elif "LOCALAPPDATA" in os.environ:
return os.path.join(os.environ["LOCALAPPDATA"], "Electrum")
else:
#raise Exception("No home directory found in environment variables.")
return
def resource_path(*parts):
return os.path.join(pkg_dir, *parts)
# absolute path to python package folder of electrum ("lib")
pkg_dir = os.path.split(os.path.realpath(__file__))[0]
def is_valid_email(s):
regexp = r"[^@]+@[^@]+\.[^@]+"
return re.match(regexp, s) is not None
def is_hash256_str(text: Any) -> bool:
if not isinstance(text, str): return False
if len(text) != 64: return False
return is_hex_str(text)
def is_hex_str(text: Any) -> bool:
if not isinstance(text, str): return False
try:
b = bytes.fromhex(text)
except:
return False
# forbid whitespaces in text:
if len(text) != 2 * len(b):
return False
return True
def is_integer(val: Any) -> bool:
return isinstance(val, int)
def is_non_negative_integer(val: Any) -> bool:
if is_integer(val):
return val >= 0
return False
def is_int_or_float(val: Any) -> bool:
return isinstance(val, (int, float))
def is_non_negative_int_or_float(val: Any) -> bool:
if is_int_or_float(val):
return val >= 0
return False
def chunks(items, size: int):
"""Break up items, an iterable, into chunks of length size."""
if size < 1:
raise ValueError(f"size must be positive, not {repr(size)}")
for i in range(0, len(items), size):
yield items[i: i + size]
def format_satoshis_plain(
x: Union[int, float, Decimal, str], # amount in satoshis,
*,
decimal_point: int = 8, # how much to shift decimal point to left (default: sat->BTC)
) -> str:
"""Display a satoshi amount scaled. Always uses a '.' as a decimal
point and has no thousands separator"""
if parse_max_spend(x):
return f'max({x})'
assert isinstance(x, (int, float, Decimal)), f"{x!r} should be a number"
scale_factor = pow(10, decimal_point)
return "{:.8f}".format(Decimal(x) / scale_factor).rstrip('0').rstrip('.')
# Check that Decimal precision is sufficient.
# We need at the very least ~20, as we deal with msat amounts, and
# log10(21_000_000 * 10**8 * 1000) ~= 18.3
# decimal.DefaultContext.prec == 28 by default, but it is mutable.
# We enforce that we have at least that available.
assert decimal.getcontext().prec >= 28, f"PyDecimal precision too low: {decimal.getcontext().prec}"
# DECIMAL_POINT = locale.localeconv()['decimal_point'] # type: str
DECIMAL_POINT = "."
THOUSANDS_SEP = " "
assert len(DECIMAL_POINT) == 1, f"DECIMAL_POINT has unexpected len. {DECIMAL_POINT!r}"
assert len(THOUSANDS_SEP) == 1, f"THOUSANDS_SEP has unexpected len. {THOUSANDS_SEP!r}"
def format_satoshis(
x: Union[int, float, Decimal, str, None], # amount in satoshis
*,
num_zeros: int = 0,
decimal_point: int = 8, # how much to shift decimal point to left (default: sat->BTC)
precision: int = 0, # extra digits after satoshi precision
is_diff: bool = False, # if True, enforce a leading sign (+/-)
whitespaces: bool = False, # if True, add whitespaces, to align numbers in a column
add_thousands_sep: bool = False, # if True, add whitespaces, for better readability of the numbers
) -> str:
if x is None:
return 'unknown'
if parse_max_spend(x):
return f'max({x})'
assert isinstance(x, (int, float, Decimal)), f"{x!r} should be a number"
# lose redundant precision
x = Decimal(x).quantize(Decimal(10) ** (-precision))
# format string
overall_precision = decimal_point + precision # max digits after final decimal point
decimal_format = "." + str(overall_precision) if overall_precision > 0 else ""
if is_diff:
decimal_format = '+' + decimal_format
# initial result
scale_factor = pow(10, decimal_point)
result = ("{:" + decimal_format + "f}").format(x / scale_factor)
if "." not in result: result += "."
result = result.rstrip('0')
# add extra decimal places (zeros)
integer_part, fract_part = result.split(".")
if len(fract_part) < num_zeros:
fract_part += "0" * (num_zeros - len(fract_part))
# add whitespaces as thousands' separator for better readability of numbers
if add_thousands_sep:
sign = integer_part[0] if integer_part[0] in ("+", "-") else ""
if sign == "-":
integer_part = integer_part[1:]
integer_part = "{:,}".format(int(integer_part)).replace(',', THOUSANDS_SEP)
integer_part = sign + integer_part
fract_part = THOUSANDS_SEP.join(fract_part[i:i+3] for i in range(0, len(fract_part), 3))
result = integer_part + DECIMAL_POINT + fract_part
# add leading/trailing whitespaces so that numbers can be aligned in a column
if whitespaces:
target_fract_len = overall_precision
target_integer_len = 14 - decimal_point # should be enough for up to unsigned 999999 BTC
if add_thousands_sep:
target_fract_len += max(0, (target_fract_len - 1) // 3)
target_integer_len += max(0, (target_integer_len - 1) // 3)
# add trailing whitespaces
result += " " * (target_fract_len - len(fract_part))
# add leading whitespaces
target_total_len = target_integer_len + 1 + target_fract_len
result = " " * (target_total_len - len(result)) + result
return result
FEERATE_PRECISION = 1 # num fractional decimal places for sat/byte fee rates
_feerate_quanta = Decimal(10) ** (-FEERATE_PRECISION)
def format_fee_satoshis(fee, *, num_zeros=0, precision=None):
if precision is None:
precision = FEERATE_PRECISION
num_zeros = min(num_zeros, FEERATE_PRECISION) # no more zeroes than available prec
return format_satoshis(fee, num_zeros=num_zeros, decimal_point=0, precision=precision)
def quantize_feerate(fee) -> Union[None, Decimal, int]:
"""Strip sat/byte fee rate of excess precision."""
if fee is None:
return None
return Decimal(fee).quantize(_feerate_quanta, rounding=decimal.ROUND_HALF_DOWN)
def timestamp_to_datetime(timestamp: Union[int, float, None]) -> Optional[datetime]:
if timestamp is None:
return None
return datetime.fromtimestamp(timestamp)
def format_time(timestamp: Union[int, float, None]) -> str:
date = timestamp_to_datetime(timestamp)
return date.isoformat(' ', timespec="minutes") if date else _("Unknown")
def age(
from_date: Union[int, float, None], # POSIX timestamp
*,
since_date: datetime = None,
target_tz=None,
include_seconds: bool = False,
) -> str:
"""Takes a timestamp and returns a string with the approximation of the age"""
if from_date is None:
return _("Unknown")
from_date = datetime.fromtimestamp(from_date)
if since_date is None:
since_date = datetime.now(target_tz)
distance_in_time = from_date - since_date
is_in_past = from_date < since_date
distance_in_seconds = int(round(abs(distance_in_time.days * 86400 + distance_in_time.seconds)))
distance_in_minutes = int(round(distance_in_seconds / 60))
if distance_in_minutes == 0:
if include_seconds:
if is_in_past:
return _("{} seconds ago").format(distance_in_seconds)
else:
return _("in {} seconds").format(distance_in_seconds)
else:
if is_in_past:
return _("less than a minute ago")
else:
return _("in less than a minute")
elif distance_in_minutes < 45:
if is_in_past:
return _("about {} minutes ago").format(distance_in_minutes)
else:
return _("in about {} minutes").format(distance_in_minutes)
elif distance_in_minutes < 90:
if is_in_past:
return _("about 1 hour ago")
else:
return _("in about 1 hour")
elif distance_in_minutes < 1440:
if is_in_past:
return _("about {} hours ago").format(round(distance_in_minutes / 60.0))
else:
return _("in about {} hours").format(round(distance_in_minutes / 60.0))
elif distance_in_minutes < 2880:
if is_in_past:
return _("about 1 day ago")
else:
return _("in about 1 day")
elif distance_in_minutes < 43220:
if is_in_past:
return _("about {} days ago").format(round(distance_in_minutes / 1440))
else:
return _("in about {} days").format(round(distance_in_minutes / 1440))
elif distance_in_minutes < 86400:
if is_in_past:
return _("about 1 month ago")
else:
return _("in about 1 month")
elif distance_in_minutes < 525600:
if is_in_past:
return _("about {} months ago").format(round(distance_in_minutes / 43200))
else:
return _("in about {} months").format(round(distance_in_minutes / 43200))
elif distance_in_minutes < 1051200:
if is_in_past:
return _("about 1 year ago")
else:
return _("in about 1 year")
else:
if is_in_past:
return _("over {} years ago").format(round(distance_in_minutes / 525600))
else:
return _("in over {} years").format(round(distance_in_minutes / 525600))
mainnet_block_explorers = {
'Bitupper Explorer': ('https://bitupper.com/en/explorer/bitcoin/',
{'tx': 'transactions/', 'addr': 'addresses/'}),
'Bitflyer.jp': ('https://chainflyer.bitflyer.jp/',
{'tx': 'Transaction/', 'addr': 'Address/'}),
'Blockchain.info': ('https://blockchain.com/btc/',
{'tx': 'tx/', 'addr': 'address/'}),
'blockchainbdgpzk.onion': ('https://blockchainbdgpzk.onion/',
{'tx': 'tx/', 'addr': 'address/'}),
'Blockstream.info': ('https://blockstream.info/',
{'tx': 'tx/', 'addr': 'address/'}),
'Bitaps.com': ('https://btc.bitaps.com/',
{'tx': '', 'addr': ''}),
'BTC.com': ('https://btc.com/',
{'tx': '', 'addr': ''}),
'Chain.so': ('https://www.chain.so/',
{'tx': 'tx/BTC/', 'addr': 'address/BTC/'}),
'Insight.is': ('https://insight.bitpay.com/',
{'tx': 'tx/', 'addr': 'address/'}),
'TradeBlock.com': ('https://tradeblock.com/blockchain/',
{'tx': 'tx/', 'addr': 'address/'}),
'BlockCypher.com': ('https://live.blockcypher.com/btc/',
{'tx': 'tx/', 'addr': 'address/'}),
'Blockchair.com': ('https://blockchair.com/bitcoin/',
{'tx': 'transaction/', 'addr': 'address/'}),
'blockonomics.co': ('https://www.blockonomics.co/',
{'tx': 'api/tx?txid=', 'addr': '#/search?q='}),
'mempool.space': ('https://mempool.space/',
{'tx': 'tx/', 'addr': 'address/'}),
'mempool.emzy.de': ('https://mempool.emzy.de/',
{'tx': 'tx/', 'addr': 'address/'}),
'OXT.me': ('https://oxt.me/',
{'tx': 'transaction/', 'addr': 'address/'}),
'smartbit.com.au': ('https://www.smartbit.com.au/',
{'tx': 'tx/', 'addr': 'address/'}),
'mynode.local': ('http://mynode.local:3002/',
{'tx': 'tx/', 'addr': 'address/'}),
'system default': ('blockchain:/',
{'tx': 'tx/', 'addr': 'address/'}),
}
testnet_block_explorers = {
'Bitaps.com': ('https://tbtc.bitaps.com/',
{'tx': '', 'addr': ''}),
'BlockCypher.com': ('https://live.blockcypher.com/btc-testnet/',
{'tx': 'tx/', 'addr': 'address/'}),
'Blockchain.info': ('https://www.blockchain.com/btc-testnet/',
{'tx': 'tx/', 'addr': 'address/'}),
'Blockstream.info': ('https://blockstream.info/testnet/',
{'tx': 'tx/', 'addr': 'address/'}),
'mempool.space': ('https://mempool.space/testnet/',
{'tx': 'tx/', 'addr': 'address/'}),
'smartbit.com.au': ('https://testnet.smartbit.com.au/',
{'tx': 'tx/', 'addr': 'address/'}),
'system default': ('blockchain://000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943/',
{'tx': 'tx/', 'addr': 'address/'}),
}
signet_block_explorers = {
'bc-2.jp': ('https://explorer.bc-2.jp/',
{'tx': 'tx/', 'addr': 'address/'}),
'mempool.space': ('https://mempool.space/signet/',
{'tx': 'tx/', 'addr': 'address/'}),
'bitcoinexplorer.org': ('https://signet.bitcoinexplorer.org/',
{'tx': 'tx/', 'addr': 'address/'}),
'wakiyamap.dev': ('https://signet-explorer.wakiyamap.dev/',
{'tx': 'tx/', 'addr': 'address/'}),
'ex.signet.bublina.eu.org': ('https://ex.signet.bublina.eu.org/',
{'tx': 'tx/', 'addr': 'address/'}),
'system default': ('blockchain:/',
{'tx': 'tx/', 'addr': 'address/'}),
}
_block_explorer_default_api_loc = {'tx': 'tx/', 'addr': 'address/'}
def block_explorer_info():
from . import constants
if constants.net.NET_NAME == "testnet":
return testnet_block_explorers
elif constants.net.NET_NAME == "signet":
return signet_block_explorers
return mainnet_block_explorers
def block_explorer(config: 'SimpleConfig') -> Optional[str]:
"""Returns name of selected block explorer,
or None if a custom one (not among hardcoded ones) is configured.
"""
if config.get('block_explorer_custom') is not None:
return None
default_ = 'Blockstream.info'
be_key = config.get('block_explorer', default_)
be_tuple = block_explorer_info().get(be_key)
if be_tuple is None:
be_key = default_
assert isinstance(be_key, str), f"{be_key!r} should be str"
return be_key
def block_explorer_tuple(config: 'SimpleConfig') -> Optional[Tuple[str, dict]]:
custom_be = config.get('block_explorer_custom')
if custom_be:
if isinstance(custom_be, str):
return custom_be, _block_explorer_default_api_loc
if isinstance(custom_be, (tuple, list)) and len(custom_be) == 2:
return tuple(custom_be)
_logger.warning(f"not using 'block_explorer_custom' from config. "
f"expected a str or a pair but got {custom_be!r}")
return None
else:
# using one of the hardcoded block explorers
return block_explorer_info().get(block_explorer(config))
def block_explorer_URL(config: 'SimpleConfig', kind: str, item: str) -> Optional[str]:
be_tuple = block_explorer_tuple(config)
if not be_tuple:
return
explorer_url, explorer_dict = be_tuple
kind_str = explorer_dict.get(kind)
if kind_str is None:
return
if explorer_url[-1] != "/":
explorer_url += "/"
url_parts = [explorer_url, kind_str, item]
return ''.join(url_parts)