forked from etotheipi/BitcoinArmory
-
Notifications
You must be signed in to change notification settings - Fork 11
/
armoryengine.py
9825 lines (8196 loc) · 363 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-2012, 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
# Orig Date: 20 November, 2011
# Descr: This file serves as an engine for python-based Bitcoin software.
# I forked this from my own project -- PyBtcEngine -- because I
# I needed to start including/rewriting code to use CppBlockUtils
# but did not want to break the pure-python-ness of PyBtcEngine.
# If you are interested in in a pure-python set of bitcoin utils
# please go checkout the PyBtcEngine github project.
#
# Of course, the biggest advatage here is that you have access to
# the blockchain through BlockObj/BlockObjRef/BlockUtils, as found
# in the CppForSWIG directory. This is available in PyBtcEngine,
# but I had to split out the modules, and I didn't have a good way
# to maintain the pure-python module while also implementing all
# the great SWIG-imported C++ utilities I built.
#
# This module replaces the ECDSA operations, with faster ones
# implemented in C++ from Crypto++. This also enables the ability
# to use SecureBinaryData objects for moving around private keys,
# though I'm not entirely clear if python-based memory management
# is going to properly clean up after itself, even with a page-
# locked, self-destructing data container.
#
#
################################################################################
# Version Numbers
BTCARMORY_VERSION = (0, 82, 4, 0) # (Major, Minor, Minor++, even-more-minor)
PYBTCWALLET_VERSION = (1, 35, 0, 0) # (Major, Minor, Minor++, even-more-minor)
ARMORY_DONATION_ADDR = '1ArmoryXcfq7TnCSuZa9fQjRYwJ4bkRKfv'
import copy
import hashlib
import random
import time
import os
import string
import sys
import shutil
import math
import logging
import logging.handlers
import ast
import traceback
from struct import pack, unpack
from datetime import datetime
import ConfigParser
import json
from sys import argv
import colordefs
import optparse
parser = optparse.OptionParser(usage="%prog [options]\n")
#parser.add_option("--host", dest="host", default="127.0.0.1",
#help="IP/hostname to connect to (default: %default)")
#parser.add_option("--port", dest="port", default="8333", type="int",
#help="port to connect to (default: %default)")
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("--testnet", dest="testnet", action="store_true", default=False,
help="Use the testnet protocol")
parser.add_option("--offline", dest="offline", action="store_true", default=False,
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 comm between Armory instances")
parser.add_option("--debug", dest="doDebug", action="store_true", default=False,
help="Increase amount of debugging output")
parser.add_option("--nologging", dest="logDisable", action="store_true", default=False,
help="Disable all logging")
#parser.add_option("--logcpp", dest="logcpp", action="store_true", default=False,
#help="Log C++/SWIG console output by redirecting *all* stdout to log file")
parser.add_option("--netlog", dest="netlog", action="store_true", default=False,
help="Log networking messages sent and received by Armory")
(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])
print '********************************************************************************'
print 'Loading Armory Engine:'
print ' Armory Version: ', getVersionString(BTCARMORY_VERSION)
print ' PyBtcWallet Version:', getVersionString(PYBTCWALLET_VERSION)
# 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 = ''
USER_HOME_DIR = ''
BTC_HOME_DIR = ''
ARMORY_HOME_DIR = ''
SUBDIR = 'testnet3' if USE_TESTNET else ''
if OS_WINDOWS:
OS_NAME = 'Windows'
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'
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:
OS_NAME = 'Mac/OSX'
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
if CLI_OPTIONS.settingsPath.lower()=='default':
CLI_OPTIONS.settingsPath = os.path.join(ARMORY_HOME_DIR, 'ArmorySettings.txt')
SETTINGS_PATH = CLI_OPTIONS.settingsPath
ARMORY_LOG_FILE = os.path.join(ARMORY_HOME_DIR, 'armorylog.txt')
print 'Detected Operating system:', OS_NAME
print ' User home-directory :', USER_HOME_DIR
print ' Satoshi BTC directory :', BTC_HOME_DIR
print ' Armory home dir :', ARMORY_HOME_DIR
if ARMORY_HOME_DIR and not os.path.exists(ARMORY_HOME_DIR):
os.makedirs(ARMORY_HOME_DIR)
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 BadInputError(Exception): pass
class BadURIError(Exception): pass
class CompressedKeyError(Exception): pass
##### MAIN NETWORK IS DEFAULT #####
if not USE_TESTNET:
# TODO: The testnet genesis tx hash can't be the same...?
BITCOIN_PORT = 8333
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'
else:
BITCOIN_PORT = 18333
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'
BLOCKCHAINS = {}
BLOCKCHAINS['\xf9\xbe\xb4\xd9'] = "Main Network"
BLOCKCHAINS['\xfa\xbf\xb5\xda'] = "Test Network"
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:
# 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 100 kB
chopLogFile(ARMORY_LOG_FILE, 100*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):
strList = traceback.format_exception(type,value,tback)
LOGERROR(''.join([s for s in strList]))
# then call the default handler
sys.__excepthook__(type, value, tback)
sys.excepthook = logexcept_override
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(' User home-directory : ' + USER_HOME_DIR)
LOGINFO(' Satoshi BTC directory : ' + BTC_HOME_DIR)
LOGINFO(' Armory home dir : ' + ARMORY_HOME_DIR)
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 coin2strX(color, nSatoshi, ndec=8, rJust=False, maxZeros=8):
if color < 0:
unit = ONE_BTC
else:
cd = color_definitions[color]
unit = int(cd[1].get('unit', 1))
magn = int(math.ceil(math.log10(unit)))
maxZeros = min(magn, maxZeros)
ndec = min(magn, ndec)
return coin2strB(unit, nSatoshi, ndec, rJust, maxZeros)
def coin2str(nSatoshi, ndec=8, rJust=False, maxZeros=8):
return coin2strB(ONE_BTC, nSatoshi, ndec, rJust, maxZeros)
def coin2strB(unit, nSatoshi, ndec=8, rJust=False, 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(unit)
s = '0.0'
if ndec==8: s = '%0.8f' % (nBtc,)
elif ndec==7: s = '%0.7f' % (nBtc,)
elif ndec==6: s = '%0.6f' % (nBtc,)
elif ndec==5: s = '%0.5f' % (nBtc,)
elif ndec==4: s = '%0.4f' % (nBtc,)
elif ndec==3: s = '%0.3f' % (nBtc,)
elif ndec==2: s = '%0.2f' % (nBtc,)
elif ndec==1: s = '%0.1f' % (nBtc,)
elif ndec==0: s = '%0.0f' % (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 not rJust:
s = s.strip(' ')
s = s.replace('. ',' ')
return s
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)
# 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)
def str2coin(coinStr):
if not '.' in coinStr:
return int(coinStr)*ONE_BTC
else:
lhs,rhs = coinStr.split('.')
return int(lhs)*ONE_BTC + int(rhs.ljust(8,'0'))
# 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
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
# 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'] ]
# Some time methods (RightNow() return local unix timestamp)
RightNow = time.time
def RightNowUTC():
return time.mktime(time.gmtime(RightNow()))
################################################################################
# Load the C++ utilites here
#
# The SWIG/C++ block utilities give us access to the blockchain, fast ECDSA
# operations, and general encryption/secure-binary containers
################################################################################
try:
import CppBlockUtils as Cpp
from CppBlockUtils import KdfRomix, CryptoECDSA, CryptoAES, SecureBinaryData
LOGINFO('C++ block utilities loaded successfully')
except:
LOGCRIT('C++ block utilities not available.')
LOGCRIT(' Make sure that you have the SWIG-compiled modules')
LOGCRIT(' in the current directory (or added to the PATH)')
LOGCRIT(' Specifically, you need:')
LOGCRIT(' CppBlockUtils.py and')
if OS_LINUX or OS_MACOSX:
LOGCRIT(' _CppBlockUtils.so')
elif OS_WINDOWS:
LOGCRIT(' _CppBlockUtils.pyd')
else:
LOGCRIT('\n\n... UNKNOWN operating system')
raise
################################################################################
# Might as well create the BDM right here -- there will only ever be one, anyway
TheBDM = Cpp.BlockDataManager().getBDM()
_TheMain = None
def engine_set_main(main):
global _TheMain
_TheMain = main
def get_main():
return _TheMain
DATATYPE = enum("Binary", 'Base58', 'Hex')
def isLikelyDataType(theStr, dtype=None):
"""
This really shouldn't be used on short strings. Hence
why it's called "likely" datatype...
"""
ret = None
hexCount = sum([1 if c in BASE16CHARS else 0 for c in theStr])
b58Count = sum([1 if c in BASE58CHARS else 0 for c in theStr])
canBeHex = hexCount==len(theStr)
canBeB58 = b58Count==len(theStr)
if canBeHex:
ret = DATATYPE.Hex
elif canBeB58 and not canBeHex:
ret = DATATYPE.Base58
else:
ret = DATATYPE.Binary
if dtype==None:
return ret
else:
return dtype==ret
def getCurrTimeAndBlock():
time0 = long(RightNowUTC())
if TheBDM.isInitialized():
return (time0, TheBDM.getTopBlockHeader().getBlockHeight())
else:
return (time0, UINT32_MAX)
# Define all the hashing functions we're going to need. We don't actually
# use any of the first three directly (sha1, sha256, ripemd160), we only
# use hash256 and hash160 which use the first three to create the ONLY hash
# operations we ever do in the bitcoin network
# UPDATE: mini-private-key format requires vanilla sha256...
def sha1(bits):
return hashlib.new('sha1', bits).digest()
def sha256(bits):
return hashlib.new('sha256', bits).digest()
def sha512(bits):
return hashlib.new('sha512', bits).digest()
def ripemd160(bits):
# It turns out that not all python has ripemd160...?
#return hashlib.new('ripemd160', bits).digest()
return Cpp.BtcUtils().ripemd160_SWIG(bits)
def hash256(s):
""" Double-SHA256 """
return sha256(sha256(s))
def hash160(s):
""" RIPEMD160( SHA256( binaryStr ) ) """
return Cpp.BtcUtils().getHash160_SWIG(s)
################################################################################
def prettyHex(theStr, indent='', withAddr=True, major=8, minor=8):
"""
This is the same as pprintHex(), but returns the string instead of
printing it to console. This is useful for redirecting output to
files, or doing further modifications to the data before display
"""
outStr = ''
sz = len(theStr)
nchunk = int((sz-1)/minor) + 1;
for i in range(nchunk):
if i%major==0:
outStr += '\n' + indent
if withAddr:
locStr = int_to_hex(i*minor/2, widthBytes=2, endOut=BIGENDIAN)
outStr += '0x' + locStr + ': '
outStr += theStr[i*minor:(i+1)*minor] + ' '
return outStr
################################################################################
def pprintHex(theStr, indent='', withAddr=True, major=8, minor=8):
"""
This method takes in a long hex string and prints it out into rows
of 64 hex chars, in chunks of 8 hex characters, and with address
markings on each row. This means that each row displays 32 bytes,
which is usually pleasant.
The format is customizable: you can adjust the indenting of the
entire block, remove address markings, or change the major/minor
grouping size (major * minor = hexCharsPerRow)
"""
print prettyHex(theStr, indent, withAddr, major, minor)
def pprintDiff(str1, str2, indent=''):
if not len(str1)==len(str2):
print 'pprintDiff: Strings are different length!'
return
byteDiff = []
for i in range(len(str1)):
if str1[i]==str2[i]:
byteDiff.append('-')
else:
byteDiff.append('X')
pprintHex(''.join(byteDiff), indent=indent)
##### Switch endian-ness #####
def hex_switchEndian(s):
""" Switches the endianness of a hex string (in pairs of hex chars) """
pairList = [s[i]+s[i+1] for i in xrange(0,len(s),2)]
return ''.join(pairList[::-1])
def binary_switchEndian(s):
""" Switches the endianness of a binary string """
return s[::-1]
##### INT/HEXSTR #####
def int_to_hex(i, widthBytes=0, endOut=LITTLEENDIAN):
"""
Convert an integer (int() or long()) to hexadecimal. Default behavior is
to use the smallest even number of hex characters necessary, and using
little-endian. Use the widthBytes argument to add 0-padding where needed
if you are expecting constant-length output.
"""
h = hex(i)[2:]
if isinstance(i,long):
h = h[:-1]
if len(h)%2 == 1:
h = '0'+h
if not widthBytes==0:
nZero = 2*widthBytes - len(h)
if nZero > 0:
h = '0'*nZero + h
if endOut==LITTLEENDIAN:
h = hex_switchEndian(h)
return h
def hex_to_int(h, endIn=LITTLEENDIAN):
"""
Convert hex-string to integer (or long). Default behavior is to interpret
hex string as little-endian
"""
hstr = h[:] # copies data, no references
if endIn==LITTLEENDIAN:
hstr = hex_switchEndian(hstr)
return( int(hstr, 16) )
##### HEXSTR/BINARYSTR #####
def hex_to_binary(h, endIn=LITTLEENDIAN, endOut=LITTLEENDIAN):
"""
Converts hexadecimal to binary (in a python string). Endianness is
only switched if (endIn != endOut)
"""
bout = h[:] # copies data, no references
if not endIn==endOut:
bout = hex_switchEndian(bout)
return bout.decode('hex_codec')
def binary_to_hex(b, endOut=LITTLEENDIAN, endIn=LITTLEENDIAN):
"""
Converts binary to hexadecimal. Endianness is only switched
if (endIn != endOut)
"""
hout = b.encode('hex_codec')
if not endOut==endIn:
hout = hex_switchEndian(hout)
return hout
##### INT/BINARYSTR #####
def int_to_binary(i, widthBytes=0, endOut=LITTLEENDIAN):
"""
Convert integer to binary. Default behavior is use as few bytes
as necessary, and to use little-endian. This can be changed with
the two optional input arguemnts.
"""
h = int_to_hex(i,widthBytes)
return hex_to_binary(h, endOut=endOut)
def binary_to_int(b, endIn=LITTLEENDIAN):
"""
Converts binary to integer (or long). Interpret as LE by default
"""
h = binary_to_hex(b, endIn, LITTLEENDIAN)
return hex_to_int(h)
##### INT/BITS #####
def int_to_bitset(i, widthBytes=0):
bitsOut = []
while i>0:
i,r = divmod(i,2)
bitsOut.append(['0','1'][r])
result = ''.join(bitsOut)
if widthBytes != 0:
result = result.ljust(widthBytes*8,'0')
return result
def bitset_to_int(bitset):
n = 0
for i,bit in enumerate(bitset):
n += (0 if bit=='0' else 1) * 2**i
return n
EmptyHash = hex_to_binary('00'*32)
################################################################################
# BINARY/BASE58 CONVERSIONS
def binary_to_base58(binstr):
"""
This method applies the Bitcoin-specific conversion from binary to Base58
which may includes some extra "zero" bytes, such as is the case with the
main-network addresses.
This method is labeled as outputting an "addrStr", but it's really this
special kind of Base58 converter, which makes it usable for encoding other
data, such as ECDSA keys or scripts.
"""
padding = 0;
for b in binstr:
if b=='\x00':
padding+=1
else:
break
n = 0
for ch in binstr:
n *= 256
n += ord(ch)
b58 = ''
while n > 0:
n, r = divmod (n, 58)
b58 = BASE58CHARS[r] + b58
return '1'*padding + b58
################################################################################
def base58_to_binary(addr):
"""
This method applies the Bitcoin-specific conversion from Base58 to binary
which may includes some extra "zero" bytes, such as is the case with the
main-network addresses.
This method is labeled as inputting an "addrStr", but it's really this
special kind of Base58 converter, which makes it usable for encoding other
data, such as ECDSA keys or scripts.
"""
# Count the zeros ('1' characters) at the beginning
padding = 0;
for c in addr:
if c=='1':
padding+=1
else:
break
n = 0
for ch in addr:
n *= 58
n += BASE58CHARS.index(ch)
binOut = ''
while n>0:
d,m = divmod(n,256)
binOut = chr(m) + binOut
n = d
return '\x00'*padding + binOut
################################################################################
def hash160_to_addrStr(binStr):
"""
Converts the 20-byte pubKeyHash to 25-byte binary Bitcoin address
which includes the network byte (prefix) and 4-byte checksum (suffix)
"""
addr21 = ADDRBYTE + binStr
addr25 = addr21 + hash256(addr21)[:4]
return binary_to_base58(addr25);
################################################################################
def addrStr_to_hash160(binStr):
return base58_to_binary(binStr)[1:-4]
##### FLOAT/BTC #####
# https://en.bitcoin.it/wiki/Proper_Money_Handling_(JSON-RPC)
def ubtc_to_floatStr(n):
return '%d.%08d' % divmod (n, ONE_BTC)
def floatStr_to_ubtc(s):
return long(round(float(s) * ONE_BTC))
def float_to_btc (f):
return long (round(f * ONE_BTC))