forked from etotheipi/BitcoinArmory
-
Notifications
You must be signed in to change notification settings - Fork 174
/
PyBtcWallet.py
3336 lines (2696 loc) · 136 KB
/
PyBtcWallet.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
################################################################################
# #
# Copyright (C) 2011-2015, Armory Technologies, Inc. #
# Distributed under the GNU Affero General Public License (AGPL v3) #
# See LICENSE or http://www.gnu.org/licenses/agpl.html #
# #
# Copyright (C) 2016-17, goatpig #
# Distributed under the MIT license #
# See LICENSE-MIT or https://opensource.org/licenses/MIT #
# #
##############################################################################
import os.path
import shutil
from CppBlockUtils import SecureBinaryData, KdfRomix, CryptoAES, CryptoECDSA
import CppBlockUtils as Cpp
from armoryengine.ArmoryUtils import *
from armoryengine.BinaryPacker import *
from armoryengine.BinaryUnpacker import *
from armoryengine.Timer import *
from armoryengine.Decorators import singleEntrantMethod
from armoryengine.SignerWrapper import SIGNER_DEFAULT, SIGNER_BCH, SIGNER_CPP, \
SIGNER_LEGACY, PythonSignerDirector, PythonSignerDirector_BCH
# This import is causing a circular import problem when used by findpass and promokit
# it is imported at the end of the file. Do not add it back at the begining
# from armoryengine.Transaction import *
BLOCKCHAIN_READONLY = 0
BLOCKCHAIN_READWRITE = 1
BLOCKCHAIN_DONOTUSE = 2
WLT_UPDATE_ADD = 0
WLT_UPDATE_MODIFY = 1
WLT_DATATYPE_KEYDATA = 0
WLT_DATATYPE_ADDRCOMMENT = 1
WLT_DATATYPE_TXCOMMENT = 2
WLT_DATATYPE_OPEVAL = 3
WLT_DATATYPE_DELETED = 4
DEFAULT_COMPUTE_TIME_TARGET = 0.25
DEFAULT_MAXMEM_LIMIT = 32*1024*1024
PYROOTPKCCVER = 1 # Current version of root pub key/chain code backup format
PYROOTPKCCVERMASK = 0x7F
PYROOTPKCCSIGNMASK = 0x80
# Only works on PyBtcWallet
# If first arg is not PyBtcWallet call the function as if it was
# not decorated, it should throw whatever error or do whatever it would
# do withouth this decorator. This decorator does nothing if applied to
# the methods of any other class
def CheckWalletRegistration(func):
def inner(*args, **kwargs):
if len(args)>0 and isinstance(args[0],PyBtcWallet):
if args[0].isRegistered():
return func(*args, **kwargs)
elif 'doRegister' in kwargs and kwargs['doRegister'] == False:
return func(*args, **kwargs)
else:
raise WalletUnregisteredError
else:
return func(*args, **kwargs)
return inner
def buildWltFileName(uniqueIDB58):
return 'armory_%s_.wallet' % uniqueIDB58
class PyBtcWallet(object):
"""
This class encapsulates all the concepts and variables in a "wallet",
and maintains the passphrase protection, key stretching, encryption,
etc, required to maintain the wallet. This class also includes the
file I/O methods for storing and loading wallets.
***NOTE: I have ONLY implemented deterministic wallets, using ECDSA
Diffie-Hellman shared-secret crypto operations. This allows
one to actually determine the next PUBLIC KEY in the address
chain without actually having access to the private keys.
This makes it possible to synchronize online-offline computers
once and never again.
You can import random keys into your wallet, but if it is
encrypted, you will have to supply a passphrase to make sure
it can be encrypted as well.
Presumably, wallets will be used for one of three purposes:
(1) Spend money and receive payments
(2) Watching-only wallets - have the private keys, just not on this computer
(3) May be watching *other* people's addrs. There's a variety of reasons
we might want to watch other peoples' addresses, but most them are not
relevant to a "basic" BTC user. Nonetheless it should be supported to
watch money without considering it part of our own assets
This class is included in the combined-python-cpp module, because we really
need to maintain a persistent Cpp.BtcWallet if this class is to be useful
(we don't want to have to rescan the entire blockchain every time we do any
wallet operations).
The file format was designed from the outset with lots of unused space to
allow for expansion without having to redefine the file format and break
previous wallets. Luckily, wallet information is cheap, so we don't have
to stress too much about saving space (100,000 addresses should take 15 MB)
This file is NOT for storing Tx-related information. I want this file to
be the minimal amount of information you need to secure and backup your
entire wallet. Tx information can always be recovered from examining the
blockchain... your private keys cannot be.
We track version numbers, just in case. We start with 1.0
Version 1.0:
---
fileID -- (8) '\xbaWALLET\x00' for wallet files
version -- (4) getVersionInt(PYBTCWALLET_VERSION)
magic bytes -- (4) defines the blockchain for this wallet (BTC, NMC)
wlt flags -- (8) 64 bits/flags representing info about wallet
binUniqueID -- (6) first 5 bytes of first address in wallet
(rootAddr25Bytes[:5][::-1]), reversed
This is not intended to look like the root addr str
and is reversed to avoid having all wallet IDs start
with the same characters (since the network byte is front)
create date -- (8) unix timestamp of when this wallet was created
(actually, the earliest creation date of any addr
in this wallet -- in the case of importing addr
data). This is used to improve blockchain searching
Short Name -- (32) Null-terminated user-supplied short name for wlt
Long Name -- (256) Null-terminated user-supplied description for wlt
Highest Used-- (8) The chain index of the highest used address
---
Crypto/KDF -- (512) information identifying the types and parameters
of encryption used to secure wallet, and key
stretching used to secure your passphrase.
Includes salt. (the breakdown of this field will
be described separately)
KeyGenerator-- (237) The base address for a determinstic wallet.
Just a serialized PyBtcAddress object.
---
UNUSED -- (1024) unused space for future expansion of wallet file
---
Remainder of file is for key storage and various other things. Each
"entry" will start with a 4-byte code identifying the entry type, then
20 bytes identifying what address the data is for, and finally then
the subsequent data . So far, I have three types of entries that can
be included:
\x01 -- Address/Key data (as of PyBtcAddress version 1.0, 237 bytes)
\x02 -- Address comments (variable-width field)
\x03 -- Address comments (variable-width field)
\x04 -- OP_EVAL subscript (when this is enabled, in the future)
Please see PyBtcAddress for information on how key data is serialized.
Comments (\x02) are var-width, and if a comment is changed to
something longer than the existing one, we'll just blank out the old
one and append a new one to the end of the file. It looks like
02000000 01 <Addr> 4f This comment is enabled (01) with 4f characters
For file syncing, we protect against corrupted wallets by doing atomic
operations before even telling the user that new data has been added.
We do this by copying the wallet file, and creating a walletUpdateFailed
file. We then modify the original, verify its integrity, and then delete
the walletUpdateFailed file. Then we create a backupUpdateFailed flag,
do the identical update on the backup file, and delete the failed flag.
This guaranatees that no matter which nanosecond the power goes out,
there will be an uncorrupted wallet and we know which one it is.
We never let the user see any data until the atomic write-to-file operation
has completed
Additionally, we implement key locking and unlocking, with timeout. These
key locking features are only DEFINED here, not actually enforced (because
this is a library, not an application). You can set the default/temporary
time that the KDF key is maintained in memory after the passphrase is
entered, and this class will keep track of when the wallet should be next
locked. It is up to the application to check whether the current time
exceeds the lock time. This will probably be done in a kind of heartbeat
method, which checks every few seconds for all sorts of things -- including
wallet locking.
"""
#############################################################################
def __init__(self):
self.fileTypeStr = '\xbaWALLET\x00'
self.magicBytes = MAGIC_BYTES
self.version = PYBTCWALLET_VERSION # (Major, Minor, Minor++, even-more-minor)
self.eofByte = 0
self.cppWallet = None # Mirror of PyBtcWallet in C++ object
self.cppInfo = {} # Extra info about each address to help sync
self.watchingOnly = False
self.wltCreateDate = 0
# Three dictionaries hold all data
self.addrMap = {} # maps 20-byte addresses to PyBtcAddress objects
self.commentsMap = {} # maps 20-byte addresses to user-created comments
self.commentLocs = {} # map comment keys to wallet file locations
self.opevalMap = {} # maps 20-byte addresses to OP_EVAL data (future)
self.labelName = ''
self.labelDescr = ''
self.linearAddr160List = []
self.chainIndexMap = {}
self.txAddrMap = {} # cache for getting tx-labels based on addr search
if USE_TESTNET or USE_REGTEST:
self.addrPoolSize = 10 # this makes debugging so much easier!
else:
self.addrPoolSize = CLI_OPTIONS.keypool
self.importList = []
# For file sync features
self.walletPath = ''
self.doBlockchainSync = BLOCKCHAIN_READONLY
self.lastSyncBlockNum = 0
# Private key encryption details
self.useEncryption = False
self.kdf = None
self.crypto = None
self.kdfKey = None
self.defaultKeyLifetime = 10 # seconds after unlock, that key is discarded
self.lockWalletAtTime = 0 # seconds after unlock, that key is discarded
self.isLocked = False
self.testedComputeTime=None
# Deterministic wallet, need a root key. Though we can still import keys.
# The unique ID contains the network byte (id[-1]) but is not intended to
# resemble the address of the root key
self.uniqueIDBin = ''
self.uniqueIDB58 = '' # Base58 version of reversed-uniqueIDBin
self.lastComputedChainAddr160 = ''
self.lastComputedChainIndex = 0
self.highestUsedChainIndex = 0
# All PyBtcAddress serializations are exact same size, figure it out now
self.pybtcaddrSize = len(PyBtcAddress().serialize())
# Finally, a bunch of offsets that tell us where data is stored in the
# file: this can be generated automatically on unpacking (meaning it
# doesn't require manually updating offsets if I change the format), and
# will save us a couple lines of code later, when we need to update things
self.offsetWltFlags = -1
self.offsetLabelName = -1
self.offsetLabelDescr = -1
self.offsetTopUsed = -1
self.offsetRootAddr = -1
self.offsetKdfParams = -1
self.offsetCrypto = -1
# These flags are ONLY for unit-testing the walletFileSafeUpdate function
self.interruptTest1 = False
self.interruptTest2 = False
self.interruptTest3 = False
#flags the wallet if it has off chain imports (from a consistency repair)
self.hasNegativeImports = False
#To enable/disable wallet row in wallet table model
self.isEnabled = True
self.mutex = threading.Lock()
#list of callables and their args to perform after a wallet
#has been scanned. Entries are order as follows:
#[[method1, [arg1, ar2, arg3]], [method2, [arg1, arg2]]]
#list is cleared after each scan.
self.actionsToTakeAfterScan = []
self.balance_spendable = 0
self.balance_unconfirmed = 0
self.balance_full = 0
self.txnCount = 0
self.addrTxnCountDict = {}
self.addrBalanceDict = {}
#############################################################################
def registerWallet(self, isNew=False):
if self.cppWallet == None:
raise Exception('invalid cppWallet object')
#this returns a copy of a BtcWallet C++ object. This object is
#instantiated at registration and is unique for the BDV object, so we
#should only ever set the cppWallet member here
try:
self.cppWallet.registerWithBDV(isNew)
except:
pass
#############################################################################
def isWltSigningAnyLockbox(self, lockboxList):
for lockbox in lockboxList:
for addr160 in lockbox.a160List:
if self.addrMap.has_key(addr160):
return True
return False
#############################################################################
def getWalletVersion(self):
return (getVersionInt(self.version), getVersionString(self.version))
#############################################################################
def getTimeRangeForAddress(self, addr160):
if not self.addrMap.has_key(addr160):
return None
else:
return self.addrMap[addr160].getTimeRange()
#############################################################################
def getBlockRangeForAddress(self, addr160):
if not self.addrMap.has_key(addr160):
return None
else:
return self.addrMap[addr160].getBlockRange()
#############################################################################
def setBlockchainSyncFlag(self, syncYes=True):
self.doBlockchainSync = syncYes
#############################################################################
def getCommentForAddrBookEntry(self, abe):
comment = self.getComment(abe.getAddr160())
if len(comment)>0:
return comment
# SWIG BUG!
# http://sourceforge.net/tracker/?func=detail&atid=101645&aid=3403085&group_id=1645
# Apparently, using the -threads option when compiling the swig module
# causes the "for i in vector<...>:" mechanic to sometimes throw seg faults!
# For this reason, this method was replaced with the one below:
for regTx in abe.getTxList():
comment = self.getComment(regTx.getTxHash())
if len(comment)>0:
return comment
return ''
#############################################################################
def getCommentForTxList(self, a160, txhashList):
comment = self.getComment(a160)
if len(comment)>0:
return comment
for txHash in txhashList:
comment = self.getComment(txHash)
if len(comment)>0:
return comment
return ''
#############################################################################
@CheckWalletRegistration
def printAddressBook(self):
addrbook = self.cppWallet.createAddressBook()
for abe in addrbook:
print hash160_to_addrStr(abe.getAddr160()),
txlist = abe.getTxList()
print len(txlist)
for rtx in txlist:
print '\t', binary_to_hex(rtx.getTxHash(), BIGENDIAN)
#############################################################################
def hasAnyImported(self):
for a160,addr in self.addrMap.iteritems():
if addr.chainIndex == -2:
return True
return False
def isRegistered(self):
return not self.cppWallet == None
#############################################################################
# The IGNOREZC args on the get*Balance calls determine whether unconfirmed
# change (sent-to-self) will be considered spendable or unconfirmed. This
# was added after the malleability issues cropped up in Feb 2014. Zero-conf
# change was always deprioritized, but using --nospendzeroconfchange makes
# it totally unspendable
def getBalance(self, balType="Spendable"):
if balType.lower() in ('spendable','spend'):
return self.balance_spendable
#return self.cppWallet.getSpendableBalance(topBlockHeight, IGNOREZC)
elif balType.lower() in ('unconfirmed','unconf'):
#return self.cppWallet.getUnconfirmedBalance(topBlockHeight, IGNOREZC)
return self.balance_unconfirmed
elif balType.lower() in ('total','ultimate','unspent','full'):
#return self.cppWallet.getFullBalance()
return self.balance_full
else:
raise TypeError('Unknown balance type! "' + balType + '"')
#############################################################################
def getTxnCount(self):
return self.txnCount
#############################################################################
def getBalancesAndCountFromDB(self):
if self.cppWallet != None and TheBDM.getState() is BDM_BLOCKCHAIN_READY:
topBlockHeight = TheBDM.getTopBlockHeight()
balanceVector = self.cppWallet.getBalancesAndCount(\
topBlockHeight, IGNOREZC)
self.balance_full = balanceVector[0]
self.balance_spendable = balanceVector[1]
self.balance_unconfirmed = balanceVector[2]
self.txnCount = balanceVector[3]
#############################################################################
@CheckWalletRegistration
def getAddrBalance(self, addr160, balType="Spendable", topBlockHeight=UINT32_MAX):
if not self.hasAddr(addr160):
return -1
else:
try:
scraddr = Hash160ToScrAddr(addr160)
addrBalances = self.addrBalanceDict[scraddr]
except:
return 0
if balType.lower() in ('spendable','spend'):
return addrBalances[1]
elif balType.lower() in ('unconfirmed','unconf'):
return addrBalances[2]
elif balType.lower() in ('ultimate','unspent','full'):
return addrBalances[0]
else:
raise TypeError('Unknown balance type!')
#############################################################################
@CheckWalletRegistration
def getTxLedger(self, ledgType='Full'):
"""
Gets the ledger entries for the entire wallet, from C++/SWIG data structs
"""
ledgBlkChain = self.getHistoryPage(0)
ledg = []
ledg.extend(ledgBlkChain)
return ledg
#############################################################################
@CheckWalletRegistration
def getUTXOListForSpendVal(self, valToSpend = 2**64 - 1):
""" Returns UnspentTxOut/C++ objects
returns a set of unspent TxOuts to cover for the value to spend
"""
if not self.doBlockchainSync==BLOCKCHAIN_DONOTUSE:
from CoinSelection import PyUnspentTxOut
utxos = self.cppWallet.getSpendableTxOutListForValue(valToSpend)
utxoList = []
for i in range(len(utxos)):
utxoList.append(PyUnspentTxOut().createFromCppUtxo(utxos[i]))
return utxoList
else:
LOGERROR('***Blockchain is not available for accessing wallet-tx data')
return []
#############################################################################
@CheckWalletRegistration
def getFullUTXOList(self):
""" Returns UnspentTxOut/C++ objects
DO NOT USE THIS CALL UNLESS NECESSARY.
This call returns *ALL* of the wallet's UTXOs. If your intent is to get
UTXOs to spend coins, use getUTXOListForSpendVal and pass the amount you
want to spend as the argument.
If you want to get UTXOs for browsing the history, use
getUTXOListForBlockRange with the top and bottom block of the desired range
"""
#return full set of unspent TxOuts
if not self.doBlockchainSync==BLOCKCHAIN_DONOTUSE:
#calling this with no value argument will return the full UTXO list
from CoinSelection import PyUnspentTxOut
utxos = self.cppWallet.getSpendableTxOutListForValue()
utxoList = []
for i in range(len(utxos)):
utxoList.append(PyUnspentTxOut().createFromCppUtxo(utxos[i]))
return utxoList
else:
LOGERROR('***Blockchain is not available for accessing wallet-tx data')
return []
#############################################################################
@CheckWalletRegistration
def getZCUTXOList(self):
#return full set of unspent ZC outputs
if not self.doBlockchainSync==BLOCKCHAIN_DONOTUSE:
from CoinSelection import PyUnspentTxOut
utxos = self.cppWallet.getSpendableZCList()
utxoList = []
for i in range(len(utxos)):
utxoList.append(PyUnspentTxOut().createFromCppUtxo(utxos[i]))
return utxoList
else:
LOGERROR('***Blockchain is not available for accessing wallet-tx data')
return []
#############################################################################
@CheckWalletRegistration
def getRBFTxOutList(self):
#return full set of unspent ZC outputs
if not self.doBlockchainSync==BLOCKCHAIN_DONOTUSE:
from CoinSelection import PyUnspentTxOut
utxos = self.cppWallet.getRBFTxOutList()
utxoList = []
for i in range(len(utxos)):
utxoList.append(PyUnspentTxOut().createFromCppUtxo(utxos[i]))
return utxoList
else:
LOGERROR('***Blockchain is not available for accessing wallet-tx data')
return []
#############################################################################
@CheckWalletRegistration
def getUTXOListForBlockRange(self, startBlock, endBlock):
""" Returns UnspentTxOut/C++ objects
returns all unspent TxOuts in the block range
"""
raise NotImplemented
#############################################################################
@CheckWalletRegistration
def getAddrTxOutList(self, addr160, txType='Spendable'):
"""
deprecated call, use getFullUTXOList instead
"""
raise NotImplemented
""" Returns UnspentTxOut/C++ objects """
if not self.doBlockchainSync==BLOCKCHAIN_DONOTUSE:
topBlockHeight = TheBDM.getTopBlockHeight()
# Removed this line of code because it's part of the old BDM paradigm.
# Leaving this comment here in case it needs to be replaced by anything
# self.syncWithBlockchainLite()
scrAddrStr = Hash160ToScrAddr(addr160)
cppAddr = self.cppWallet.getScrAddrObjByKey(scrAddrStr)
if txType.lower() in ('spend', 'spendable'):
return cppAddr.getSpendableTxOutList(IGNOREZC);
elif txType.lower() in ('full', 'all', 'unspent', 'ultimate'):
return cppAddr.getFullTxOutList(topBlockHeight, IGNOREZC);
else:
raise TypeError('Unknown TxOutList type! ' + txType)
else:
LOGERROR('***Blockchain is not available for accessing wallet-tx data')
return []
#############################################################################
def getAddrByHash160(self, addr160):
return (None if not self.hasAddr(addr160) else self.addrMap[addr160])
#############################################################################
def hasScrAddr(self, scrAddr):
"""
Wallets currently only hold P2PKH scraddrs, so if it's not that, False
"""
if not scrAddr[0] == ADDRBYTE or not len(scrAddr)==21:
try:
return self.cppWallet.hasScrAddr(scrAddr)
except:
return False
# For P2PKH scraddrs, the first byte is prefix, next 20 bytes is addr160
return self.hasAddr(scrAddr[1:])
#############################################################################
def hasAddr(self, addrData):
if isinstance(addrData, str):
if len(addrData) == 20:
return self.addrMap.has_key(addrData)
elif isLikelyDataType(addrData)==DATATYPE.Base58:
return self.addrMap.has_key(addrStr_to_hash160(addrData)[1])
else:
return False
elif isinstance(addrData, PyBtcAddress):
return self.addrMap.has_key(addrData.getAddr160())
else:
return False
#############################################################################
def setDefaultKeyLifetime(self, newlifetime):
""" Set a new default lifetime for holding the unlock key. Min 2 sec """
self.defaultKeyLifetime = max(newlifetime, 2)
#############################################################################
def checkWalletLockTimeout(self):
if not self.isLocked and self.kdfKey and RightNow()>self.lockWalletAtTime:
self.lock()
if self.kdfKey:
self.kdfKey.destroy()
self.kdfKey = None
if self.useEncryption:
self.isLocked = True
#############################################################################
@CheckWalletRegistration
def lockTxOutsOnNewTx(self, pytxObj):
for txin in pytxObj.inputs:
self.cppWallet.lockTxOutSwig(txin.outpoint.txHash, \
txin.outpoint.txOutIndex)
#############################################################################
# THIS WAS CREATED ORIGINALLY TO SUPPORT BITSAFE INTEGRATION INTO ARMORY
# But it's also a good first step into general BIP 32 support
def getChildExtPubFromRoot(self, i):
root = self.addrMap['ROOT']
ekey = ExtendedKey().CreateFromPublic(root.binPublicKey65, root.chaincode)
newKey = HDWalletCrypto().ChildKeyDeriv(ekey, i)
newKey.setIndex(i)
return newKey
#newAddr = PyBtcAddress().createFromExtendedPublicKey(newKey)
#############################################################################
#def createFromExtendedPublicKey(self, ekey):
#pub65 = ekey.getPub()
#chain = ekey.getChain()
#newAddr = self.createFromPublicKeyData(pub65, chain)
#newAddr.chainIndex = newAddr.getIndex()
#return newAddr
#############################################################################
#def deriveChildPublicKey(self, i):
#newKey = HDWalletCrypto().ChildKeyDeriv(self.getExtendedPublicKey(), i)
#newAddr = PyBtcAddress().createFromExtendedPublicKey(newKey)
#############################################################################
# Copy the wallet file to backup
def backupWalletFile(self, backupPath = None):
'''Function that attempts to make a backup copy of the wallet to the file
in a given path and returns whether or not the copy succeeded.'''
# Assume upfront that the copy will work.
retVal = True
walletFileBackup = self.getWalletPath('backup') if backupPath == None \
else backupPath
try:
shutil.copy(self.walletPath, walletFileBackup)
except IOError, errReason:
LOGERROR('Unable to copy file %s' % backupPath)
LOGERROR('Reason for copy failure: %s' % errReason)
retVal = False
return retVal
#############################################################################
# THIS WAS CREATED ORIGINALLY TO SUPPORT BITSAFE INTEGRATION INTO ARMORY
# But it's also a good first step into general BIP 32 support
def createWalletFromMasterPubKey(self, masterHex, \
isActuallyNew=True, \
doRegisterWithBDM=True):
# This function eats hex inputs. (Not sure why I chose to do that.)
# B/c we have a known starting pt. for keys, use that instead of trying to
# index off a chaincode value, as the value could be in the key.
p0 = masterHex.index('4104') + 1
pubkey = SecureBinaryData(hex_to_binary(masterHex[p0:p0+130]))
c0 = masterHex.index('4104') + 66
chain = SecureBinaryData(hex_to_binary(masterHex[c0:c0+64]))
# Create the root address object
rootAddr = PyBtcAddress().createFromPublicKeyData( pubkey )
rootAddr.markAsRootAddr(chain)
self.addrMap['ROOT'] = rootAddr
ekey = self.getChildExtPubFromRoot(0)
firstAddr = PyBtcAddress().createFromPublicKeyData(ekey.getPub())
firstAddr.chaincode = ekey.getChain()
firstAddr.chainIndex = 0
first160 = firstAddr.getAddr160()
# Update wallet object with the new data
# NEW IN WALLET VERSION 1.35: unique ID is now based on
# the first chained address: this guarantees that the unique ID
# is based not only on the private key, BUT ALSO THE CHAIN CODE
self.useEncryption = False
self.addrMap[firstAddr.getAddr160()] = firstAddr
self.uniqueIDBin = (ADDRBYTE + firstAddr.getAddr160()[:5])[::-1]
self.uniqueIDB58 = binary_to_base58(self.uniqueIDBin)
self.labelName = 'BitSafe Demo Wallet'
self.labelDescr = 'We\'ll be lucky if this works!'
self.lastComputedChainAddr160 = first160
self.lastComputedChainIndex = firstAddr.chainIndex
self.highestUsedChainIndex = firstAddr.chainIndex-1
self.wltCreateDate = long(RightNow())
self.linearAddr160List = [first160]
self.chainIndexMap[firstAddr.chainIndex] = first160
self.watchingOnly = True
# We don't have to worry about atomic file operations when
# creating the wallet: so we just do it naively here.
newWalletFilePath = os.path.join(ARMORY_HOME_DIR, 'bitsafe_demo_%s.wallet' % self.uniqueIDB58)
self.walletPath = newWalletFilePath
if not newWalletFilePath:
shortName = self.labelName .replace(' ','_')
# This was really only needed when we were putting name in filename
#for c in ',?;:\'"?/\\=+-|[]{}<>':
#shortName = shortName.replace(c,'_')
newName = buildWltFileName(self.uniqueIDB58)
self.walletPath = os.path.join(ARMORY_HOME_DIR, newName)
LOGINFO(' New wallet will be written to: %s', self.walletPath)
newfile = open(self.walletPath, 'wb')
fileData = BinaryPacker()
# packHeader method writes KDF params and root address
headerBytes = self.packHeader(fileData)
# We make sure we have byte locations of the two addresses, to start
self.addrMap[first160].walletByteLoc = headerBytes + 21
fileData.put(BINARY_CHUNK, '\x00' + first160 + firstAddr.serialize())
# Store the current localtime and blocknumber. Block number is always
# accurate if available, but time may not be exactly right. Whenever
# basing anything on time, please assume that it is up to one day off!
time0,blk0 = getCurrTimeAndBlock() if isActuallyNew else (0,0)
# Don't forget to sync the C++ wallet object
newfile.write(fileData.getBinaryString())
newfile.flush()
os.fsync(newfile.fileno())
newfile.close()
walletFileBackup = self.getWalletPath('backup')
shutil.copy(self.walletPath, walletFileBackup)
# Let's fill the address pool while we are unlocked
# It will get a lot more expensive if we do it on the next unlock
self.fillAddressPool(self.addrPoolSize, isActuallyNew=isActuallyNew, doRegister=doRegisterWithBDM)
return self
#############################################################################
def createNewWalletFromPKCC(self, plainPubKey, chaincode, newWalletFilePath=None, \
isActuallyNew=False, doRegisterWithBDM=True, \
skipBackupFile=False):
"""
This method will create a new wallet based on a root public key, chain
code and wallet ID.
"""
LOGINFO('***Creating watching-only wallet from a public key & chain code')
# Prep for C++ usage, then create the root address object and first public
# address and its Hash160.
plainPubKey = SecureBinaryData(plainPubKey)
chaincode = SecureBinaryData(chaincode)
rootAddr = PyBtcAddress().createFromPublicKeyData(plainPubKey)
rootAddr.markAsRootAddr(chaincode)
firstAddr = rootAddr.extendAddressChain()
first160 = firstAddr.getAddr160()
# Update wallet object with the new data.
# NEW IN WALLET VERSION 1.35: unique ID is now based on the first chained
# address. This guarantees that the unique ID is based not only on the
# private key, BUT ALSO THE CHAIN CODE.
self.useEncryption = False
self.watchingOnly = True
self.wltCreateDate = long(RightNow())
self.addrMap['ROOT'] = rootAddr
self.addrMap[firstAddr.getAddr160()] = firstAddr
self.uniqueIDBin = (ADDRBYTE + firstAddr.getAddr160()[:5])[::-1]
self.uniqueIDB58 = binary_to_base58(self.uniqueIDBin)
self.labelName = (self.uniqueIDB58 + ' (Watch)')[:32]
self.labelDescr = (self.uniqueIDB58 + ' (Watching-only copy)')[:256]
self.lastComputedChainAddr160 = first160
self.lastComputedChainIndex = firstAddr.chainIndex
self.highestUsedChainIndex = firstAddr.chainIndex-1
self.linearAddr160List = [first160]
self.chainIndexMap[firstAddr.chainIndex] = first160
# We don't have to worry about atomic file operations when creating the
# wallet, so we just do it here, naively.
self.walletPath = newWalletFilePath
if not newWalletFilePath:
shortName = self.labelName .replace(' ','_')
# This was really only needed when we were putting name in filename
#for c in ',?;:\'"?/\\=+-|[]{}<>':
#shortName = shortName.replace(c,'_')
newName = 'armory_%s_WatchOnly.wallet' % self.uniqueIDB58
self.walletPath = os.path.join(ARMORY_HOME_DIR, newName)
# Start writing the wallet.
LOGINFO(' New wallet will be written to: %s', self.walletPath)
newfile = open(self.walletPath, 'wb')
fileData = BinaryPacker()
# packHeader method writes KDF params and root address
headerBytes = self.packHeader(fileData)
# We make sure we have byte locations of the two addresses, to start
self.addrMap[first160].walletByteLoc = headerBytes + 21
fileData.put(BINARY_CHUNK, '\x00' + first160 + firstAddr.serialize())
# Store the current localtime and blocknumber. Block number is always
# accurate if available, but time may not be exactly right. Whenever
# basing anything on time, please assume that it is up to one day off!
time0,blk0 = getCurrTimeAndBlock() if isActuallyNew else (0,0)
# Write the actual wallet file and close it. Create a backup if necessary.
newfile.write(fileData.getBinaryString())
newfile.close()
if not skipBackupFile:
walletFileBackup = self.getWalletPath('backup')
shutil.copy(self.walletPath, walletFileBackup)
# Let's fill the address pool while we are unlocked. It will get a lot
# more expensive if we do it on the next unlock.
self.fillAddressPool(self.addrPoolSize, isActuallyNew=isActuallyNew, doRegister=doRegisterWithBDM)
return self
#############################################################################
def createNewWallet(self, newWalletFilePath=None, \
plainRootKey=None, chaincode=None, \
withEncrypt=True, IV=None, securePassphrase=None, \
kdfTargSec=DEFAULT_COMPUTE_TIME_TARGET, \
kdfMaxMem=DEFAULT_MAXMEM_LIMIT, \
shortLabel='', longLabel='', isActuallyNew=True, \
doRegisterWithBDM=True, skipBackupFile=False, \
extraEntropy=None, Progress=emptyFunc, \
armoryHomeDir = ARMORY_HOME_DIR):
"""
This method will create a new wallet, using as much customizability
as you want. You can enable encryption, and set the target params
of the key-derivation function (compute-time and max memory usage).
The KDF parameters will be experimentally determined to be as hard
as possible for your computer within the specified time target
(default, 0.25s). It will aim for maximizing memory usage and using
only 1 or 2 iterations of it, but this can be changed by scaling
down the kdfMaxMem parameter (default 32 MB).
If you use encryption, don't forget to supply a 32-byte passphrase,
created via SecureBinaryData(pythonStr). This method will apply
the passphrase so that the wallet is "born" encrypted.
The field plainRootKey could be used to recover a written backup
of a wallet, since all addresses are deterministically computed
from the root address. This obviously won't reocver any imported
keys, but does mean that you can recover your ENTIRE WALLET from
only those 32 plaintext bytes AND the 32-byte chaincode.
We skip the atomic file operations since we don't even have
a wallet file yet to safely update.
DO NOT CALL THIS FROM BDM METHOD. IT MAY DEADLOCK.
"""
if securePassphrase:
securePassphrase = SecureBinaryData(securePassphrase)
if plainRootKey:
plainRootKey = SecureBinaryData(plainRootKey)
if chaincode:
chaincode = SecureBinaryData(chaincode)
if withEncrypt and not securePassphrase:
raise EncryptionError('Cannot create encrypted wallet without passphrase')
LOGINFO('***Creating new deterministic wallet')
# Set up the KDF
if not withEncrypt:
self.kdfKey = None
else:
LOGINFO('(with encryption)')
self.kdf = KdfRomix()
LOGINFO('Target (time,RAM)=(%0.3f,%d)', kdfTargSec, kdfMaxMem)
(mem,niter,salt) = self.computeSystemSpecificKdfParams( \
kdfTargSec, kdfMaxMem)
self.kdf.usePrecomputedKdfParams(mem, niter, salt)
self.kdfKey = self.kdf.DeriveKey(securePassphrase)
if not plainRootKey:
# TODO: We should find a source for injecting extra entropy
# At least, Crypto++ grabs from a few different sources, itself
if not extraEntropy:
extraEntropy = SecureBinaryData(0)
plainRootKey = SecureBinaryData().GenerateRandom(32, extraEntropy)
if not chaincode:
#chaincode = SecureBinaryData().GenerateRandom(32)
# For wallet 1.35a, derive chaincode deterministically from root key
# The root key already has 256 bits of entropy which is excessive,
# anyway. And my original reason for having the chaincode random is
# no longer valid.
chaincode = DeriveChaincodeFromRootKey(plainRootKey)
# Create the root address object
rootAddr = PyBtcAddress().createFromPlainKeyData( \
plainRootKey, \
IV16=IV, \
willBeEncr=withEncrypt, \
generateIVIfNecessary=True)
rootAddr.markAsRootAddr(chaincode)
# This does nothing if no encryption
rootAddr.lock(self.kdfKey)
rootAddr.unlock(self.kdfKey)
firstAddr = rootAddr.extendAddressChain(self.kdfKey)
first160 = firstAddr.getAddr160()
# Update wallet object with the new data
# NEW IN WALLET VERSION 1.35: unique ID is now based on
# the first chained address: this guarantees that the unique ID
# is based not only on the private key, BUT ALSO THE CHAIN CODE
self.useEncryption = withEncrypt
self.addrMap['ROOT'] = rootAddr
self.addrMap[firstAddr.getAddr160()] = firstAddr
self.uniqueIDBin = (ADDRBYTE + firstAddr.getAddr160()[:5])[::-1]
self.uniqueIDB58 = binary_to_base58(self.uniqueIDBin)
self.labelName = shortLabel[:32] # aka "Wallet Name"
self.labelDescr = longLabel[:256] # aka "Description"
self.lastComputedChainAddr160 = first160
self.lastComputedChainIndex = firstAddr.chainIndex
self.highestUsedChainIndex = firstAddr.chainIndex-1
self.wltCreateDate = long(RightNow())
self.linearAddr160List = [first160]
self.chainIndexMap[firstAddr.chainIndex] = first160
# We don't have to worry about atomic file operations when
# creating the wallet: so we just do it naively here.
self.walletPath = newWalletFilePath
if not newWalletFilePath:
shortName = self.labelName .replace(' ','_')
# This was really only needed when we were putting name in filename
#for c in ',?;:\'"?/\\=+-|[]{}<>':
#shortName = shortName.replace(c,'_')
newName = buildWltFileName(self.uniqueIDB58)
self.walletPath = os.path.join(armoryHomeDir, newName)
LOGINFO(' New wallet will be written to: %s', self.walletPath)
newfile = open(self.walletPath, 'wb')
fileData = BinaryPacker()
# packHeader method writes KDF params and root address
headerBytes = self.packHeader(fileData)
# We make sure we have byte locations of the two addresses, to start
self.addrMap[first160].walletByteLoc = headerBytes + 21
fileData.put(BINARY_CHUNK, '\x00' + first160 + firstAddr.serialize())
# Store the current localtime and blocknumber. Block number is always
# accurate if available, but time may not be exactly right. Whenever
# basing anything on time, please assume that it is up to one day off!
time0,blk0 = getCurrTimeAndBlock() if isActuallyNew else (0,0)
newfile.write(fileData.getBinaryString())
newfile.close()
if not skipBackupFile:
walletFileBackup = self.getWalletPath('backup')
shutil.copy(self.walletPath, walletFileBackup)
# Lock/unlock to make sure encrypted keys are computed and written to file
if self.useEncryption:
self.unlock(secureKdfOutput=self.kdfKey, Progress=Progress)
# Let's fill the address pool while we are unlocked
# It will get a lot more expensive if we do it on the next unlock
self.fillAddressPool(self.addrPoolSize, isActuallyNew=isActuallyNew,
Progress=Progress, doRegister=doRegisterWithBDM)
if self.useEncryption:
self.lock()
return self
#############################################################################
def advanceHighestIndex(self, ct=1, isNew=False):