forked from cryptoadvance/specter-desktop
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathwallet.py
1618 lines (1502 loc) · 59.8 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
import copy, hashlib, json, logging, os, re
import time
from .device import Device
from .key import Key
from .util.merkleblock import is_valid_merkle_proof
from .helpers import der_to_bytes
from embit import base58
from .util.descriptor import Descriptor, sort_descriptor, AddChecksum
from .util.xpub import get_xpub_fingerprint
from .util.tx import decoderawtransaction
from .persistence import write_json_file, delete_file
from hwilib.serializations import PSBT, CTransaction
from io import BytesIO
from .specter_error import SpecterError
import threading
import requests
from math import ceil
from .addresslist import AddressList
from .txlist import TxList
logger = logging.getLogger()
LISTTRANSACTIONS_BATCH_SIZE = 1000
class Wallet:
# if the wallet is old we import 300 addresses
IMPORT_KEYPOOL = 300
# a gap of 20 addresses is what many wallets do (not used with descriptor wallets)
GAP_LIMIT = 20
# minimal fee rate is slightly above 1 sat/vbyte
# to avoid rounding errors
MIN_FEE_RATE = 1.01
def __init__(
self,
name,
alias,
description,
address_type,
address,
address_index,
change_address,
change_index,
keypool,
change_keypool,
recv_descriptor,
change_descriptor,
keys,
devices,
sigs_required,
pending_psbts,
frozen_utxo,
fullpath,
device_manager,
manager,
old_format_detected=False,
last_block=None,
):
self.name = name
self.alias = alias
self.description = description
self.address_type = address_type
self.address = address
self.address_index = address_index
self.change_address = change_address
self.change_index = change_index
self.keypool = keypool
self.change_keypool = change_keypool
self.recv_descriptor = recv_descriptor
self.change_descriptor = change_descriptor
self.keys = keys
self.devices = [
(
device
if isinstance(device, Device)
else device_manager.get_by_alias(device)
)
for device in devices
]
if None in self.devices:
raise Exception("A device used by this wallet could not have been found!")
self.sigs_required = int(sigs_required)
self.pending_psbts = pending_psbts
self.frozen_utxo = frozen_utxo
self.fullpath = fullpath
self.manager = manager
self.rpc = self.manager.rpc.wallet(
os.path.join(self.manager.rpc_path, self.alias)
)
self.last_block = last_block
addr_path = self.fullpath.replace(".json", "_addr.csv")
self._addresses = AddressList(addr_path, self.rpc)
if not self._addresses.file_exists:
self.fetch_labels()
txs_path = self.fullpath.replace(".json", "_txs.csv")
self._transactions = TxList(
txs_path, self.rpc, self._addresses, self.manager.chain
)
if address == "":
self.getnewaddress()
if change_address == "":
self.getnewaddress(change=True)
self.update()
if old_format_detected or self.last_block != last_block:
self.save_to_file()
def fetch_labels(self):
"""Load addresses and labels to self._addresses"""
recv = [
dict(
address=self.get_address(idx, change=False, check_keypool=False),
index=idx,
change=False,
)
for idx in range(self.keypool)
]
change = [
dict(
address=self.get_address(idx, change=True, check_keypool=False),
index=idx,
change=True,
)
for idx in range(self.change_keypool)
]
# TODO: load addresses for all txs here as well
self._addresses.add(recv + change, check_rpc=True)
def fetch_transactions(self):
"""Load transactions from Bitcoin Core"""
arr = []
idx = 0
while True:
res = self.rpc.listtransactions(
"*",
LISTTRANSACTIONS_BATCH_SIZE,
LISTTRANSACTIONS_BATCH_SIZE * idx,
True,
)
res = [
tx
for tx in res
if tx["txid"] not in self._transactions
or not self._transactions[tx["txid"]].get("address", None)
or self._transactions[tx["txid"]].get("blockhash", None)
!= tx.get("blockhash", None)
or (
self._transactions[tx["txid"]].get("blockhash", None)
and not self._transactions[tx["txid"]].get("blockheight", None)
) # Fix for Core v19 with Specter v1
or self._transactions[tx["txid"]].get("conflicts", [])
!= tx.get("walletconflicts", [])
]
# TODO: Looks like Core ignore a consolidation (self-transfer) going into the change address (in listtransactions)
# This means it'll show unconfirmed for us forever...
arr.extend(res)
idx += 1
# not sure if Core <20 returns last batch or empty array at the end
if (
len(res) < LISTTRANSACTIONS_BATCH_SIZE
or len(arr) < LISTTRANSACTIONS_BATCH_SIZE * idx
):
break
txs = dict.fromkeys([a["txid"] for a in arr])
txids = list(txs.keys())
# get all raw transactions
res = self.rpc.multi([("gettransaction", txid) for txid in txids])
for i, r in enumerate(res):
txid = txids[i]
# check if we already added it
if txs.get(txid, None) is not None:
continue
txs[txid] = r["result"]
# This is a fix for Bitcoin Core versions < v0.20
# These do not return the blockheight as part of the `gettransaction` command
# So here we check if this property is lacking and if so
# query the current block height and manually calculate it.
##################### Remove from here after dropping Core v0.19 support #####################
check_blockheight = False
for tx in txs.values():
if tx.get("confirmations", 0) > 0 and "blockheight" not in tx:
check_blockheight = True
break
if check_blockheight:
current_blockheight = self.rpc.getblockcount()
for tx in txs.values():
if tx.get("confirmations", 0) > 0:
tx["blockheight"] = current_blockheight - tx["confirmations"] + 1
##################### Remove until here after dropping Core v0.19 support #####################
self._transactions.add(txs)
if self.use_descriptors:
while (
len(
[
tx
for tx in self._transactions
if self._transactions[tx]["category"] != "send"
and not self._transactions[tx]["address"]
]
)
!= 0
):
addresses = [
dict(
address=self.get_address(
idx, change=False, check_keypool=False
),
index=idx,
change=False,
)
for idx in range(
self._addresses.max_index(change=False),
self._addresses.max_index(change=False) + self.GAP_LIMIT,
)
]
change_addresses = [
dict(
address=self.get_address(idx, change=True, check_keypool=False),
index=idx,
change=True,
)
for idx in range(
self._addresses.max_index(change=True),
self._addresses.max_index(change=True) + self.GAP_LIMIT,
)
]
self._addresses.add(addresses, check_rpc=False)
self._addresses.add(change_addresses, check_rpc=False)
self._transactions.add(txs)
def update(self):
self.getdata()
self.get_balance()
self.check_addresses()
def check_unused(self):
"""Check current receive address is unused and get new if needed"""
addr = self.address
try:
while self.rpc.getreceivedbyaddress(addr, 0) != 0:
addr = self.getnewaddress()
except Exception as e:
logger.error(f"Failed to check for address reuse: {e}")
def check_addresses(self):
"""Checking the gap limit is still ok"""
if self.last_block is None:
obj = self.rpc.listsinceblock()
else:
# sometimes last_block is invalid, not sure why
try:
obj = self.rpc.listsinceblock(self.last_block)
except:
logger.error(f"Invalid block {self.last_block}")
obj = self.rpc.listsinceblock()
txs = obj["transactions"]
last_block = obj["lastblock"]
addresses = [tx["address"] for tx in txs if "address" in tx]
# remove duplicates
addresses = list(dict.fromkeys(addresses))
max_recv = self.address_index - 1
max_change = self.change_index - 1
# get max used from addresses list
max_recv = max(max_recv, self._addresses.max_used_index(False))
max_change = max(max_change, self._addresses.max_used_index(True))
# from tx list
for addr in addresses:
if addr in self._addresses:
a = self._addresses[addr]
if a.index is not None:
if a.change:
max_change = max(max_change, a.index)
else:
max_recv = max(max_recv, a.index)
updated = False
while max_recv >= self.address_index:
self.getnewaddress(change=False, save=False)
updated = True
while max_change >= self.change_index:
self.getnewaddress(change=True, save=False)
updated = True
# save only if needed
if updated:
self.save_to_file()
self.last_block = last_block
@staticmethod
def parse_old_format(wallet_dict, device_manager):
old_format_detected = False
new_dict = {}
new_dict.update(wallet_dict)
if "key" in wallet_dict:
new_dict["keys"] = [wallet_dict["key"]]
del new_dict["key"]
old_format_detected = True
if "device" in wallet_dict:
new_dict["devices"] = [wallet_dict["device"]]
del new_dict["device"]
old_format_detected = True
devices = [
device_manager.get_by_alias(device) for device in new_dict["devices"]
]
if (
len(new_dict["keys"]) > 1
and "sortedmulti" not in new_dict["recv_descriptor"]
):
new_dict["recv_descriptor"] = AddChecksum(
new_dict["recv_descriptor"]
.replace("multi", "sortedmulti")
.split("#")[0]
)
old_format_detected = True
if (
len(new_dict["keys"]) > 1
and "sortedmulti" not in new_dict["change_descriptor"]
):
new_dict["change_descriptor"] = AddChecksum(
new_dict["change_descriptor"]
.replace("multi", "sortedmulti")
.split("#")[0]
)
old_format_detected = True
if None in devices:
devices = [
(
(device["name"] if isinstance(device, dict) else device)
if (device["name"] if isinstance(device, dict) else device)
in device_manager.devices
else None
)
for device in new_dict["devices"]
]
if None in devices:
logger.error("A device used by this wallet could not have been found!")
return
else:
new_dict["devices"] = [
device_manager.devices[device].alias for device in devices
]
old_format_detected = True
new_dict["old_format_detected"] = old_format_detected
return new_dict
@classmethod
def from_json(
cls, wallet_dict, device_manager, manager, default_alias="", default_fullpath=""
):
name = wallet_dict.get("name", "")
alias = wallet_dict.get("alias", default_alias)
description = wallet_dict.get("description", "")
address = wallet_dict.get("address", "")
address_index = wallet_dict.get("address_index", 0)
change_address = wallet_dict.get("change_address", "")
change_index = wallet_dict.get("change_index", 0)
keypool = wallet_dict.get("keypool", 0)
change_keypool = wallet_dict.get("change_keypool", 0)
sigs_required = wallet_dict.get("sigs_required", 1)
pending_psbts = wallet_dict.get("pending_psbts", {})
frozen_utxo = wallet_dict.get("frozen_utxo", [])
fullpath = wallet_dict.get("fullpath", default_fullpath)
last_block = wallet_dict.get("last_block", None)
wallet_dict = Wallet.parse_old_format(wallet_dict, device_manager)
try:
address_type = wallet_dict["address_type"]
recv_descriptor = wallet_dict["recv_descriptor"]
change_descriptor = wallet_dict["change_descriptor"]
keys = [Key.from_json(key_dict) for key_dict in wallet_dict["keys"]]
devices = wallet_dict["devices"]
except:
logger.error("Could not construct a Wallet object from the data provided.")
return
return cls(
name,
alias,
description,
address_type,
address,
address_index,
change_address,
change_index,
keypool,
change_keypool,
recv_descriptor,
change_descriptor,
keys,
devices,
sigs_required,
pending_psbts,
frozen_utxo,
fullpath,
device_manager,
manager,
old_format_detected=wallet_dict["old_format_detected"],
last_block=last_block,
)
def get_info(self):
try:
self.info = self.rpc.getwalletinfo()
except Exception:
self.info = {}
return self.info
def check_utxo(self):
try:
locked_utxo = self.rpc.listlockunspent()
if locked_utxo:
self.rpc.lockunspent(True, locked_utxo)
utxo = self.rpc.listunspent(0)
if locked_utxo:
self.rpc.lockunspent(False, locked_utxo)
for tx in utxo:
if [
_tx
for _tx in locked_utxo
if _tx["txid"] == tx["txid"] and _tx["vout"] == tx["vout"]
]:
tx["locked"] = True
# list only the ones we know (have descriptor for it)
utxo = [tx for tx in utxo if tx.get("desc", "")]
for tx in utxo:
tx_data = self.gettransaction(tx["txid"], 0)
tx["time"] = tx_data["time"]
tx["category"] = "send"
if "locked" not in tx:
tx["locked"] = False
try:
# get category from the descriptor - recv or change
idx = tx["desc"].split("[")[1].split("]")[0].split("/")[-2]
if idx == "0":
tx["category"] = "receive"
except:
pass
self.full_utxo = sorted(utxo, key=lambda utxo: utxo["time"], reverse=True)
except Exception as e:
logger.error(f"Failed to load utxos, {e}")
self.full_utxo = []
def getdata(self):
self.fetch_transactions()
self.check_utxo()
self.get_info()
# TODO: Should do the same for the non change address (?)
# check if address was used already
try:
value_on_address = self.rpc.getreceivedbyaddress(self.change_address, 0)
except:
# Could happen if address not in wallet (wallet was imported)
# try adding keypool
logger.info(
f"Didn't get transactions on address {self.change_address}. Refilling keypool."
)
self.keypoolrefill(0, end=self.keypool, change=False)
self.keypoolrefill(0, end=self.change_keypool, change=True)
value_on_address = 0
# if not - just return
if value_on_address > 0:
self.change_index += 1
self.getnewaddress(change=True)
@property
def utxo(self):
return [utxo for utxo in self.full_utxo if not utxo["locked"]]
@property
def json(self):
return self.to_json()
def to_json(self, for_export=False):
o = {
"name": self.name,
"alias": self.alias,
"description": self.description,
"address_type": self.address_type,
"address": self.address,
"address_index": self.address_index,
"change_address": self.change_address,
"change_index": self.change_index,
"keypool": self.keypool,
"change_keypool": self.change_keypool,
"recv_descriptor": self.recv_descriptor,
"change_descriptor": self.change_descriptor,
"keys": [key.json for key in self.keys],
"devices": [device.alias for device in self.devices],
"sigs_required": self.sigs_required,
"blockheight": self.blockheight,
}
if for_export:
o["labels"] = self.export_labels()
else:
o["pending_psbts"] = self.pending_psbts
o["frozen_utxo"] = self.frozen_utxo
o["last_block"] = self.last_block
return o
def save_to_file(self):
write_json_file(self.to_json(), self.fullpath)
self.manager.update()
def delete_files(self):
delete_file(self.fullpath)
delete_file(self.fullpath + ".bkp")
delete_file(self._addresses.path)
delete_file(self._transactions.path)
@property
def use_descriptors(self):
if not hasattr(self, "info") or self.info != {}:
self.get_info()
return "descriptors" in self.info and self.info["descriptors"] == True
@property
def is_multisig(self):
return len(self.keys) > 1
@property
def locked_amount(self):
amount = 0
for psbt in self.pending_psbts:
amount += sum(
[
utxo["witness_utxo"]["amount"]
for utxo in self.pending_psbts[psbt]["inputs"]
]
)
return amount
def delete_pending_psbt(self, txid):
try:
self.rpc.lockunspent(True, self.pending_psbts[txid]["tx"]["vin"])
except:
# UTXO was spent
pass
if txid in self.pending_psbts:
del self.pending_psbts[txid]
self.save_to_file()
def toggle_freeze_utxo(self, utxo_list):
# utxo = ["txid:vout", "txid:vout"]
for utxo in utxo_list:
if utxo in self.frozen_utxo:
try:
self.rpc.lockunspent(
True,
[{"txid": utxo.split(":")[0], "vout": int(utxo.split(":")[1])}],
)
except Exception as e:
# UTXO was spent
print(e)
pass
self.frozen_utxo.remove(utxo)
else:
try:
self.rpc.lockunspent(
False,
[{"txid": utxo.split(":")[0], "vout": int(utxo.split(":")[1])}],
)
except Exception as e:
# UTXO was spent
print(e)
pass
self.frozen_utxo.append(utxo)
self.save_to_file()
def update_pending_psbt(self, psbt, txid, raw):
if txid in self.pending_psbts:
self.pending_psbts[txid]["base64"] = psbt
decodedpsbt = self.rpc.decodepsbt(psbt)
signed_devices = self.get_signed_devices(decodedpsbt)
self.pending_psbts[txid]["devices_signed"] = [
dev.alias for dev in signed_devices
]
if "hex" in raw:
self.pending_psbts[txid]["sigs_count"] = self.sigs_required
self.pending_psbts[txid]["raw"] = raw["hex"]
else:
self.pending_psbts[txid]["sigs_count"] = len(signed_devices)
self.save_to_file()
return self.pending_psbts[txid]
else:
raise SpecterError("Can't find pending PSBT with this txid")
def save_pending_psbt(self, psbt):
self.pending_psbts[psbt["tx"]["txid"]] = psbt
try:
self.rpc.lockunspent(False, psbt["tx"]["vin"])
except:
logger.debug(
"Failed to lock UTXO for transaction, might be fine if the transaction is an RBF."
)
self.save_to_file()
def txlist(
self,
fetch_transactions=True,
validate_merkle_proofs=False,
current_blockheight=None,
):
"""Returns a list of all transactions in the wallet's CSV cache - processed with information to display in the UI in the transactions list
#Parameters:
# fetch_transactions (bool): Update the TxList CSV caching by fetching transactions from the Bitcoin RPC
# validate_merkle_proofs (bool): Return transactions with validated_blockhash
# current_blockheight (int): Current blockheight for calculating confirmations number (None will fetch the block count from the RPC)
"""
if fetch_transactions or (
self.use_descriptors
and len(
[
tx
for tx in self._transactions
if self._transactions[tx]["category"] != "send"
and not self._transactions[tx]["address"]
]
)
!= 0
):
self.fetch_transactions()
try:
_transactions = [
tx.__dict__().copy()
for tx in self._transactions.values()
if tx["ismine"]
]
transactions = sorted(
_transactions, key=lambda tx: tx["time"], reverse=True
)
transactions = [
tx
for tx in transactions
if (
not tx["conflicts"]
or max(
[
self.gettransaction(conflicting_tx, 0)["time"]
for conflicting_tx in tx["conflicts"]
]
)
< tx["time"]
)
]
if not current_blockheight:
current_blockheight = self.rpc.getblockcount()
result = []
blocks = {}
for tx in transactions:
if not tx.get("blockheight", 0):
tx["confirmations"] = 0
else:
tx["confirmations"] = current_blockheight - tx["blockheight"] + 1
# coinbase tx
if tx["category"] == "generate":
if tx["confirmations"] <= 100:
category = "immature"
if (
tx.get("confirmations") == 0
and tx.get("bip125-replaceable", "no") == "yes"
):
tx["fee"] = self.rpc.gettransaction(tx["txid"]).get("fee", 1)
if isinstance(tx["address"], str):
tx["label"] = self.getlabel(tx["address"])
elif isinstance(tx["address"], list):
tx["label"] = [self.getlabel(address) for address in tx["address"]]
else:
tx["label"] = None
# TODO: validate for unique txids only
tx["validated_blockhash"] = "" # default is assume unvalidated
if validate_merkle_proofs is True and tx["confirmations"] > 0:
proof_hex = self.rpc.gettxoutproof([tx["txid"]], tx["blockhash"])
logger.debug(
f"Attempting merkle proof validation of tx { tx['txid'] } in block { tx['blockhash'] }"
)
if is_valid_merkle_proof(
proof_hex=proof_hex,
target_tx_hex=tx["txid"],
target_block_hash_hex=tx["blockhash"],
target_merkle_root_hex=None,
):
# NOTE: this does NOT guarantee this blockhash is actually in the real Bitcoin blockchain!
# See merkletooltip.html for details
logger.debug(
f"Merkle proof of { tx['txid'] } validation success"
)
tx["validated_blockhash"] = tx["blockhash"]
else:
logger.warning(
f"Attempted merkle proof validation on {tx['txid']} but failed. This is likely a configuration error but perhaps your node is compromised! Details: {proof_hex}"
)
result.append(tx)
return result
except Exception as e:
logging.error("Exception while processing txlist: {}".format(e))
return []
def gettransaction(self, txid, blockheight=None, decode=False):
try:
tx_data = self._transactions.gettransaction(txid, blockheight)
if decode:
return decoderawtransaction(tx_data["hex"], self.manager.chain)
return tx_data
except Exception as e:
logger.warning("Could not get transaction {}, error: {}".format(txid, e))
def is_tx_purged(self, txid):
# Is tx unconfirmed and no longer in the mempool?
try:
tx = self.rpc.gettransaction(txid)
# Do this quick test first to avoid the costlier rpc call
if tx["confirmations"] > 0:
return False
return txid not in self.rpc.getrawmempool()
except Exception as e:
logger.warning("Could not check is_tx_purged {}, error: {}".format(txid, e))
def abandontransaction(self, txid):
# Sanity checks: tx must be unconfirmed and cannot be in the mempool
tx = self.rpc.gettransaction(txid)
if tx["confirmations"] != 0:
raise SpecterError("Cannot abandon a transaction that has a confirmation.")
elif txid in self.rpc.getrawmempool():
raise SpecterError(
"Cannot abandon a transaction that is still in the mempool."
)
self.rpc.abandontransaction(txid)
def rescanutxo(self, explorer=None, requests_session=None, only_tor=False):
delete_file(self._transactions.path)
self.fetch_transactions()
t = threading.Thread(
target=self._rescan_utxo_thread,
args=(
explorer,
requests_session,
only_tor,
),
)
t.start()
def export_labels(self):
return self._addresses.get_labels()
def import_labels(self, labels):
# format:
# {
# 'label1': ['address1', 'address2'],
# 'label2': ['address3', 'address4']
# }
#
for label, addresses in labels.items():
if not label:
continue
for address in addresses:
self._addresses.set_label(address, label)
def _rescan_utxo_thread(self, explorer=None, requests_session=None, only_tor=False):
# rescan utxo is pretty fast,
# so we can check large range of addresses
# and adjust keypool accordingly
args = [
"start",
[
{"desc": self.recv_descriptor, "range": max(self.keypool, 1000)},
{
"desc": self.change_descriptor,
"range": max(self.change_keypool, 1000),
},
],
]
unspents = self.rpc.scantxoutset(*args)["unspents"]
# if keypool adjustments fails - not a big deal
try:
# check derivation indexes in found unspents (last 2 indexes in [brackets])
derivations = [
tx["desc"].split("[")[1].split("]")[0].split("/")[-2:]
for tx in unspents
]
# get max derivation for change and receive branches
max_recv = max([-1] + [int(der[1]) for der in derivations if der[0] == "0"])
max_change = max(
[-1] + [int(der[1]) for der in derivations if der[0] == "1"]
)
updated = False
if max_recv >= self.address_index:
# skip to max_recv
self.address_index = max_recv
# get next
self.getnewaddress(change=False, save=False)
updated = True
while max_change >= self.change_index:
# skip to max_change
self.change_index = max_change
# get next
self.getnewaddress(change=True, save=False)
updated = True
# save only if needed
if updated:
self.save_to_file()
except Exception as e:
logger.warning(f"Failed to get derivation path from utxo transaction: {e}")
# keep working with unspents
res = self.rpc.multi([("getblockhash", tx["height"]) for tx in unspents])
block_hashes = [r["result"] for r in res]
for i, tx in enumerate(unspents):
tx["blockhash"] = block_hashes[i]
res = self.rpc.multi(
[("gettxoutproof", [tx["txid"]], tx["blockhash"]) for tx in unspents]
)
proofs = [r["result"] for r in res]
for i, tx in enumerate(unspents):
tx["proof"] = proofs[i]
res = self.rpc.multi(
[
("getrawtransaction", tx["txid"], False, tx["blockhash"])
for tx in unspents
]
)
raws = [r["result"] for r in res]
for i, tx in enumerate(unspents):
tx["raw"] = raws[i]
missing = [tx for tx in unspents if tx["raw"] is None]
existing = [tx for tx in unspents if tx["raw"] is not None]
self.rpc.multi(
[("importprunedfunds", tx["raw"], tx["proof"]) for tx in existing]
)
# handle missing transactions now
# if Tor is running, requests will be sent over Tor
if explorer is not None:
# make sure there is no trailing /
explorer = explorer.rstrip("/")
try:
# get raw transactions
raws = [
requests_session.get(f"{explorer}/api/tx/{tx['txid']}/hex").text
for tx in missing
]
# get proofs
proofs = [
requests_session.get(
f"{explorer}/api/tx/{tx['txid']}/merkleblock-proof"
).text
for tx in missing
]
# import funds
self.rpc.multi(
[
("importprunedfunds", raws[i], proofs[i])
for i in range(len(raws))
]
)
except Exception as e:
logger.warning(f"Failed to fetch data from block explorer: {e}")
# retry if using requests_session failed
if not only_tor:
try:
# get raw transactions
raws = [
requests.get(f"{explorer}/api/tx/{tx['txid']}/hex").text
for tx in missing
]
# get proofs
proofs = [
requests.get(
f"{explorer}/api/tx/{tx['txid']}/merkleblock-proof"
).text
for tx in missing
]
# import funds
self.rpc.multi(
[
("importprunedfunds", raws[i], proofs[i])
for i in range(len(raws))
]
)
except:
logger.warning(f"Failed to fetch data from block explorer: {e}")
self.fetch_transactions()
self.check_addresses()
@property
def rescan_progress(self):
"""Returns None if rescanblockchain is not launched,
value between 0 and 1 otherwise
"""
if self.info.get("scanning", False) == False:
return None
else:
return self.info["scanning"]["progress"]
@property
def blockheight(self):
self.fetch_transactions()
MAX_BLOCKHEIGHT = 999999999999 # Replace before we reach this height
first_tx = sorted(
self._transactions.values(),
key=lambda tx: tx.get("blockheight", None)
if tx.get("blockheight", None)
else MAX_BLOCKHEIGHT,
)
first_tx_blockheight = (
first_tx[0].get("blockheight", None) if first_tx else None
)
if first_tx:
if first_tx_blockheight and first_tx_blockheight - 101 > 0:
return (
first_tx_blockheight - 101
) # Give tiny margin to catch edge case of mined coins
return 481824 if self.manager.chain == "main" else 0
@property
def account_map(self):
account_map_dict = {
"label": self.name.replace("'", "_").replace('"', "_"),
"blockheight": self.blockheight,
"descriptor": self.recv_descriptor.replace("/", "\\/"),
"devices": [{"type": d.device_type, "label": d.name} for d in self.devices],
}
return json.dumps(account_map_dict)
def getnewaddress(self, change=False, save=True):
if change:
self.change_index += 1
index = self.change_index
else:
self.address_index += 1
index = self.address_index
address = self.get_address(index, change=change)
if change:
self.change_address = address
else:
self.address = address
if save:
self.save_to_file()
return address
def get_address(self, index, change=False, check_keypool=True):
if check_keypool:
pool = self.change_keypool if change else self.keypool
if pool < index + self.GAP_LIMIT:
self.keypoolrefill(pool, index + self.GAP_LIMIT, change=change)
desc = self.change_descriptor if change else self.recv_descriptor
return Descriptor.parse(desc).address(index, self.manager.chain)
def get_descriptor(self, index=None, change=False, address=None):
"""
Returns address descriptor from index, change
or from address belonging to the wallet.
"""
if address is not None:
# only ask rpc if address is not known directly
if address not in self._addresses:
return self.rpc.getaddressinfo(address).get("desc", "")
else:
a = self._addresses[address]
index = a.index
change = a.change
if index is None:
index = self.change_index if change else self.address_index
desc = self.change_descriptor if change else self.recv_descriptor
derived_desc = Descriptor.parse(desc).derive(index).serialize()
derived_desc_xpubs = (
Descriptor.parse(desc).derive(index, keep_xpubs=True).serialize()
)
return {"descriptor": derived_desc, "xpubs_descriptor": derived_desc_xpubs}
def get_address_info(self, address):
try:
return self._addresses[address]
except:
return None
def is_address_mine(self, address):
addrinfo = self.get_address_info(address)
return addrinfo and not addrinfo.is_external
def get_electrum_file(self):
""" Exports the wallet data as Electrum JSON format """
electrum_devices = [
"bitbox02",
"coldcard",
"digitalbitbox",
"keepkey",
"ledger",
"safe_t",
"trezor",