forked from etotheipi/BitcoinArmory
-
Notifications
You must be signed in to change notification settings - Fork 7
/
armoryengine.py
13061 lines (10757 loc) · 483 KB
/
armoryengine.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-2013, Alan C. Reiner <[email protected]>
# 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
#
################################################################################
# Version Numbers
BTCARMORY_VERSION = (0, 88, 1, 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')
import copy
import hashlib
import random
import time
import os
import string
import sys
import stat
import shutil
import math
import logging
import logging.handlers
import locale
import ast
import traceback
import threading
import signal
import inspect
import multiprocessing
import psutil
from struct import pack, unpack
from datetime import datetime
# In Windows with py2exe, we have a problem unless we PIPE all streams
from subprocess import Popen, PIPE
from sys import argv
import optparse
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("--bitcoind-path", dest="bitcoindPath",default='DEFAULT', type="str", help="Path to the location of bitcoind on your system")
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-version-check", dest="skipVerCheck", default=False, action="store_true", help="Do not contact bitcoinarmory.com to check for new versions")
parser.add_option("--keypool", dest="keypool", default=100, type="int", help="Default number of addresses to lookahead in Armory wallets")
################################################################################
# We need to have some methods for casting ASCII<->Unicode<->Preferred
DEFAULT_ENCODING = 'utf-8'
def isASCII(theStr):
try:
theStr.decode('ascii')
return True
except UnicodeEncodeError:
return False
except UnicodeDecodeError:
return False
except:
LOGEXCEPT('What was passed to this function? %s', theStr)
return False
def toBytes(theStr, theEncoding=DEFAULT_ENCODING):
if isinstance(theStr, unicode):
return theStr.encode(theEncoding)
elif isinstance(theStr, str):
return theStr
else:
LOGERROR('toBytes() not been defined for input: %s', str(type(theStr)))
def toUnicode(theStr, theEncoding=DEFAULT_ENCODING):
if isinstance(theStr, unicode):
return theStr
elif isinstance(theStr, str):
return unicode(theStr, theEncoding)
else:
LOGERROR('toUnicode() not been defined for input: %s', str(type(theStr)))
def toPreferred(theStr):
return toUnicode(theStr).encode(locale.getpreferredencoding())
def lenBytes(theStr, theEncoding=DEFAULT_ENCODING):
return len(toBytes(theStr, theEncoding))
################################################################################
(CLI_OPTIONS, CLI_ARGS) = parser.parse_args()
# Use CLI args to determine testnet or not
USE_TESTNET = CLI_OPTIONS.testnet
# Set default port for inter-process communication
if CLI_OPTIONS.interport < 0:
CLI_OPTIONS.interport = 8223 + (1 if USE_TESTNET else 0)
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])
# Get the host operating system
import platform
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()
# Figure out the default directories for Satoshi client, and BicoinArmory
OS_NAME = ''
OS_VARIANT = ''
USER_HOME_DIR = ''
BTC_HOME_DIR = ''
ARMORY_HOME_DIR = ''
SUBDIR = 'testnet3' if USE_TESTNET else ''
if OS_WINDOWS:
OS_NAME = 'Windows'
OS_VARIANT = platform.win32_ver()
USER_HOME_DIR = os.getenv('APPDATA')
BTC_HOME_DIR = os.path.join(USER_HOME_DIR, 'Bitcoin', SUBDIR)
ARMORY_HOME_DIR = os.path.join(USER_HOME_DIR, 'Armory', SUBDIR)
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)
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)
else:
print '***Unknown operating system!'
print '***Cannot determine default directory locations'
# Allow user to override default bitcoin-qt/bitcoind home directory
if not CLI_OPTIONS.satoshiHome.lower()=='default':
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
# Change the settings file to use
#BITCOIND_PATH = None
#if not CLI_OPTIONS.bitcoindPath.lower()=='default':
#BITCOIND_PATH = CLI_OPTIONS.bitcoindPath
# 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
ARMORY_LOG_FILE = CLI_OPTIONS.logFile
# 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)
def findLatestBlkFiles(baseDir):
# Bitcoin-Qt 0.8+ uses new location. User might also be specifying
# non-standard location. Detect whatever the heck we can...
lastModTimeOld4 = 0
lastModTimeOld5 = 0
lastModTimeNew4 = 0
lastModTimeNew5 = 0
baseDir = toPreferred(baseDir)
newDir = os.path.join(baseDir, 'blocks')
newBlkPath4 = lambda x: os.path.join(newDir, 'blk%04d.dat'%x)
newBlkPath5 = lambda x: os.path.join(newDir, 'blk%05d.dat'%x)
oldBlkPath4 = lambda x: os.path.join(baseDir, 'blk%04d.dat'%x)
oldBlkPath5 = lambda x: os.path.join(baseDir, 'blk%05d.dat'%x)
# Check the last modification time of the top blocks/blk000X.dat
i = 1;
if os.path.exists(newDir) and os.path.exists(newBlkPath4(i)):
while( os.path.exists(newBlkPath4(i) ) ):
lastModTimeNew4 = os.path.getmtime(newBlkPath4(i))
i += 1
# Check the last modification time of the top blocks/blk0000X.dat
i = 0;
if os.path.exists(newDir) and os.path.exists(newBlkPath5(i)):
while( os.path.exists(newBlkPath5(i) ) ):
lastModTimeNew5 = os.path.getmtime(newBlkPath5(i))
i += 1
# Check the last modification time of the top blk000X.dat
i = 1;
if os.path.exists(baseDir) and os.path.exists( oldBlkPath4(i)):
while( os.path.exists(oldBlkPath4(i) ) ):
lastModTimeOld4 = os.path.getmtime(oldBlkPath4(i))
i += 1
# Check the last modification time of the top blk0000X.dat
i = 0;
if os.path.exists(baseDir) and os.path.exists( oldBlkPath5(i)):
while( os.path.exists(oldBlkPath5(i) ) ):
lastModTimeOld5 = os.path.getmtime(oldBlkPath5(i))
i += 1
latestMod = max(lastModTimeNew4, lastModTimeNew5, lastModTimeOld4, lastModTimeOld5)
#if latestMod==0:
#print '\n*****ERROR: No blkXXXXX.dat files found!\n'
output = [newDir, 5, 0]
if(lastModTimeNew4 == latestMod):
output = [newDir, 4, 1]
elif(lastModTimeNew5 == latestMod):
output = [newDir, 5, 0]
elif(lastModTimeOld4 == latestMod):
output = [baseDir, 4, 1]
elif(lastModTimeOld5 == latestMod):
output = [baseDir, 5, 0]
# We didn't detect anything... will return default location for 0.8+
firstFile = os.path.join(output[0], 'blk')
firstFile += ('%%0%dd.dat' % output[1]) % output[2]
output.append(firstFile)
return output
BLKFILE_LOCATION = findLatestBlkFiles(BTC_HOME_DIR)
BLKFILE_DIRECTORY = BLKFILE_LOCATION[0]
BLKFILE_NUMDIGITS = BLKFILE_LOCATION[1]
BLKFILE_STARTINDEX = BLKFILE_LOCATION[2]
BLKFILE_FIRSTFILE = BLKFILE_LOCATION[3]
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 ' First blkX.dat file :', BLKFILE_FIRSTFILE
print ' Armory home dir :', ARMORY_HOME_DIR
print ' Armory settings file :', SETTINGS_PATH
print ' Armory log file :', ARMORY_LOG_FILE
class UnserializeError(Exception): pass
class BadAddressError(Exception): pass
class VerifyScriptError(Exception): pass
class FileExistsError(Exception): pass
class ECDSA_Error(Exception): pass
class PackerError(Exception): pass
class UnpackerError(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 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
##### 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'
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'
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.rpcport == 'DEFAULT':
try:
ARMORY_RPC_PORT = int(CLI_OPTIONS.rpcport)
except:
raise TypeError, 'Invalid RPC port for armoryd ' + str(ARMORY_RPC_PORT)
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['\x6f'] = "Test Network"
NETWORKS['\x34'] = "Namecoin Network"
######### 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
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 -= 10
DEFAULT_FILE_LOGTHRESH -= 10
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
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
# For now, ditch the C++-console-catching. Logging python is enough
# My attempt at C++ logging too was becoming a hardcore hack...
"""
elif CLI_OPTIONS.logcpp:
# In order to catch C++ output, we have to redirect ALL stdout
# (which means that console writes by python, too)
cpplogfile = open(ARMORY_LOG_FILE_CPP, 'r')
allLines = cpplogfile.readlines()
cpplogfile.close()
# Chop off the beginning of the file
nBytes,nLines = 0,0;
for line in allLines[::-1]:
nBytes += len(line)
nLines += 1
if nBytes>100*1024:
break
cpplogfile = open(ARMORY_LOG_FILE_CPP, 'w')
print 'nlines:', nLines
for line in allLines[-nLines:]:
print line,
cpplogfile.write(line)
cpplogfile.close()
cpplogfile = open(ARMORY_LOG_FILE_CPP, 'a')
raw_input()
os.dup2(cpplogfile.fileno(), sys.stdout.fileno())
raw_input()
os.dup2(cpplogfile.fileno(), sys.stderr.fileno())
"""
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
################################################################################
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 import Popen, PIPE, STARTUPINFO, STARTF_USESHOWWINDOW
# Need lots of complicated stuff to accommodate quirks with Windows
if isinstance(cmd, basestring):
cmd2 = toPreferred(cmd)
else:
cmd2 = [toPreferred(c) for c in cmd]
if useStartInfo:
startinfo = STARTUPINFO()
startinfo.dwFlags |= STARTF_USESHOWWINDOW
return Popen(cmd2, \
*args, \
stdin=PIPE, \
stdout=PIPE, \
stderr=PIPE, \
startupinfo=startinfo, \
**kwargs)
else:
return Popen(cmd2, \
*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 Popen, PIPE, 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.
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]
################################################################################
# Get system details for logging purposes
class DumbStruct(object): pass
def GetSystemDetails():
"""Checks memory of a given system"""
out = DumbStruct()
CPU,COR,X64,MEM = range(4)
sysParam = [None,None,None,None]
if OS_LINUX:
# Get total RAM
freeStr = subprocess_check_output('free -m', shell=True)
totalMemory = freeStr.split('\n')[1].split()[1]
out.Memory = int(totalMemory) * 1024
# Get CPU name
cpuinfo = subprocess_check_output(['cat','/proc/cpuinfo'])
for line in cpuinfo.split('\n'):
if line.strip().lower().startswith('model name'):
out.CpuStr = line.split(':')[1].strip()
break
elif OS_WINDOWS:
import ctypes
class MEMORYSTATUSEX(ctypes.Structure):
_fields_ = [
("dwLength", ctypes.c_ulong),
("dwMemoryLoad", ctypes.c_ulong),
("ullTotalPhys", ctypes.c_ulonglong),
("ullAvailPhys", ctypes.c_ulonglong),
("ullTotalPageFile", ctypes.c_ulonglong),
("ullAvailPageFile", ctypes.c_ulonglong),
("ullTotalVirtual", ctypes.c_ulonglong),
("ullAvailVirtual", ctypes.c_ulonglong),
("sullAvailExtendedVirtual", ctypes.c_ulonglong),
]
def __init__(self):
# have to initialize this to the size of MEMORYSTATUSEX
self.dwLength = ctypes.sizeof(self)
super(MEMORYSTATUSEX, self).__init__()
stat = MEMORYSTATUSEX()
ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))
out.Memory = stat.ullTotalPhys/1024.
out.CpuStr = platform.processor()
else:
raise OSError, "Can't get system specs in OSX"
out.NumCores = multiprocessing.cpu_count()
out.IsX64 = platform.architecture()[0].startswith('64')
out.Memory = out.Memory / (1024*1024.)
return out
try:
SystemSpecs = GetSystemDetails()
except:
LOGEXCEPT('Error getting system details:')
LOGERROR('Skipping.')
SystemSpecs = DumbStruct()
SystemSpecs.Memory = -1
SystemSpecs.CpuStr = 'Unknown'
SystemSpecs.NumCores = -1
SystemSpecs.IsX64 = 'Unknown'
LOGINFO('')
LOGINFO('')
LOGINFO('')
LOGINFO('************************************************************')
LOGINFO('Invoked: ' + ' '.join(argv))
LOGINFO('************************************************************')
LOGINFO('Loading Armory Engine:')
LOGINFO(' Armory Version : ' + getVersionString(BTCARMORY_VERSION))
LOGINFO(' PyBtcWallet Version : ' + getVersionString(PYBTCWALLET_VERSION))
LOGINFO('Detected Operating system: ' + OS_NAME)
LOGINFO(' OS Variant : ' + (str(OS_VARIANT) if OS_MACOSX else '-'.join(OS_VARIANT)))
LOGINFO(' User home-directory : ' + USER_HOME_DIR)
LOGINFO(' Satoshi BTC directory : ' + BTC_HOME_DIR)
LOGINFO(' First blk*.dat file : ' + BLKFILE_FIRSTFILE)
LOGINFO(' Armory home dir : ' + ARMORY_HOME_DIR)
LOGINFO('Detected System Specs : ')
LOGINFO(' Total Available RAM : %0.2f GB', SystemSpecs.Memory)
LOGINFO(' CPU ID string : ' + SystemSpecs.CpuStr)
LOGINFO(' Number of CPU cores : %d cores', SystemSpecs.NumCores)
LOGINFO(' System is 64-bit : ' + str(SystemSpecs.IsX64))
LOGINFO(' Preferred Encoding : ' + locale.getpreferredencoding())
LOGINFO('')
LOGINFO('Network Name: ' + NETWORKS[ADDRBYTE])
LOGINFO('Satoshi Port: %d', BITCOIN_PORT)
LOGINFO('Named options/arguments to armoryengine.py:')
for key,val in ast.literal_eval(str(CLI_OPTIONS)).iteritems():
LOGINFO(' %-16s: %s', key,val)
LOGINFO('Other arguments:')
for val in CLI_ARGS:
LOGINFO(' %s', val)
LOGINFO('************************************************************')
def GetExecDir():
"""
Return the path from where armoryengine was imported. Inspect method
expects a function or module name, it can actually inspect its own
name...
"""
srcfile = inspect.getsourcefile(GetExecDir)
srcpath = os.path.dirname(srcfile)
srcpath = os.path.abspath(srcpath)
return srcpath
def coin2str(nSatoshi, ndec=8, rJust=True, maxZeros=8):
"""
Converts a raw value (1e-8 BTC) into a formatted string for display
ndec, guarantees that we get get a least N decimal places in our result
maxZeros means we will replace zeros with spaces up to M decimal places
in order to declutter the amount field
"""
nBtc = float(nSatoshi) / float(ONE_BTC)
s = ('%%0.%df' % ndec) % nBtc
s = s.rjust(18, ' ')
if maxZeros < ndec:
maxChop = ndec - maxZeros
nChop = min(len(s) - len(str(s.strip('0'))), maxChop)
if nChop>0:
s = s[:-nChop] + nChop*' '
if nSatoshi < 10000*ONE_BTC:
s.lstrip()
if not rJust:
s = s.strip(' ')
s = s.replace('. ', '')
return s
def coin2strNZ(nSatoshi):
""" Right-justified, minimum zeros, but with padding for alignment"""
return coin2str(nSatoshi, 8, True, 0)
def coin2strNZS(nSatoshi):
""" Right-justified, minimum zeros, stripped """
return coin2str(nSatoshi, 8, True, 0).strip()
def coin2str_approx(nSatoshi, sigfig=3):
posVal = nSatoshi
isNeg = False
if nSatoshi<0:
isNeg = True
posVal *= -1
nDig = max(round(math.log(posVal+1, 10)-0.5), 0)
nChop = max(nDig-2, 0 )
approxVal = round((10**nChop) * round(posVal / (10**nChop)))
return coin2str( (-1 if isNeg else 1)*approxVal, maxZeros=0)
def str2coin(theStr, negAllowed=True, maxDec=8, roundHighPrec=True):
coinStr = str(theStr)
if len(coinStr.strip())==0:
raise ValueError
isNeg = ('-' in coinStr)
coinStrPos = coinStr.replace('-','')
if not '.' in coinStrPos:
if not negAllowed and isNeg:
raise NegativeValueError
return (int(coinStrPos)*ONE_BTC)*(-1 if isNeg else 1)
else:
lhs,rhs = coinStrPos.strip().split('.')
if len(lhs.strip('-'))==0:
lhs='0'
if len(rhs)>maxDec and not roundHighPrec:
raise TooMuchPrecisionError
if not negAllowed and isNeg:
raise NegativeValueError
fullInt = (int(lhs + rhs[:9].ljust(9,'0')) + 5) / 10
return fullInt*(-1 if isNeg else 1)
# This is a sweet trick for create enum-like dictionaries.
# Either automatically numbers (*args), or name-val pairs (**kwargs)
#http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
# Some useful constants to be used throughout everything
BASE58CHARS = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
BASE16CHARS = '0123 4567 89ab cdef'.replace(' ','')
LITTLEENDIAN = '<';
BIGENDIAN = '>';
NETWORKENDIAN = '!';
ONE_BTC = long(100000000)
CENT = long(1000000)
UNINITIALIZED = None
UNKNOWN = -2
MIN_TX_FEE = 50000
MIN_RELAY_TX_FEE = 10000
MT_WAIT_TIMEOUT_SEC = 10;
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
KILOBYTE = 1024.0
MEGABYTE = 1024*KILOBYTE
GIGABYTE = 1024*MEGABYTE
TERABYTE = 1024*GIGABYTE
PETABYTE = 1024*TERABYTE
# 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)'], \