-
Notifications
You must be signed in to change notification settings - Fork 608
/
ArmoryUtils.py
3636 lines (2991 loc) · 125 KB
/
ArmoryUtils.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-2014, Armory Technologies, Inc.
# Distributed under the GNU Affero General Public License (AGPL v3)
# See LICENSE or http://www.gnu.org/licenses/agpl.html
#
################################################################################
#
# Project: Armory
# Author: Alan Reiner
# Website: www.bitcoinarmory.com
# Orig Date: 20 November, 2011
#
################################################################################
import ast
from datetime import datetime
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import hashlib
import inspect
import locale
import logging
import math
import multiprocessing
import optparse
import os
import platform
import random
import signal
import smtplib
from struct import pack, unpack
from itertools import izip
#from subprocess import PIPE
import sys
import threading
import time
import traceback
import shutil
import base64
import socket
#from psutil import Popen
import psutil
from CppBlockUtils import KdfRomix, CryptoAES
from qrcodenative import QRCode, QRErrorCorrectLevel
# Version Numbers
BTCARMORY_VERSION = (0, 92, 3, 0) # (Major, Minor, Bugfix, AutoIncrement)
PYBTCWALLET_VERSION = (1, 35, 0, 0) # (Major, Minor, Bugfix, AutoIncrement)
ARMORY_DONATION_ADDR = '1ArmoryXcfq7TnCSuZa9fQjRYwJ4bkRKfv'
ARMORY_DONATION_PUBKEY = ( '04'
'11d14f8498d11c33d08b0cd7b312fb2e6fc9aebd479f8e9ab62b5333b2c395c5'
'f7437cab5633b5894c4a5c2132716bc36b7571cbe492a7222442b75df75b9a84')
ARMORY_INFO_SIGN_ADDR = '1NWvhByxfTXPYNT4zMBmEY3VL8QJQtQoei'
ARMORY_INFO_SIGN_PUBLICKEY = ('04'
'af4abc4b24ef57547dd13a1110e331645f2ad2b99dfe1189abb40a5b24e4ebd8'
'de0c1c372cc46bbee0ce3d1d49312e416a1fa9c7bb3e32a7eb3867d1c6d1f715')
SATOSHI_PUBLIC_KEY = ( '04'
'fc9702847840aaf195de8442ebecedf5b095cdbb9bc716bda9110971b28a49e0'
'ead8564ff0db22209e0374782c093bb899692d524e9d6a6956e7c5ecbcd68284')
indent = ' '*3
haveGUI = [False, None]
parser = optparse.OptionParser(usage="%prog [options]\n")
parser.add_option("--settings", dest="settingsPath",default='DEFAULT', type="str", help="load Armory with a specific settings file")
parser.add_option("--datadir", dest="datadir", default='DEFAULT', type="str", help="Change the directory that Armory calls home")
parser.add_option("--satoshi-datadir", dest="satoshiHome", default='DEFAULT', type='str', help="The Bitcoin-Qt/bitcoind home directory")
parser.add_option("--satoshi-port", dest="satoshiPort", default='DEFAULT', type="str", help="For Bitcoin-Qt instances operating on a non-standard port")
parser.add_option("--satoshi-rpcport", dest="satoshiRpcport",default='DEFAULT',type="str", help="RPC port Bitcoin-Qt instances operating on a non-standard port")
#parser.add_option("--bitcoind-path", dest="bitcoindPath",default='DEFAULT', type="str", help="Path to the location of bitcoind on your system")
parser.add_option("--dbdir", dest="leveldbDir", default='DEFAULT', type='str', help="Location to store blocks database (defaults to --datadir)")
parser.add_option("--rpcport", dest="rpcport", default='DEFAULT', type="str", help="RPC port for running armoryd.py")
parser.add_option("--testnet", dest="testnet", default=False, action="store_true", help="Use the testnet protocol")
parser.add_option("--offline", dest="offline", default=False, action="store_true", help="Force Armory to run in offline mode")
parser.add_option("--nettimeout", dest="nettimeout", default=2, type="int", help="Timeout for detecting internet connection at startup")
parser.add_option("--interport", dest="interport", default=-1, type="int", help="Port for inter-process communication between Armory instances")
parser.add_option("--debug", dest="doDebug", default=False, action="store_true", help="Increase amount of debugging output")
parser.add_option("--nologging", dest="logDisable", default=False, action="store_true", help="Disable all logging")
parser.add_option("--netlog", dest="netlog", default=False, action="store_true", help="Log networking messages sent and received by Armory")
parser.add_option("--logfile", dest="logFile", default='DEFAULT', type='str', help="Specify a non-default location to send logging information")
parser.add_option("--mtdebug", dest="mtdebug", default=False, action="store_true", help="Log multi-threaded call sequences")
parser.add_option("--skip-online-check",dest="forceOnline", default=False, action="store_true", help="Go into online mode, even if internet connection isn't detected")
parser.add_option("--skip-stats-report", dest="skipStatsReport", default=False, action="store_true", help="Does announcement checking without any OS/version reporting (for ATI statistics)")
parser.add_option("--skip-announce-check",dest="skipAnnounceCheck", default=False, action="store_true", help="Do not query for Armory announcements")
parser.add_option("--tor", dest="useTorSettings", default=False, action="store_true", help="Enable common settings for when Armory connects through Tor")
parser.add_option("--keypool", dest="keypool", default=100, type="int", help="Default number of addresses to lookahead in Armory wallets")
parser.add_option("--redownload", dest="redownload", default=False, action="store_true", help="Delete Bitcoin-Qt/bitcoind databases; redownload")
parser.add_option("--rebuild", dest="rebuild", default=False, action="store_true", help="Rebuild blockchain database and rescan")
parser.add_option("--rescan", dest="rescan", default=False, action="store_true", help="Rescan existing blockchain DB")
parser.add_option("--maxfiles", dest="maxOpenFiles",default=0, type="int", help="Set maximum allowed open files for LevelDB databases")
parser.add_option("--disable-torrent", dest="disableTorrent", default=False, action="store_true", help="Only download blockchain data via P2P network (slow)")
parser.add_option("--test-announce", dest="testAnnounceCode", default=False, action="store_true", help="Only used for developers needing to test announcement code with non-offline keys")
parser.add_option("--nospendzeroconfchange",dest="ignoreAllZC",default=False, action="store_true", help="All zero-conf funds will be unspendable, including sent-to-self coins")
parser.add_option("--multisigfile", dest="multisigFile", default='DEFAULT', type='str', help="File to store information about multi-signature transactions")
parser.add_option("--force-wallet-check", dest="forceWalletCheck", default=False, action="store_true", help="Force the wallet sanity check on startup")
parser.add_option("--disable-modules", dest="disableModules", default=False, action="store_true", help="Disable looking for modules in the execution directory")
parser.add_option("--disable-conf-permis", dest="disableConfPermis", default=False, action="store_true", help="Disable forcing permissions on bitcoin.conf")
# Pre-10.9 OS X sometimes passes a process serial number as -psn_0_xxxxxx. Nuke!
if sys.platform == 'darwin':
parser.add_option('-p', '--psn')
# These are arguments passed by running unit-tests that need to be handled
parser.add_option("--port", dest="port", default=None, type="int", help="Unit Test Argument - Do not consume")
parser.add_option("--verbosity", dest="verbosity", default=None, type="int", help="Unit Test Argument - Do not consume")
parser.add_option("--coverage_output_dir", dest="coverageOutputDir", default=None, type="str", help="Unit Test Argument - Do not consume")
parser.add_option("--coverage_include", dest="coverageInclude", default=None, type="str", help="Unit Test Argument - Do not consume")
# Some useful constants to be used throughout everything
BASE58CHARS = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
BASE16CHARS = '0123 4567 89ab cdef'.replace(' ','')
LITTLEENDIAN = '<'
BIGENDIAN = '>'
NETWORKENDIAN = '!'
ONE_BTC = long(100000000)
DONATION = long(5000000)
CENT = long(1000000)
UNINITIALIZED = None
UNKNOWN = -2
MIN_TX_FEE = 10000
MIN_RELAY_TX_FEE = 10000
MT_WAIT_TIMEOUT_SEC = 20;
UINT8_MAX = 2**8-1
UINT16_MAX = 2**16-1
UINT32_MAX = 2**32-1
UINT64_MAX = 2**64-1
RightNow = time.time
SECOND = 1
MINUTE = 60
HOUR = 3600
DAY = 24*HOUR
WEEK = 7*DAY
MONTH = 30*DAY
YEAR = 365*DAY
UNCOMP_PK_LEN = 65
COMP_PK_LEN = 33
KILOBYTE = 1024.0
MEGABYTE = 1024*KILOBYTE
GIGABYTE = 1024*MEGABYTE
TERABYTE = 1024*GIGABYTE
PETABYTE = 1024*TERABYTE
LB_MAXM = 7
LB_MAXN = 7
# Set the default-default
DEFAULT_DATE_FORMAT = '%Y-%b-%d %I:%M%p'
FORMAT_SYMBOLS = [ \
['%y', 'year, two digit (00-99)'], \
['%Y', 'year, four digit'], \
['%b', 'month name (abbrev)'], \
['%B', 'month name (full)'], \
['%m', 'month number (01-12)'], \
['%d', 'day of month (01-31)'], \
['%H', 'hour 24h (00-23)'], \
['%I', 'hour 12h (01-12)'], \
['%M', 'minute (00-59)'], \
['%p', 'morning/night (am,pm)'], \
['%a', 'day of week (abbrev)'], \
['%A', 'day of week (full)'], \
['%%', 'percent symbol'] ]
class UnserializeError(Exception): pass
class BadAddressError(Exception): pass
class VerifyScriptError(Exception): pass
class FileExistsError(Exception): pass
class ECDSA_Error(Exception): pass
class UnitializedBlockDataError(Exception): pass
class WalletLockError(Exception): pass
class SignatureError(Exception): pass
class KeyDataError(Exception): pass
class ChecksumError(Exception): pass
class WalletAddressError(Exception): pass
class PassphraseError(Exception): pass
class EncryptionError(Exception): pass
class InterruptTestError(Exception): pass
class NetworkIDError(Exception): pass
class WalletExistsError(Exception): pass
class ConnectionError(Exception): pass
class BlockchainUnavailableError(Exception): pass
class InvalidHashError(Exception): pass
class InvalidScriptError(Exception): pass
class BadURIError(Exception): pass
class CompressedKeyError(Exception): pass
class TooMuchPrecisionError(Exception): pass
class NegativeValueError(Exception): pass
class FiniteFieldError(Exception): pass
class BitcoindError(Exception): pass
class ShouldNotGetHereError(Exception): pass
class BadInputError(Exception): pass
class UstxError(Exception): pass
class P2SHNotSupportedError(Exception): pass
# Get the host operating system
opsys = platform.system()
OS_WINDOWS = 'win32' in opsys.lower() or 'windows' in opsys.lower()
OS_LINUX = 'nix' in opsys.lower() or 'nux' in opsys.lower()
OS_MACOSX = 'darwin' in opsys.lower() or 'osx' in opsys.lower()
if getattr(sys, 'frozen', False):
sys.argv = [arg.decode('utf8') for arg in sys.argv]
CLI_OPTIONS = None
CLI_ARGS = None
(CLI_OPTIONS, CLI_ARGS) = parser.parse_args()
# This is probably an abuse of the CLI_OPTIONS structure, but not
# automatically expanding "~" symbols is killing me
for opt,val in CLI_OPTIONS.__dict__.iteritems():
if not isinstance(val, basestring) or not val.startswith('~'):
continue
if os.path.exists(os.path.expanduser(val)):
CLI_OPTIONS.__dict__[opt] = os.path.expanduser(val)
else:
# If the path doesn't exist, it still won't exist when we don't
# modify it, and I'd like to modify as few vars as possible
pass
# Use CLI args to determine testnet or not
USE_TESTNET = CLI_OPTIONS.testnet
#USE_TESTNET = True
# Set default port for inter-process communication
if CLI_OPTIONS.interport < 0:
CLI_OPTIONS.interport = 8223 + (1 if USE_TESTNET else 0)
# Pass this bool to all getSpendable* methods, and it will consider
# all zero-conf UTXOs as unspendable, including sent-to-self (change)
IGNOREZC = CLI_OPTIONS.ignoreAllZC
# Figure out the default directories for Satoshi client, and BicoinArmory
OS_NAME = ''
OS_VARIANT = ''
USER_HOME_DIR = ''
BTC_HOME_DIR = ''
ARMORY_HOME_DIR = ''
LEVELDB_DIR = ''
SUBDIR = 'testnet3' if USE_TESTNET else ''
if OS_WINDOWS:
OS_NAME = 'Windows'
OS_VARIANT = platform.win32_ver()
import ctypes
buffer = ctypes.create_unicode_buffer(u'\0' * 260)
rt = ctypes.windll.shell32.SHGetFolderPathW(0, 26, 0, 0, ctypes.byref(buffer))
USER_HOME_DIR = unicode(buffer.value)
BTC_HOME_DIR = os.path.join(USER_HOME_DIR, 'Bitcoin', SUBDIR)
ARMORY_HOME_DIR = os.path.join(USER_HOME_DIR, 'Armory', SUBDIR)
BLKFILE_DIR = os.path.join(BTC_HOME_DIR, 'blocks')
BLKFILE_1stFILE = os.path.join(BLKFILE_DIR, 'blk00000.dat')
elif OS_LINUX:
OS_NAME = 'Linux'
OS_VARIANT = platform.linux_distribution()
USER_HOME_DIR = os.getenv('HOME')
BTC_HOME_DIR = os.path.join(USER_HOME_DIR, '.bitcoin', SUBDIR)
ARMORY_HOME_DIR = os.path.join(USER_HOME_DIR, '.armory', SUBDIR)
BLKFILE_DIR = os.path.join(BTC_HOME_DIR, 'blocks')
BLKFILE_1stFILE = os.path.join(BLKFILE_DIR, 'blk00000.dat')
elif OS_MACOSX:
platform.mac_ver()
OS_NAME = 'MacOSX'
OS_VARIANT = platform.mac_ver()
USER_HOME_DIR = os.path.expanduser('~/Library/Application Support')
BTC_HOME_DIR = os.path.join(USER_HOME_DIR, 'Bitcoin', SUBDIR)
ARMORY_HOME_DIR = os.path.join(USER_HOME_DIR, 'Armory', SUBDIR)
BLKFILE_DIR = os.path.join(BTC_HOME_DIR, 'blocks')
BLKFILE_1stFILE = os.path.join(BLKFILE_DIR, 'blk00000.dat')
else:
print '***Unknown operating system!'
print '***Cannot determine default directory locations'
# Get the host operating system
opsys = platform.system()
OS_WINDOWS = 'win32' in opsys.lower() or 'windows' in opsys.lower()
OS_LINUX = 'nix' in opsys.lower() or 'nux' in opsys.lower()
OS_MACOSX = 'darwin' in opsys.lower() or 'osx' in opsys.lower()
BLOCKCHAINS = {}
BLOCKCHAINS['\xf9\xbe\xb4\xd9'] = "Main Network"
BLOCKCHAINS['\xfa\xbf\xb5\xda'] = "Old Test Network"
BLOCKCHAINS['\x0b\x11\x09\x07'] = "Test Network (testnet3)"
NETWORKS = {}
NETWORKS['\x00'] = "Main Network"
NETWORKS['\x05'] = "Main Network"
NETWORKS['\x6f'] = "Test Network"
NETWORKS['\xc4'] = "Test Network"
NETWORKS['\x34'] = "Namecoin Network"
# We disable wallet checks on ARM for the sake of resources (unless forced)
DO_WALLET_CHECK = CLI_OPTIONS.forceWalletCheck or \
not platform.machine().lower().startswith('arm')
# Version Handling Code
def getVersionString(vquad, numPieces=4):
vstr = '%d.%02d' % vquad[:2]
if (vquad[2] > 0 or vquad[3] > 0) and numPieces>2:
vstr += '.%d' % vquad[2]
if vquad[3] > 0 and numPieces>3:
vstr += '.%d' % vquad[3]
return vstr
def getVersionInt(vquad, numPieces=4):
vint = int(vquad[0] * 1e7)
vint += int(vquad[1] * 1e5)
if numPieces>2:
vint += int(vquad[2] * 1e3)
if numPieces>3:
vint += int(vquad[3])
return vint
def readVersionString(verStr):
verList = [int(piece) for piece in verStr.split('.')]
while len(verList)<4:
verList.append(0)
return tuple(verList)
def readVersionInt(verInt):
verStr = str(verInt).rjust(10,'0')
verList = []
verList.append( int(verStr[ -3:]) )
verList.append( int(verStr[ -5:-3 ]) )
verList.append( int(verStr[ -7:-5 ]) )
verList.append( int(verStr[:-7 ]) )
return tuple(verList[::-1])
# Allow user to override default bitcoin-qt/bitcoind home directory
if not CLI_OPTIONS.satoshiHome.lower()=='default':
success = True
if USE_TESTNET:
testnetTry = os.path.join(CLI_OPTIONS.satoshiHome, 'testnet3')
if os.path.exists(testnetTry):
CLI_OPTIONS.satoshiHome = testnetTry
if not os.path.exists(CLI_OPTIONS.satoshiHome):
print 'Directory "%s" does not exist! Using default!' % \
CLI_OPTIONS.satoshiHome
else:
BTC_HOME_DIR = CLI_OPTIONS.satoshiHome
# Allow user to override default Armory home directory
if not CLI_OPTIONS.datadir.lower()=='default':
if not os.path.exists(CLI_OPTIONS.datadir):
print 'Directory "%s" does not exist! Using default!' % \
CLI_OPTIONS.datadir
else:
ARMORY_HOME_DIR = CLI_OPTIONS.datadir
# Same for the directory that holds the LevelDB databases
LEVELDB_DIR = os.path.join(ARMORY_HOME_DIR, 'databases')
if not CLI_OPTIONS.leveldbDir.lower()=='default':
if not os.path.exists(CLI_OPTIONS.leveldbDir):
print 'Directory "%s" does not exist! Using default!' % \
CLI_OPTIONS.leveldbDir
os.makedirs(CLI_OPTIONS.leveldbDir)
else:
LEVELDB_DIR = CLI_OPTIONS.leveldbDir
# Change the log file to use
ARMORY_LOG_FILE = os.path.join(ARMORY_HOME_DIR, 'armorylog.txt')
ARMCPP_LOG_FILE = os.path.join(ARMORY_HOME_DIR, 'armorycpplog.txt')
if not sys.argv[0] in ['ArmoryQt.py', 'ArmoryQt.exe', 'Armory.exe']:
basename = os.path.basename(sys.argv[0])
CLI_OPTIONS.logFile = os.path.join(ARMORY_HOME_DIR, '%s.log.txt' % basename)
# Change the settings file to use
if CLI_OPTIONS.settingsPath.lower()=='default':
CLI_OPTIONS.settingsPath = os.path.join(ARMORY_HOME_DIR, 'ArmorySettings.txt')
# Change the log file to use
if CLI_OPTIONS.logFile.lower()=='default':
if sys.argv[0] in ['ArmoryQt.py', 'ArmoryQt.exe', 'Armory.exe']:
CLI_OPTIONS.logFile = os.path.join(ARMORY_HOME_DIR, 'armorylog.txt')
else:
basename = os.path.basename(sys.argv[0])
CLI_OPTIONS.logFile = os.path.join(ARMORY_HOME_DIR, '%s.log.txt' % basename)
SETTINGS_PATH = CLI_OPTIONS.settingsPath
MULT_LOG_FILE = os.path.join(ARMORY_HOME_DIR, 'multipliers.txt')
MULTISIG_FILE_NAME = 'multisigs.txt'
MULTISIG_FILE = os.path.join(ARMORY_HOME_DIR, MULTISIG_FILE_NAME)
if not CLI_OPTIONS.multisigFile.lower()=='default':
if not os.path.exists(CLI_OPTIONS.multisigFile):
print 'Multisig file "%s" does not exist!' % CLI_OPTIONS.multisigFile
else:
MULTISIG_FILE = CLI_OPTIONS.multisigFile
# If this is the first Armory has been run, create directories
if ARMORY_HOME_DIR and not os.path.exists(ARMORY_HOME_DIR):
os.makedirs(ARMORY_HOME_DIR)
if not os.path.exists(LEVELDB_DIR):
os.makedirs(LEVELDB_DIR)
##### MAIN NETWORK IS DEFAULT #####
if not USE_TESTNET:
# TODO: The testnet genesis tx hash can't be the same...?
BITCOIN_PORT = 8333
BITCOIN_RPC_PORT = 8332
ARMORY_RPC_PORT = 8225
MAGIC_BYTES = '\xf9\xbe\xb4\xd9'
GENESIS_BLOCK_HASH_HEX = '6fe28c0ab6f1b372c1a6a246ae63f74f931e8365e15a089c68d6190000000000'
GENESIS_BLOCK_HASH = 'o\xe2\x8c\n\xb6\xf1\xb3r\xc1\xa6\xa2F\xaec\xf7O\x93\x1e\x83e\xe1Z\x08\x9ch\xd6\x19\x00\x00\x00\x00\x00'
GENESIS_TX_HASH_HEX = '3ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a'
GENESIS_TX_HASH = ';\xa3\xed\xfdz{\x12\xb2z\xc7,>gv\x8fa\x7f\xc8\x1b\xc3\x88\x8aQ2:\x9f\xb8\xaaK\x1e^J'
ADDRBYTE = '\x00'
P2SHBYTE = '\x05'
PRIVKEYBYTE = '\x80'
# This will usually just be used in the GUI to make links for the user
BLOCKEXPLORE_NAME = 'blockchain.info'
BLOCKEXPLORE_URL_TX = 'https://blockchain.info/tx/%s'
BLOCKEXPLORE_URL_ADDR = 'https://blockchain.info/address/%s'
else:
BITCOIN_PORT = 18333
BITCOIN_RPC_PORT = 18332
ARMORY_RPC_PORT = 18225
MAGIC_BYTES = '\x0b\x11\x09\x07'
GENESIS_BLOCK_HASH_HEX = '43497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000'
GENESIS_BLOCK_HASH = 'CI\x7f\xd7\xf8&\x95q\x08\xf4\xa3\x0f\xd9\xce\xc3\xae\xbay\x97 \x84\xe9\x0e\xad\x01\xea3\t\x00\x00\x00\x00'
GENESIS_TX_HASH_HEX = '3ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a'
GENESIS_TX_HASH = ';\xa3\xed\xfdz{\x12\xb2z\xc7,>gv\x8fa\x7f\xc8\x1b\xc3\x88\x8aQ2:\x9f\xb8\xaaK\x1e^J'
ADDRBYTE = '\x6f'
P2SHBYTE = '\xc4'
PRIVKEYBYTE = '\xef'
#
BLOCKEXPLORE_NAME = 'blockexplorer.com'
BLOCKEXPLORE_URL_TX = 'http://blockexplorer.com/testnet/tx/%s'
BLOCKEXPLORE_URL_ADDR = 'http://blockexplorer.com/testnet/address/%s'
# These are the same regardless of network
# They are the way data is stored in the database which is network agnostic
SCRADDR_P2PKH_BYTE = '\x00'
SCRADDR_P2SH_BYTE = '\x05'
SCRADDR_MULTISIG_BYTE = '\xfe'
SCRADDR_NONSTD_BYTE = '\xff'
SCRADDR_BYTE_LIST = [SCRADDR_P2PKH_BYTE, \
SCRADDR_P2SH_BYTE, \
SCRADDR_MULTISIG_BYTE, \
SCRADDR_NONSTD_BYTE]
# Copied from cppForSwig/BtcUtils.h::getTxOutScriptTypeInt(script)
CPP_TXOUT_STDHASH160 = 0
CPP_TXOUT_STDPUBKEY65 = 1
CPP_TXOUT_STDPUBKEY33 = 2
CPP_TXOUT_MULTISIG = 3
CPP_TXOUT_P2SH = 4
CPP_TXOUT_NONSTANDARD = 5
CPP_TXOUT_HAS_ADDRSTR = [CPP_TXOUT_STDHASH160, \
CPP_TXOUT_STDPUBKEY65,
CPP_TXOUT_STDPUBKEY33,
CPP_TXOUT_P2SH]
CPP_TXOUT_STDSINGLESIG = [CPP_TXOUT_STDHASH160, \
CPP_TXOUT_STDPUBKEY65,
CPP_TXOUT_STDPUBKEY33]
CPP_TXOUT_SCRIPT_NAMES = ['']*6
CPP_TXOUT_SCRIPT_NAMES[CPP_TXOUT_STDHASH160] = 'Standard (PKH)'
CPP_TXOUT_SCRIPT_NAMES[CPP_TXOUT_STDPUBKEY65] = 'Standard (PK65)'
CPP_TXOUT_SCRIPT_NAMES[CPP_TXOUT_STDPUBKEY33] = 'Standard (PK33)'
CPP_TXOUT_SCRIPT_NAMES[CPP_TXOUT_MULTISIG] = 'Multi-Signature'
CPP_TXOUT_SCRIPT_NAMES[CPP_TXOUT_P2SH] = 'Standard (P2SH)'
CPP_TXOUT_SCRIPT_NAMES[CPP_TXOUT_NONSTANDARD] = 'Non-Standard'
# Copied from cppForSwig/BtcUtils.h::getTxInScriptTypeInt(script)
CPP_TXIN_STDUNCOMPR = 0
CPP_TXIN_STDCOMPR = 1
CPP_TXIN_COINBASE = 2
CPP_TXIN_SPENDPUBKEY = 3
CPP_TXIN_SPENDMULTI = 4
CPP_TXIN_SPENDP2SH = 5
CPP_TXIN_NONSTANDARD = 6
CPP_TXIN_SCRIPT_NAMES = ['']*7
CPP_TXIN_SCRIPT_NAMES[CPP_TXIN_STDUNCOMPR] = 'Sig + PubKey65'
CPP_TXIN_SCRIPT_NAMES[CPP_TXIN_STDCOMPR] = 'Sig + PubKey33'
CPP_TXIN_SCRIPT_NAMES[CPP_TXIN_COINBASE] = 'Coinbase'
CPP_TXIN_SCRIPT_NAMES[CPP_TXIN_SPENDPUBKEY] = 'Plain Signature'
CPP_TXIN_SCRIPT_NAMES[CPP_TXIN_SPENDMULTI] = 'Spend Multisig'
CPP_TXIN_SCRIPT_NAMES[CPP_TXIN_SPENDP2SH] = 'Spend P2SH'
CPP_TXIN_SCRIPT_NAMES[CPP_TXIN_NONSTANDARD] = 'Non-Standard'
################################################################################
if not CLI_OPTIONS.satoshiPort == 'DEFAULT':
try:
BITCOIN_PORT = int(CLI_OPTIONS.satoshiPort)
except:
raise TypeError('Invalid port for Bitcoin-Qt, using ' + str(BITCOIN_PORT))
################################################################################
if not CLI_OPTIONS.satoshiRpcport == 'DEFAULT':
try:
BITCOIN_RPC_PORT = int(CLI_OPTIONS.satoshiRpcport)
except:
raise TypeError('Invalid rpc port for Bitcoin-Qt, using ' + str(BITCOIN_RPC_PORT))
################################################################################
if not CLI_OPTIONS.rpcport == 'DEFAULT':
try:
ARMORY_RPC_PORT = int(CLI_OPTIONS.rpcport)
except:
raise TypeError('Invalid RPC port for armoryd ' + str(ARMORY_RPC_PORT))
if sys.argv[0]=='ArmoryQt.py':
print '********************************************************************************'
print 'Loading Armory Engine:'
print ' Armory Version: ', getVersionString(BTCARMORY_VERSION)
print ' PyBtcWallet Version:', getVersionString(PYBTCWALLET_VERSION)
print 'Detected Operating system:', OS_NAME
print ' OS Variant :', OS_VARIANT
print ' User home-directory :', USER_HOME_DIR
print ' Satoshi BTC directory :', BTC_HOME_DIR
print ' Armory home dir :', ARMORY_HOME_DIR
print ' LevelDB directory :', LEVELDB_DIR
print ' Armory settings file :', SETTINGS_PATH
print ' Armory log file :', ARMORY_LOG_FILE
print ' Do wallet checking :', DO_WALLET_CHECK
################################################################################
def launchProcess(cmd, useStartInfo=True, *args, **kwargs):
LOGINFO('Executing popen: %s', str(cmd))
if not OS_WINDOWS:
from subprocess import Popen, PIPE
return Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, *args, **kwargs)
else:
from subprocess_win import Popen, PIPE, STARTUPINFO, STARTF_USESHOWWINDOW
if useStartInfo:
startinfo = STARTUPINFO()
startinfo.dwFlags |= STARTF_USESHOWWINDOW
return Popen(cmd, \
*args, \
stdin=PIPE, \
stdout=PIPE, \
stderr=PIPE, \
startupinfo=startinfo, \
**kwargs)
else:
return Popen(cmd, \
*args, \
stdin=PIPE, \
stdout=PIPE, \
stderr=PIPE, \
**kwargs)
################################################################################
def killProcess(pid, sig='default'):
# I had to do this, because killing a process in Windows has issues
# when using py2exe (yes, os.kill does not work, for the same reason
# I had to pass stdin/stdout/stderr everywhere...
LOGWARN('Killing process pid=%d', pid)
if not OS_WINDOWS:
import os
sig = signal.SIGKILL if sig=='default' else sig
os.kill(pid, sig)
else:
import sys, os.path, ctypes, ctypes.wintypes
k32 = ctypes.WinDLL('kernel32.dll')
k32.OpenProcess.restype = ctypes.wintypes.HANDLE
k32.TerminateProcess.restype = ctypes.wintypes.BOOL
hProcess = k32.OpenProcess(1, False, pid)
k32.TerminateProcess(hProcess, 1)
k32.CloseHandle(hProcess)
################################################################################
def subprocess_check_output(*popenargs, **kwargs):
"""
Run command with arguments and return its output as a byte string.
Backported from Python 2.7, because it's stupid useful, short, and
won't exist on systems using Python 2.6 or earlier
"""
from subprocess import CalledProcessError
process = launchProcess(*popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
error = CalledProcessError(retcode, cmd)
error.output = output
raise error
return output
################################################################################
def killProcessTree(pid):
# In this case, Windows is easier because we know it has the get_children
# call, because have bundled a recent version of psutil. Linux, however,
# does not have that function call in earlier versions.
from subprocess import Popen, PIPE
if not OS_LINUX:
for child in psutil.Process(pid).get_children():
killProcess(child.pid)
else:
proc = Popen("ps -o pid --ppid %d --noheaders" % pid, shell=True, stdout=PIPE)
out,err = proc.communicate()
for pid_str in out.split("\n")[:-1]:
killProcess(int(pid_str))
################################################################################
# Similar to subprocess_check_output, but used for long-running commands
def execAndWait(cli_str, timeout=0, useStartInfo=True):
"""
There may actually still be references to this function where check_output
would've been more appropriate. But I didn't know about check_output at
the time...
"""
process = launchProcess(cli_str, shell=True, useStartInfo=useStartInfo)
pid = process.pid
start = RightNow()
while process.poll() == None:
time.sleep(0.1)
if timeout>0 and (RightNow() - start)>timeout:
print 'Process exceeded timeout, killing it'
killProcess(pid)
out,err = process.communicate()
return [out,err]
######### INITIALIZE LOGGING UTILITIES ##########
#
# Setup logging to write INFO+ to file, and WARNING+ to console
# In debug mode, will write DEBUG+ to file and INFO+ to console
#
# Want to get the line in which an error was triggered, but by wrapping
# the logger function (as I will below), the displayed "file:linenum"
# references the logger function, not the function that called it.
# So I use traceback to find the file and line number two up in the
# stack trace, and return that to be displayed instead of default
# [Is this a hack? Yes and no. I see no other way to do this]
def getCallerLine():
stkTwoUp = traceback.extract_stack()[-3]
filename,method = stkTwoUp[0], stkTwoUp[1]
return '%s:%d' % (os.path.basename(filename),method)
# When there's an error in the logging function, it's impossible to find!
# These wrappers will print the full stack so that it's possible to find
# which line triggered the error
def LOGDEBUG(msg, *a):
try:
logstr = msg if len(a)==0 else (msg%a)
callerStr = getCallerLine() + ' - '
logging.debug(callerStr + logstr)
except TypeError:
traceback.print_stack()
raise
def LOGINFO(msg, *a):
try:
logstr = msg if len(a)==0 else (msg%a)
callerStr = getCallerLine() + ' - '
logging.info(callerStr + logstr)
except TypeError:
traceback.print_stack()
raise
def LOGWARN(msg, *a):
try:
logstr = msg if len(a)==0 else (msg%a)
callerStr = getCallerLine() + ' - '
logging.warn(callerStr + logstr)
except TypeError:
traceback.print_stack()
raise
def LOGERROR(msg, *a):
try:
logstr = msg if len(a)==0 else (msg%a)
callerStr = getCallerLine() + ' - '
logging.error(callerStr + logstr)
except TypeError:
traceback.print_stack()
raise
def LOGCRIT(msg, *a):
try:
logstr = msg if len(a)==0 else (msg%a)
callerStr = getCallerLine() + ' - '
logging.critical(callerStr + logstr)
except TypeError:
traceback.print_stack()
raise
def LOGEXCEPT(msg, *a):
try:
logstr = msg if len(a)==0 else (msg%a)
callerStr = getCallerLine() + ' - '
logging.exception(callerStr + logstr)
except TypeError:
traceback.print_stack()
raise
def chopLogFile(filename, size):
if not os.path.exists(filename):
print 'Log file doesn\'t exist [yet]'
return
logfile = open(filename, 'r')
allLines = logfile.readlines()
logfile.close()
nBytes,nLines = 0,0;
for line in allLines[::-1]:
nBytes += len(line)
nLines += 1
if nBytes>size:
break
logfile = open(filename, 'w')
for line in allLines[-nLines:]:
logfile.write(line)
logfile.close()
# Cut down the log file to just the most recent 1 MB
chopLogFile(ARMORY_LOG_FILE, 1024*1024)
# Now set loglevels
DEFAULT_CONSOLE_LOGTHRESH = logging.WARNING
DEFAULT_FILE_LOGTHRESH = logging.INFO
DEFAULT_PPRINT_LOGLEVEL = logging.DEBUG
DEFAULT_RAWDATA_LOGLEVEL = logging.DEBUG
rootLogger = logging.getLogger('')
if CLI_OPTIONS.doDebug or CLI_OPTIONS.netlog or CLI_OPTIONS.mtdebug:
# Drop it all one level: console will see INFO, file will see DEBUG
DEFAULT_CONSOLE_LOGTHRESH -= 20
DEFAULT_FILE_LOGTHRESH -= 20
if CLI_OPTIONS.logDisable:
DEFAULT_CONSOLE_LOGTHRESH += 100
DEFAULT_FILE_LOGTHRESH += 100
DateFormat = '%Y-%m-%d %H:%M'
logging.getLogger('').setLevel(logging.DEBUG)
fileFormatter = logging.Formatter('%(asctime)s (%(levelname)s) -- %(message)s', \
datefmt=DateFormat)
fileHandler = logging.FileHandler(ARMORY_LOG_FILE)
fileHandler.setLevel(DEFAULT_FILE_LOGTHRESH)
fileHandler.setFormatter(fileFormatter)
logging.getLogger('').addHandler(fileHandler)
consoleFormatter = logging.Formatter('(%(levelname)s) %(message)s')
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(DEFAULT_CONSOLE_LOGTHRESH)
consoleHandler.setFormatter( consoleFormatter )
logging.getLogger('').addHandler(consoleHandler)
class stringAggregator(object):
def __init__(self):
self.theStr = ''
def getStr(self):
return self.theStr
def write(self, theStr):
self.theStr += theStr
# A method to redirect pprint() calls to the log file
# Need a way to take a pprint-able object, and redirect its output to file
# Do this by swapping out sys.stdout temporarily, execute theObj.pprint()
# then set sys.stdout back to the original.
def LOGPPRINT(theObj, loglevel=DEFAULT_PPRINT_LOGLEVEL):
sys.stdout = stringAggregator()
theObj.pprint()
printedStr = sys.stdout.getStr()
sys.stdout = sys.__stdout__
stkOneUp = traceback.extract_stack()[-2]
filename,method = stkOneUp[0], stkOneUp[1]
methodStr = '(PPRINT from %s:%d)\n' % (filename,method)
logging.log(loglevel, methodStr + printedStr)
# For super-debug mode, we'll write out raw data
def LOGRAWDATA(rawStr, loglevel=DEFAULT_RAWDATA_LOGLEVEL):
dtype = isLikelyDataType(rawStr)
stkOneUp = traceback.extract_stack()[-2]
filename,method = stkOneUp[0], stkOneUp[1]
methodStr = '(PPRINT from %s:%d)\n' % (filename,method)
pstr = rawStr[:]
if dtype==DATATYPE.Binary:
pstr = binary_to_hex(rawStr)
pstr = prettyHex(pstr, indent=' ', withAddr=False)
elif dtype==DATATYPE.Hex:
pstr = prettyHex(pstr, indent=' ', withAddr=False)
else:
pstr = ' ' + '\n '.join(pstr.split('\n'))
logging.log(loglevel, methodStr + pstr)
cpplogfile = None
if CLI_OPTIONS.logDisable:
print 'Logging is disabled'
rootLogger.disabled = True
def logexcept_override(type, value, tback):
import traceback
import logging
strList = traceback.format_exception(type,value,tback)
logging.error(''.join([s for s in strList]))
# then call the default handler
sys.__excepthook__(type, value, tback)
sys.excepthook = logexcept_override
# If there is a rebuild or rescan flag, let's do the right thing.
fileRedownload = os.path.join(ARMORY_HOME_DIR, 'redownload.flag')
fileRebuild = os.path.join(ARMORY_HOME_DIR, 'rebuild.flag')
fileRescan = os.path.join(ARMORY_HOME_DIR, 'rescan.flag')
fileDelSettings = os.path.join(ARMORY_HOME_DIR, 'delsettings.flag')
# Flag to remove everything in Bitcoin dir except wallet.dat (if requested)
if os.path.exists(fileRedownload):
# Flag to remove *BITCOIN-QT* databases so it will have to re-download
LOGINFO('Found %s, will delete Bitcoin DBs & redownload' % fileRedownload)
os.remove(fileRedownload)
if os.path.exists(fileRebuild):
os.remove(fileRebuild)
if os.path.exists(fileRescan):
os.remove(fileRescan)
CLI_OPTIONS.redownload = True
CLI_OPTIONS.rebuild = True
elif os.path.exists(fileRebuild):
# Flag to remove Armory databases so it will have to rebuild
LOGINFO('Found %s, will destroy and rebuild databases' % fileRebuild)
os.remove(fileRebuild)
if os.path.exists(fileRescan):
os.remove(fileRescan)
CLI_OPTIONS.rebuild = True
elif os.path.exists(fileRescan):
LOGINFO('Found %s, will throw out saved history, rescan' % fileRescan)
os.remove(fileRescan)
if os.path.exists(fileRebuild):
os.remove(fileRebuild)
CLI_OPTIONS.rescan = True
# Separately, we may want to delete the settings file, which couldn't
# be done easily from the GUI, because it frequently gets rewritten to
# file before shutdown is complete. The best way is to delete it on start.
if os.path.exists(fileDelSettings):
os.remove(SETTINGS_PATH)
os.remove(fileDelSettings)
################################################################################
def deleteBitcoindDBs():
if not os.path.exists(BTC_HOME_DIR):
LOGERROR('Could not find Bitcoin-Qt/bitcoind home dir to remove blk data')
LOGERROR(' Does not exist: %s' % BTC_HOME_DIR)
else:
LOGINFO('Found bitcoin home dir, removing blocks and databases')
# Remove directories
for btcDir in ['blocks', 'chainstate', 'database']:
fullPath = os.path.join(BTC_HOME_DIR, btcDir)
if os.path.exists(fullPath):
LOGINFO(' Removing dir: %s' % fullPath)
shutil.rmtree(fullPath)
# Remove files
for btcFile in ['DB_CONFIG', 'db.log', 'debug.log', 'peers.dat']:
fullPath = os.path.join(BTC_HOME_DIR, btcFile)
if os.path.exists(fullPath):
LOGINFO(' Removing file: %s' % fullPath)
os.remove(fullPath)
#####
if CLI_OPTIONS.redownload:
deleteBitcoindDBs()
if os.path.exists(fileRedownload):
os.remove(fileRedownload)
#####
if CLI_OPTIONS.rebuild and os.path.exists(LEVELDB_DIR):
LOGINFO('Found existing databases dir; removing before rebuild')
shutil.rmtree(LEVELDB_DIR)
os.mkdir(LEVELDB_DIR)
####
if CLI_OPTIONS.testAnnounceCode:
LOGERROR('*'*60)
LOGERROR('You are currently using a developer mode intended for ')
LOGERROR('to help with testing of announcements, which is considered')
LOGERROR('a security risk. ')
LOGERROR('*'*60)
ARMORY_INFO_SIGN_ADDR = '1PpAJyNoocJt38Vcf4AfPffaxo76D4AAEe'
ARMORY_INFO_SIGN_PUBLICKEY = ('04'
'601c891a2cbc14a7b2bb1ecc9b6e42e166639ea4c2790703f8e2ed126fce432c'
'62fe30376497ad3efcd2964aa0be366010c11b8d7fc8209f586eac00bb763015')
####
if CLI_OPTIONS.useTorSettings:
LOGWARN('Option --tor was supplied, forcing --skip-announce-check,')
LOGWARN('--skip-online-check, --skip-stats-report and --disable-torrent')
CLI_OPTIONS.skipAnnounceCheck = True
CLI_OPTIONS.skipStatsReport = True
CLI_OPTIONS.forceOnline = True
CLI_OPTIONS.disableTorrent = True
################################################################################
def addWalletToList(inWltPath, inWltList):
'''Helper function that checks to see if a path contains a valid wallet. If
so, the wallet will be added to the incoming list.'''
if os.path.isfile(inWltPath):
if not inWltPath.endswith('backup.wallet'):
openfile = open(inWltPath, 'rb')
first8 = openfile.read(8)
openfile.close()
if first8=='\xbaWALLET\x00':
inWltList.append(inWltPath)
else:
if not os.path.isdir(inWltPath):
LOGWARN('Path %s does not exist.' % inWltPath)
else:
LOGDEBUG('%s is a directory.' % inWltPath)
################################################################################
def readWalletFiles(inWltList=None):
'''Function that finds the paths of all non-backup wallets in the Armory
data directory (nothing passed in) or in a list of wallet paths (paths
passed in.'''
wltPaths = []
if not inWltList: