/
wallet.py
3987 lines (3550 loc) · 167 KB
/
wallet.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) 2015 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.
# Wallet classes:
# - Imported_Wallet: imported addresses or single keys, 0 or 1 keystore
# - Standard_Wallet: one HD keystore, P2PKH-like scripts
# - Multisig_Wallet: several HD keystores, M-of-N OP_CHECKMULTISIG scripts
import os
import sys
import random
import time
import json
import copy
import errno
import traceback
import operator
import math
from functools import partial
from collections import defaultdict
from numbers import Number
from decimal import Decimal
from typing import TYPE_CHECKING, List, Optional, Tuple, Union, NamedTuple, Sequence, Dict, Any, Set, Iterable
from abc import ABC, abstractmethod
import itertools
import threading
import enum
import asyncio
from aiorpcx import timeout_after, TaskTimeout, ignore_after, run_in_thread
from .i18n import _
from .bip32 import BIP32Node, convert_bip32_intpath_to_strpath, convert_bip32_strpath_to_intpath
from .crypto import sha256
from . import util
from .util import (NotEnoughFunds, UserCancelled, profiler, OldTaskGroup, ignore_exceptions,
format_satoshis, format_fee_satoshis, NoDynamicFeeEstimates,
WalletFileException, BitcoinException,
InvalidPassword, format_time, timestamp_to_datetime, Satoshis,
Fiat, bfh, TxMinedInfo, quantize_feerate, OrderedDictWithIndex)
from .simple_config import SimpleConfig, FEE_RATIO_HIGH_WARNING, FEERATE_WARNING_HIGH_FEE
from .bitcoin import COIN, TYPE_ADDRESS
from .bitcoin import is_address, address_to_script, is_minikey, relayfee, dust_threshold
from .bitcoin import DummyAddress, DummyAddressUsedInTxException
from .crypto import sha256d
from . import keystore
from .keystore import (load_keystore, Hardware_KeyStore, KeyStore, KeyStoreWithMPK,
AddressIndexGeneric, CannotDerivePubkey)
from .util import multisig_type, parse_max_spend
from .storage import StorageEncryptionVersion, WalletStorage
from .wallet_db import WalletDB
from . import transaction, bitcoin, coinchooser, paymentrequest, ecc, bip32
from .transaction import (Transaction, TxInput, UnknownTxinType, TxOutput,
PartialTransaction, PartialTxInput, PartialTxOutput, TxOutpoint, Sighash)
from .plugin import run_hook
from .address_synchronizer import (AddressSynchronizer, TX_HEIGHT_LOCAL,
TX_HEIGHT_UNCONF_PARENT, TX_HEIGHT_UNCONFIRMED, TX_HEIGHT_FUTURE, TX_TIMESTAMP_INF)
from .invoices import BaseInvoice, Invoice, Request
from .invoices import PR_PAID, PR_UNPAID, PR_UNKNOWN, PR_EXPIRED, PR_UNCONFIRMED, PR_INFLIGHT
from .contacts import Contacts
from .interface import NetworkException
from .mnemonic import Mnemonic
from .logging import get_logger, Logger
from .lnworker import LNWallet
from .paymentrequest import PaymentRequest
from .util import read_json_file, write_json_file, UserFacingException, FileImportFailed
from .util import EventListener, event_listener
from . import descriptor
from .descriptor import Descriptor
if TYPE_CHECKING:
from .network import Network
from .exchange_rate import FxThread
_logger = get_logger(__name__)
TX_STATUS = [
_('Unconfirmed'),
_('Unconfirmed parent'),
_('Not Verified'),
_('Local'),
]
async def _append_utxos_to_inputs(
*,
inputs: List[PartialTxInput],
network: 'Network',
script_descriptor: 'descriptor.Descriptor',
imax: int,
) -> None:
script = script_descriptor.expand().output_script.hex()
scripthash = bitcoin.script_to_scripthash(script)
async def append_single_utxo(item):
prev_tx_raw = await network.get_transaction(item['tx_hash'])
prev_tx = Transaction(prev_tx_raw)
prev_txout = prev_tx.outputs()[item['tx_pos']]
if scripthash != bitcoin.script_to_scripthash(prev_txout.scriptpubkey.hex()):
raise Exception('scripthash mismatch when sweeping')
prevout_str = item['tx_hash'] + ':%d' % item['tx_pos']
prevout = TxOutpoint.from_str(prevout_str)
txin = PartialTxInput(prevout=prevout)
txin.utxo = prev_tx
txin.block_height = int(item['height'])
txin.script_descriptor = script_descriptor
inputs.append(txin)
u = await network.listunspent_for_scripthash(scripthash)
async with OldTaskGroup() as group:
for item in u:
if len(inputs) >= imax:
break
await group.spawn(append_single_utxo(item))
async def sweep_preparations(privkeys, network: 'Network', imax=100):
async def find_utxos_for_privkey(txin_type, privkey, compressed):
pubkey = ecc.ECPrivkey(privkey).get_public_key_hex(compressed=compressed)
desc = descriptor.get_singlesig_descriptor_from_legacy_leaf(pubkey=pubkey, script_type=txin_type)
await _append_utxos_to_inputs(
inputs=inputs,
network=network,
script_descriptor=desc,
imax=imax)
keypairs[pubkey] = privkey, compressed
inputs = [] # type: List[PartialTxInput]
keypairs = {}
async with OldTaskGroup() as group:
for sec in privkeys:
txin_type, privkey, compressed = bitcoin.deserialize_privkey(sec)
await group.spawn(find_utxos_for_privkey(txin_type, privkey, compressed))
# do other lookups to increase support coverage
if is_minikey(sec):
# minikeys don't have a compressed byte
# we lookup both compressed and uncompressed pubkeys
await group.spawn(find_utxos_for_privkey(txin_type, privkey, not compressed))
elif txin_type == 'p2pkh':
# WIF serialization does not distinguish p2pkh and p2pk
# we also search for pay-to-pubkey outputs
await group.spawn(find_utxos_for_privkey('p2pk', privkey, compressed))
if not inputs:
raise UserFacingException(_('No inputs found.'))
return inputs, keypairs
async def sweep(
privkeys,
*,
network: 'Network',
config: 'SimpleConfig',
to_address: str,
fee: int = None,
imax=100,
locktime=None,
tx_version=None) -> PartialTransaction:
inputs, keypairs = await sweep_preparations(privkeys, network, imax)
total = sum(txin.value_sats() for txin in inputs)
if fee is None:
outputs = [PartialTxOutput(scriptpubkey=bfh(bitcoin.address_to_script(to_address)),
value=total)]
tx = PartialTransaction.from_io(inputs, outputs)
fee = config.estimate_fee(tx.estimated_size())
if total - fee < 0:
raise Exception(_('Not enough funds on address.') + '\nTotal: %d satoshis\nFee: %d'%(total, fee))
if total - fee < dust_threshold(network):
raise Exception(_('Not enough funds on address.') + '\nTotal: %d satoshis\nFee: %d\nDust Threshold: %d'%(total, fee, dust_threshold(network)))
outputs = [PartialTxOutput(scriptpubkey=bfh(bitcoin.address_to_script(to_address)),
value=total - fee)]
if locktime is None:
locktime = get_locktime_for_new_transaction(network)
tx = PartialTransaction.from_io(inputs, outputs, locktime=locktime, version=tx_version)
tx.set_rbf(True)
tx.sign(keypairs)
return tx
def get_locktime_for_new_transaction(network: 'Network') -> int:
# if no network or not up to date, just set locktime to zero
if not network:
return 0
chain = network.blockchain()
if chain.is_tip_stale():
return 0
# figure out current block height
chain_height = chain.height() # learnt from all connected servers, SPV-checked
server_height = network.get_server_height() # height claimed by main server, unverified
# note: main server might be lagging (either is slow, is malicious, or there is an SPV-invisible-hard-fork)
# - if it's lagging too much, it is the network's job to switch away
if server_height < chain_height - 10:
# the diff is suspiciously large... give up and use something non-fingerprintable
return 0
# discourage "fee sniping"
locktime = min(chain_height, server_height)
# sometimes pick locktime a bit further back, to help privacy
# of setups that need more time (offline/multisig/coinjoin/...)
if random.randint(0, 9) == 0:
locktime = max(0, locktime - random.randint(0, 99))
locktime = max(0, locktime)
return locktime
class CannotRBFTx(Exception): pass
class CannotBumpFee(CannotRBFTx):
def __str__(self):
return _('Cannot bump fee') + ':\n\n' + Exception.__str__(self)
class CannotDoubleSpendTx(CannotRBFTx):
def __str__(self):
return _('Cannot cancel transaction') + ':\n\n' + Exception.__str__(self)
class CannotCPFP(Exception):
def __str__(self):
return _('Cannot create child transaction') + ':\n\n' + Exception.__str__(self)
class InternalAddressCorruption(Exception):
def __str__(self):
return _("Wallet file corruption detected. "
"Please restore your wallet from seed, and compare the addresses in both files")
class TransactionPotentiallyDangerousException(Exception): pass
class TransactionDangerousException(TransactionPotentiallyDangerousException): pass
class TxSighashRiskLevel(enum.IntEnum):
# higher value -> more risk
SAFE = 0
FEE_WARNING_SKIPCONFIRM = 1 # show warning icon (ignored for CLI)
FEE_WARNING_NEEDCONFIRM = 2 # prompt user for confirmation
WEIRD_SIGHASH = 3 # prompt user for confirmation
INSANE_SIGHASH = 4 # reject
class TxSighashDanger:
def __init__(
self,
*,
risk_level: TxSighashRiskLevel = TxSighashRiskLevel.SAFE,
short_message: str = None,
messages: List[str] = None,
):
self.risk_level = risk_level
self.short_message = short_message
self._messages = messages or []
def needs_confirm(self) -> bool:
"""If True, the user should be prompted for explicit confirmation before signing."""
return self.risk_level >= TxSighashRiskLevel.FEE_WARNING_NEEDCONFIRM
def needs_reject(self) -> bool:
"""If True, the transaction should be rejected, i.e. abort signing."""
return self.risk_level >= TxSighashRiskLevel.INSANE_SIGHASH
def get_long_message(self) -> str:
"""Returns a description of the potential dangers of signing the tx that can be shown to the user.
Empty string if there are none.
"""
if self.short_message:
header = [self.short_message]
else:
header = []
return "\n".join(header + self._messages)
def combine(*args: 'TxSighashDanger') -> 'TxSighashDanger':
max_danger = max(args, key=lambda sighash_danger: sighash_danger.risk_level) # type: TxSighashDanger
messages = [msg for sighash_danger in args for msg in sighash_danger._messages]
return TxSighashDanger(
risk_level=max_danger.risk_level,
short_message=max_danger.short_message,
messages=messages,
)
def __repr__(self):
return (f"<{self.__class__.__name__} risk_level={self.risk_level} "
f"short_message={self.short_message!r} _messages={self._messages!r}>")
class BumpFeeStrategy(enum.Enum):
PRESERVE_PAYMENT = enum.auto()
DECREASE_PAYMENT = enum.auto()
@classmethod
def all(cls) -> Sequence['BumpFeeStrategy']:
return list(BumpFeeStrategy.__members__.values())
def text(self) -> str:
if self == self.PRESERVE_PAYMENT:
return _('Preserve payment')
elif self == self.DECREASE_PAYMENT:
return _('Decrease payment')
else:
raise Exception(f"unknown strategy: {self=}")
class ReceiveRequestHelp(NamedTuple):
# help texts (warnings/errors):
address_help: str
URI_help: str
ln_help: str
# whether the texts correspond to an error (or just a warning):
address_is_error: bool
URI_is_error: bool
ln_is_error: bool
ln_swap_suggestion: Optional[Any] = None
ln_rebalance_suggestion: Optional[Any] = None
def can_swap(self) -> bool:
return bool(self.ln_swap_suggestion)
def can_rebalance(self) -> bool:
return bool(self.ln_rebalance_suggestion)
class TxWalletDelta(NamedTuple):
is_relevant: bool # "related to wallet?"
is_any_input_ismine: bool
is_all_input_ismine: bool
delta: int
fee: Optional[int]
class TxWalletDetails(NamedTuple):
txid: Optional[str]
status: str
label: str
can_broadcast: bool
can_bump: bool
can_cpfp: bool
can_dscancel: bool # whether user can double-spend to self
can_save_as_local: bool
amount: Optional[int]
fee: Optional[int]
tx_mined_status: TxMinedInfo
mempool_depth_bytes: Optional[int]
can_remove: bool # whether user should be allowed to delete tx
is_lightning_funding_tx: bool
is_related_to_wallet: bool
class Abstract_Wallet(ABC, Logger, EventListener):
"""
Wallet classes are created to handle various address generation methods.
Completion states (watching-only, single account, no seed, etc) are handled inside classes.
"""
LOGGING_SHORTCUT = 'w'
max_change_outputs = 3
gap_limit_for_change = 10
txin_type: str
wallet_type: str
lnworker: Optional['LNWallet']
network: Optional['Network']
def __init__(self, db: WalletDB, *, config: SimpleConfig):
self.config = config
assert self.config is not None, "config must not be None"
self.db = db
self.storage = db.storage # type: Optional[WalletStorage]
# load addresses needs to be called before constructor for sanity checks
db.load_addresses(self.wallet_type)
self.keystore = None # type: Optional[KeyStore] # will be set by load_keystore
self._password_in_memory = None # see self.unlock
Logger.__init__(self)
self.network = None
self.adb = AddressSynchronizer(db, config, name=self.diagnostic_name())
for addr in self.get_addresses():
self.adb.add_address(addr)
self.lock = self.adb.lock
self.transaction_lock = self.adb.transaction_lock
self._last_full_history = None
self._tx_parents_cache = {}
self.taskgroup = OldTaskGroup()
# saved fields
self.use_change = db.get('use_change', True)
self.multiple_change = db.get('multiple_change', False)
self._labels = db.get_dict('labels')
self._frozen_addresses = set(db.get('frozen_addresses', []))
self._frozen_coins = db.get_dict('frozen_coins') # type: Dict[str, bool]
self.fiat_value = db.get_dict('fiat_value')
self._receive_requests = db.get_dict('payment_requests') # type: Dict[str, Request]
self._invoices = db.get_dict('invoices') # type: Dict[str, Invoice]
self._reserved_addresses = set(db.get('reserved_addresses', []))
self._num_parents = db.get_dict('num_parents')
self._freeze_lock = threading.RLock() # for mutating/iterating frozen_{addresses,coins}
self.load_keystore()
self._init_lnworker()
self._init_requests_rhash_index()
self._prepare_onchain_invoice_paid_detection()
self.calc_unused_change_addresses()
# save wallet type the first time
if self.db.get('wallet_type') is None:
self.db.put('wallet_type', self.wallet_type)
self.contacts = Contacts(self.db)
self._coin_price_cache = {}
# true when synchronized. this is stricter than adb.is_up_to_date():
# to-be-generated (HD) addresses are also considered here (gap-limit-roll-forward)
self._up_to_date = False
self.test_addresses_sanity()
if self.storage and self.has_storage_encryption():
if (se := self.storage.get_encryption_version()) != (ae := self.get_available_storage_encryption_version()):
raise WalletFileException(f"unexpected storage encryption type. found: {se!r}. allowed: {ae!r}")
self.register_callbacks()
def _init_lnworker(self):
self.lnworker = None
async def main_loop(self):
self.logger.info("starting taskgroup.")
try:
async with self.taskgroup as group:
await group.spawn(asyncio.Event().wait) # run forever (until cancel)
await group.spawn(self.do_synchronize_loop())
except Exception as e:
self.logger.exception("taskgroup died.")
finally:
util.trigger_callback('wallet_updated', self)
self.logger.info("taskgroup stopped.")
async def do_synchronize_loop(self):
"""Generates new deterministic addresses if needed (gap limit roll-forward),
and sets up_to_date.
"""
while True:
# polling.
# TODO if adb had "up_to_date_changed" asyncio.Event(), we could *also* trigger on that.
# The polling would still be useful as often need to gen new addrs while adb.is_up_to_date() is False
await asyncio.sleep(0.1)
# note: we only generate new HD addresses if the existing ones
# have history that are mined and SPV-verified.
await run_in_thread(self.synchronize)
def save_db(self):
if self.db.storage:
self.db.write()
def save_backup(self, backup_dir):
new_path = os.path.join(backup_dir, self.basename() + '.backup')
new_storage = WalletStorage(new_path)
new_storage._encryption_version = self.storage._encryption_version
new_storage.pubkey = self.storage.pubkey
new_db = WalletDB(self.db.dump(), storage=new_storage, upgrade=True)
if self.lnworker:
channel_backups = new_db.get_dict('imported_channel_backups')
for chan_id, chan in self.lnworker.channels.items():
channel_backups[chan_id.hex()] = self.lnworker.create_channel_backup(chan_id)
new_db.put('channels', None)
new_db.put('lightning_privkey2', None)
new_db.set_modified(True)
new_db.write()
return new_path
def has_lightning(self) -> bool:
return bool(self.lnworker)
def can_have_lightning(self) -> bool:
# we want static_remotekey to be a wallet address
return self.txin_type == 'p2wpkh'
def can_have_deterministic_lightning(self) -> bool:
if not self.can_have_lightning():
return False
if not self.keystore:
return False
return self.keystore.can_have_deterministic_lightning_xprv()
def init_lightning(self, *, password) -> None:
assert self.can_have_lightning()
assert self.db.get('lightning_xprv') is None
assert self.db.get('lightning_privkey2') is None
if self.can_have_deterministic_lightning():
assert isinstance(self.keystore, keystore.BIP32_KeyStore)
ln_xprv = self.keystore.get_lightning_xprv(password)
self.db.put('lightning_xprv', ln_xprv)
else:
seed = os.urandom(32)
node = BIP32Node.from_rootseed(seed, xtype='standard')
ln_xprv = node.to_xprv()
self.db.put('lightning_privkey2', ln_xprv)
self.lnworker = LNWallet(self, ln_xprv)
self.save_db()
if self.network:
self._start_network_lightning()
async def stop(self):
"""Stop all networking and save DB to disk."""
self.unregister_callbacks()
try:
async with ignore_after(5):
if self.network:
if self.lnworker:
await self.lnworker.stop()
self.lnworker = None
await self.adb.stop()
await self.taskgroup.cancel_remaining()
finally: # even if we get cancelled
if any([ks.is_requesting_to_be_rewritten_to_wallet_file for ks in self.get_keystores()]):
self.save_keystore()
self.save_db()
def is_up_to_date(self) -> bool:
if self.taskgroup.joined: # either stop() was called, or the taskgroup died
return False
return self._up_to_date
def tx_is_related(self, tx):
is_mine = any([self.is_mine(out.address) for out in tx.outputs()])
is_mine |= any([self.is_mine(self.adb.get_txin_address(txin)) for txin in tx.inputs()])
return is_mine
def clear_tx_parents_cache(self):
with self.lock, self.transaction_lock:
self._tx_parents_cache.clear()
self._num_parents.clear()
self._last_full_history = None
@event_listener
async def on_event_adb_set_up_to_date(self, adb):
if self.adb != adb:
return
num_new_addrs = await run_in_thread(self.synchronize)
up_to_date = self.adb.is_up_to_date() and num_new_addrs == 0
with self.lock:
status_changed = self._up_to_date != up_to_date
self._up_to_date = up_to_date
if up_to_date:
self.adb.reset_netrequest_counters() # sync progress indicator
self.save_db()
# fire triggers
if status_changed or up_to_date: # suppress False->False transition, as it is spammy
util.trigger_callback('wallet_updated', self)
util.trigger_callback('status')
if status_changed:
self.logger.info(f'set_up_to_date: {up_to_date}')
@event_listener
def on_event_adb_added_tx(self, adb, tx_hash: str, tx: Transaction):
if self.adb != adb:
return
if not self.tx_is_related(tx):
return
self.clear_tx_parents_cache()
if self.lnworker:
self.lnworker.maybe_add_backup_from_tx(tx)
self._update_invoices_and_reqs_touched_by_tx(tx_hash)
util.trigger_callback('new_transaction', self, tx)
@event_listener
def on_event_adb_removed_tx(self, adb, txid: str, tx: Transaction):
if self.adb != adb:
return
if not self.tx_is_related(tx):
return
self.clear_tx_parents_cache()
util.trigger_callback('removed_transaction', self, tx)
@event_listener
def on_event_adb_added_verified_tx(self, adb, tx_hash):
if adb != self.adb:
return
self._update_invoices_and_reqs_touched_by_tx(tx_hash)
tx_mined_status = self.adb.get_tx_height(tx_hash)
util.trigger_callback('verified', self, tx_hash, tx_mined_status)
@event_listener
def on_event_adb_removed_verified_tx(self, adb, tx_hash):
if adb != self.adb:
return
self._update_invoices_and_reqs_touched_by_tx(tx_hash)
def clear_history(self):
self.adb.clear_history()
self.save_db()
def start_network(self, network: 'Network'):
assert self.network is None, "already started"
self.network = network
if network:
asyncio.run_coroutine_threadsafe(self.main_loop(), self.network.asyncio_loop)
self.adb.start_network(network)
if self.lnworker:
self._start_network_lightning()
def _start_network_lightning(self):
assert self.lnworker
assert self.lnworker.network is None, 'lnworker network already initialized'
self.lnworker.start_network(self.network)
# only start gossiping when we already have channels
if self.db.get('channels'):
self.network.start_gossip()
@abstractmethod
def load_keystore(self) -> None:
pass
def diagnostic_name(self):
return self.basename()
def __str__(self):
return self.basename()
def get_master_public_key(self):
return None
def get_master_public_keys(self):
return []
def basename(self) -> str:
return self.storage.basename() if self.storage else 'no_name'
def test_addresses_sanity(self) -> None:
addrs = self.get_receiving_addresses()
if len(addrs) > 0:
addr = str(addrs[0])
if not bitcoin.is_address(addr):
neutered_addr = addr[:5] + '..' + addr[-2:]
raise WalletFileException(f'The addresses in this wallet are not bitcoin addresses.\n'
f'e.g. {neutered_addr} (length: {len(addr)})')
def check_returned_address_for_corruption(func):
def wrapper(self, *args, **kwargs):
addr = func(self, *args, **kwargs)
self.check_address_for_corruption(addr)
return addr
return wrapper
def calc_unused_change_addresses(self) -> Sequence[str]:
"""Returns a list of change addresses to choose from, for usage in e.g. new transactions.
The caller should give priority to earlier ones in the list.
"""
with self.lock:
# We want a list of unused change addresses.
# As a performance optimisation, to avoid checking all addresses every time,
# we maintain a list of "not old" addresses ("old" addresses have deeply confirmed history),
# and only check those.
if not hasattr(self, '_not_old_change_addresses'):
self._not_old_change_addresses = self.get_change_addresses()
self._not_old_change_addresses = [addr for addr in self._not_old_change_addresses
if not self.adb.address_is_old(addr)]
unused_addrs = [addr for addr in self._not_old_change_addresses
if not self.adb.is_used(addr) and not self.is_address_reserved(addr)]
return unused_addrs
def is_deterministic(self) -> bool:
return self.keystore.is_deterministic()
def _set_label(self, key: str, value: Optional[str]) -> None:
with self.lock:
if value is None:
self._labels.pop(key, None)
else:
self._labels[key] = value
def set_label(self, name: str, text: str = None) -> bool:
if not name:
return False
changed = False
with self.lock:
old_text = self._labels.get(name)
if text:
text = text.replace("\n", " ")
if old_text != text:
self._labels[name] = text
changed = True
else:
if old_text is not None:
self._labels.pop(name)
changed = True
if changed:
run_hook('set_label', self, name, text)
return changed
def import_labels(self, path):
data = read_json_file(path)
for key, value in data.items():
self.set_label(key, value)
def export_labels(self, path):
write_json_file(path, self.get_all_labels())
def set_fiat_value(self, txid, ccy, text, fx, value_sat):
if not self.db.get_transaction(txid):
return
# since fx is inserting the thousands separator,
# and not util, also have fx remove it
text = fx.remove_thousands_separator(text)
def_fiat = self.default_fiat_value(txid, fx, value_sat)
formatted = fx.ccy_amount_str(def_fiat, add_thousands_sep=False)
def_fiat_rounded = Decimal(formatted)
reset = not text
if not reset:
try:
text_dec = Decimal(text)
text_dec_rounded = Decimal(fx.ccy_amount_str(text_dec, add_thousands_sep=False))
reset = text_dec_rounded == def_fiat_rounded
except Exception:
# garbage. not resetting, but not saving either
return False
if reset:
d = self.fiat_value.get(ccy, {})
if d and txid in d:
d.pop(txid)
else:
# avoid saving empty dict
return True
else:
if ccy not in self.fiat_value:
self.fiat_value[ccy] = {}
self.fiat_value[ccy][txid] = text
return reset
def get_fiat_value(self, txid, ccy):
fiat_value = self.fiat_value.get(ccy, {}).get(txid)
try:
return Decimal(fiat_value)
except Exception:
return
def is_mine(self, address) -> bool:
if not address: return False
return bool(self.get_address_index(address))
def is_change(self, address) -> bool:
if not self.is_mine(address):
return False
return self.get_address_index(address)[0] == 1
@abstractmethod
def get_addresses(self) -> Sequence[str]:
pass
@abstractmethod
def get_address_index(self, address: str) -> Optional[AddressIndexGeneric]:
pass
@abstractmethod
def get_address_path_str(self, address: str) -> Optional[str]:
"""Returns derivation path str such as "m/0/5" to address,
or None if not applicable.
"""
pass
def get_redeem_script(self, address: str) -> Optional[str]:
desc = self.get_script_descriptor_for_address(address)
if desc is None: return None
redeem_script = desc.expand().redeem_script
if redeem_script:
return redeem_script.hex()
def get_witness_script(self, address: str) -> Optional[str]:
desc = self.get_script_descriptor_for_address(address)
if desc is None: return None
witness_script = desc.expand().witness_script
if witness_script:
return witness_script.hex()
@abstractmethod
def get_txin_type(self, address: str) -> str:
"""Return script type of wallet address."""
pass
def export_private_key(self, address: str, password: Optional[str]) -> str:
if self.is_watching_only():
raise UserFacingException(_("This is a watching-only wallet"))
if not is_address(address):
raise UserFacingException(_('Invalid bitcoin address: {}').format(address))
if not self.is_mine(address):
raise UserFacingException(_('Address not in wallet: {}').format(address))
index = self.get_address_index(address)
pk, compressed = self.keystore.get_private_key(index, password)
txin_type = self.get_txin_type(address)
serialized_privkey = bitcoin.serialize_privkey(pk, compressed, txin_type)
return serialized_privkey
def export_private_key_for_path(self, path: Union[Sequence[int], str], password: Optional[str]) -> str:
raise UserFacingException("this wallet is not deterministic")
@abstractmethod
def get_public_keys(self, address: str) -> Sequence[str]:
pass
def get_public_keys_with_deriv_info(self, address: str) -> Dict[bytes, Tuple[KeyStoreWithMPK, Sequence[int]]]:
"""Returns a map: pubkey -> (keystore, derivation_suffix)"""
return {}
def is_lightning_funding_tx(self, txid: Optional[str]) -> bool:
if not self.lnworker or txid is None:
return False
if any([chan.funding_outpoint.txid == txid
for chan in self.lnworker.channels.values()]):
return True
if any([chan.funding_outpoint.txid == txid
for chan in self.lnworker.channel_backups.values()]):
return True
return False
def get_swap_by_claim_tx(self, tx: Transaction) -> bool:
return self.lnworker.swap_manager.get_swap_by_claim_tx(tx) if self.lnworker else None
def get_swap_by_funding_tx(self, tx: Transaction) -> bool:
return bool(self.lnworker.swap_manager.get_swap_by_funding_tx(tx)) if self.lnworker else None
def get_wallet_delta(self, tx: Transaction) -> TxWalletDelta:
"""Return the effect a transaction has on the wallet.
This method must use self.is_mine, not self.adb.is_mine()
"""
is_relevant = False # "related to wallet?"
num_input_ismine = 0
v_in = v_in_mine = v_out = v_out_mine = 0
with self.lock, self.transaction_lock:
for txin in tx.inputs():
addr = self.adb.get_txin_address(txin)
value = self.adb.get_txin_value(txin, address=addr)
if self.is_mine(addr):
num_input_ismine += 1
is_relevant = True
assert value is not None
v_in_mine += value
if value is None:
v_in = None
elif v_in is not None:
v_in += value
for txout in tx.outputs():
v_out += txout.value
if self.is_mine(txout.address):
v_out_mine += txout.value
is_relevant = True
delta = v_out_mine - v_in_mine
if v_in is not None:
fee = v_in - v_out
else:
fee = None
if fee is None and isinstance(tx, PartialTransaction):
fee = tx.get_fee()
return TxWalletDelta(
is_relevant=is_relevant,
is_any_input_ismine=num_input_ismine > 0,
is_all_input_ismine=num_input_ismine == len(tx.inputs()),
delta=delta,
fee=fee,
)
def get_tx_info(self, tx: Transaction) -> TxWalletDetails:
tx_wallet_delta = self.get_wallet_delta(tx)
is_relevant = tx_wallet_delta.is_relevant
is_any_input_ismine = tx_wallet_delta.is_any_input_ismine
is_swap = bool(self.get_swap_by_claim_tx(tx))
fee = tx_wallet_delta.fee
exp_n = None
can_broadcast = False
can_bump = False
can_cpfp = False
tx_hash = tx.txid() # note: txid can be None! e.g. when called from GUI tx dialog
is_lightning_funding_tx = self.is_lightning_funding_tx(tx_hash)
tx_we_already_have_in_db = self.adb.db.get_transaction(tx_hash)
can_save_as_local = (is_relevant and tx.txid() is not None
and (tx_we_already_have_in_db is None or not tx_we_already_have_in_db.is_complete()))
label = ''
tx_mined_status = self.adb.get_tx_height(tx_hash)
can_remove = ((tx_mined_status.height in [TX_HEIGHT_FUTURE, TX_HEIGHT_LOCAL])
# otherwise 'height' is unreliable (typically LOCAL):
and is_relevant
# don't offer during common signing flow, e.g. when watch-only wallet starts creating a tx:
and bool(tx_we_already_have_in_db))
can_dscancel = False
if tx.is_complete():
if tx_we_already_have_in_db:
label = self.get_label_for_txid(tx_hash)
if tx_mined_status.height > 0:
if tx_mined_status.conf:
status = _("{} confirmations").format(tx_mined_status.conf)
else:
status = _('Not verified')
elif tx_mined_status.height in (TX_HEIGHT_UNCONF_PARENT, TX_HEIGHT_UNCONFIRMED):
status = _('Unconfirmed')
if fee is None:
fee = self.adb.get_tx_fee(tx_hash)
if fee and self.network and self.config.has_fee_mempool():
size = tx.estimated_size()
fee_per_byte = fee / size
exp_n = self.config.fee_to_depth(fee_per_byte)
can_bump = (is_any_input_ismine or is_swap) and tx.is_rbf_enabled()
can_dscancel = (is_any_input_ismine and tx.is_rbf_enabled()
and not all([self.is_mine(txout.address) for txout in tx.outputs()]))
try:
self.cpfp(tx, 0)
can_cpfp = True
except Exception:
can_cpfp = False
else:
status = _('Local')
if tx_mined_status.height == TX_HEIGHT_FUTURE:
num_blocks_remainining = tx_mined_status.wanted_height - self.adb.get_local_height()
num_blocks_remainining = max(0, num_blocks_remainining)
status = _('Local (future: {})').format(_('in {} blocks').format(num_blocks_remainining))
can_broadcast = self.network is not None
can_bump = (is_any_input_ismine or is_swap) and tx.is_rbf_enabled()
else:
status = _("Signed")
can_broadcast = self.network is not None
else:
assert isinstance(tx, PartialTransaction)
s, r = tx.signature_count()
status = _("Unsigned") if s == 0 else _('Partially signed') + ' (%d/%d)'%(s,r)
if is_relevant:
if tx_wallet_delta.is_all_input_ismine:
assert fee is not None
amount = tx_wallet_delta.delta + fee
else:
amount = tx_wallet_delta.delta
else:
amount = None
if is_lightning_funding_tx:
can_bump = False # would change txid
return TxWalletDetails(
txid=tx_hash,
status=status,
label=label,
can_broadcast=can_broadcast,
can_bump=can_bump,
can_cpfp=can_cpfp,
can_dscancel=can_dscancel,
can_save_as_local=can_save_as_local,
amount=amount,
fee=fee,
tx_mined_status=tx_mined_status,
mempool_depth_bytes=exp_n,
can_remove=can_remove,
is_lightning_funding_tx=is_lightning_funding_tx,
is_related_to_wallet=is_relevant,
)
def get_num_parents(self, txid: str) -> Optional[int]:
if not self.is_up_to_date():
return
if txid not in self._num_parents:
self._num_parents[txid] = len(self.get_tx_parents(txid))
return self._num_parents[txid]
def get_tx_parents(self, txid: str) -> Dict[str, Tuple[List[str], List[str]]]:
"""
returns a flat dict:
txid -> list of parent txids
"""
with self.lock, self.transaction_lock:
if self._last_full_history is None:
self._last_full_history = self.get_full_history(None, include_lightning=False)
# populate cache in chronological order (confirmed tx only)
# todo: get_full_history should return unconfirmed tx topologically sorted
for _txid, tx_item in self._last_full_history.items():
if tx_item['height'] > 0:
self.get_tx_parents(_txid)