-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathnpwb.py
3823 lines (3302 loc) · 122 KB
/
npwb.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
#!/usr/bin/env python
# This is an experimental version, please use it with care
#
# jackjack's npw.py
# https://github.com/jackjack-jj/npw
# Released under GPLv3
#
import sys,time,os,base64,random,struct,platform
import threading
from getpass import getpass
import hashlib
from datetime import datetime
import urllib2
def randomk():
return long(os.urandom(32).encode('hex'),16)
def sqrt_mod(a, p):
return pow(a, (p+1)/4, p)
def verify_message_Bitcoin(address, signature, message, pureECDSASigning=False):
networkversion=str_to_long(b58decode(address, None)) >> (8*24)
msg=message
if not pureECDSASigning:
msg=Hash(format_msg_to_sign(message))
compressed=False
curve = curve_secp256k1
G = generator_secp256k1
_a,_b,_p=curve.a(),curve.b(),curve.p()
order = G.order()
sig = base64.b64decode(signature)
if len(sig) != 65:
raise Exception("vmB","Bad signature")
hb = ord(sig[0])
r,s = map(str_to_long,[sig[1:33],sig[33:65]])
if hb < 27 or hb >= 35:
raise Exception("vmB","Bad first byte")
if hb >= 31:
compressed = True
hb -= 4
recid = hb - 27
x = (r + (recid/2) * order) % _p
y2 = ( pow(x,3,_p) + _a*x + _b ) % _p
yomy = sqrt_mod(y2, _p)
if (yomy - recid) % 2 == 0:
y=yomy
else:
y=_p - yomy
R = Point(curve, x, y, order)
e = str_to_long(msg)
minus_e = -e % order
inv_r = inverse_mod(r,order)
Q = inv_r * ( R*s + G*minus_e )
public_key = Public_key(G, Q, compressed)
addr = public_key_to_bc_address(public_key.ser(), networkversion)
if address != addr:
raise Exception("vmB","Bad address. Signing: %s, received: %s"%(addr,address))
def sign_message(secret, message, pureECDSASigning=False):
if len(secret) == 32:
pkey = EC_KEY(str_to_long(secret))
compressed = False
elif len(secret) == 33:
pkey = EC_KEY(str_to_long(secret[:-1]))
secret=secret[:-1]
compressed = True
else:
raise Exception("sm","Bad private key size (%d)"%len(secret))
msg=message
if not pureECDSASigning:
msg=Hash(format_msg_to_sign(message))
eckey = EC_KEY(str_to_long(secret), compressed)
private_key = eckey.privkey
public_key = eckey.pubkey
addr = public_key_to_bc_address(GetPubKey(eckey,eckey.pubkey.compressed))
sig = private_key.sign(msg, randomk())
if not public_key.verify(msg, sig):
raise Exception("sm","Problem signing message")
return [sig,addr,compressed,public_key]
def sign_message_Bitcoin(secret, msg, pureECDSASigning=False):
sig,addr,compressed,public_key=sign_message(secret, msg, pureECDSASigning)
for i in range(4):
hb=27+i
if compressed:
hb+=4
sign=base64.b64encode(chr(hb)+sig.ser())
try:
verify_message_Bitcoin(addr, sign, msg, pureECDSASigning)
return {'address':addr, 'b64-signature':sign, 'signature':chr(hb)+sig.ser(), 'message':msg}
except Exception as e:
# print e.args
pass
raise Exception("smB","Unable to construct recoverable key")
def FormatText(t, sigctx, verbose=False): #sigctx: False=what is displayed, True=what is signed
r=''
te=t.split('\n')
for l in te:
while len(l) and l[len(l)-1] in [' ', '\t', chr(9)]:
l=l[:-1]
if not len(l) or l[len(l)-1]!='\r':
l+='\r'
if not sigctx:
if len(l) and l[0]=='-':
l='- '+l[1:]
r+=l+'\n'
r=r[:-2]
global FTVerbose
if FTVerbose:
print ' -- Sent: '+t.encode('hex')
if sigctx:
print ' -- Signed: '+r.encode('hex')
else:
print ' -- Displayed: '+r.encode('hex')
return r
def crc24(m):
INIT = 0xB704CE
POLY = 0x1864CFB
crc = INIT
r = ''
for o in m:
o=ord(o)
crc ^= (o << 16)
for i in xrange(8):
crc <<= 1
if crc & 0x1000000:
crc ^= POLY
for i in range(3):
r += chr( ( crc & (0xff<<(8*i))) >> (8*i) )
return r
def chunks(t, n):
return [t[i:i+n] for i in range(0, len(t), n)]
def ASCIIArmory(block, name):
r='-----BEGIN '+name+'-----\r\n'
r+='\r\n'.join(chunks(base64.b64encode(block), 64))+'\r\n='
r+=base64.b64encode(crc24(block))+'\r\n'
r+='-----END '+name+'-----'
return r
#==============================================
def verifySignature(addr, b64sig, msg):
return verify_message_Bitcoin(addr, b64sig, FormatText(msg, True))
import os
import time
import traceback
from datetime import datetime
from bsddb.db import *
def hash_160(public_key):
md = hashlib.new('ripemd160')
md.update(hashlib.sha256(public_key).digest())
return md.digest()
def public_key_to_bc_address(public_key, v=None):
if v==None:
v=addrtype
h160 = hash_160(public_key)
return hash_160_to_bc_address(h160, v)
def hash_160_to_bc_address(h160, v=None):
if v==None:
v=addrtype
vh160 = chr(v) + h160
h = Hash(vh160)
addr = vh160 + h[0:4]
return b58encode(addr)
def bc_address_to_hash_160(addr):
bytes = b58decode(addr, 25)
return bytes[1:21]
__b58chars = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
__b58base = len(__b58chars)
def b58encode(v):
""" encode v, which is a string of bytes, to base58.
"""
long_value = 0L
for (i, c) in enumerate(v[::-1]):
long_value += (256**i) * ord(c)
result = ''
while long_value >= __b58base:
div, mod = divmod(long_value, __b58base)
result = __b58chars[mod] + result
long_value = div
result = __b58chars[long_value] + result
# Bitcoin does a little leading-zero-compression:
# leading 0-bytes in the input become leading-1s
nPad = 0
for c in v:
if c == '\0': nPad += 1
else: break
return (__b58chars[0]*nPad) + result
def b58decode(v, length):
""" decode v into a string of len bytes
"""
long_value = 0L
for (i, c) in enumerate(v[::-1]):
long_value += __b58chars.find(c) * (__b58base**i)
result = ''
while long_value >= 256:
div, mod = divmod(long_value, 256)
result = chr(mod) + result
long_value = div
result = chr(long_value) + result
nPad = 0
for c in v:
if c == __b58chars[0]: nPad += 1
else: break
result = chr(0)*nPad + result
if length is not None and len(result) != length:
return None
return result
# end of bitcointools base58 implementation
# address handling code
def long_hex(bytes):
return bytes.encode('hex_codec')
def Hash(data):
return hashlib.sha256(hashlib.sha256(data).digest()).digest()
def EncodeBase58Check(secret):
hash = Hash(secret)
return b58encode(secret + hash[0:4])
def DecodeBase58Check(sec):
vchRet = b58decode(sec, None)
secret = vchRet[0:-4]
csum = vchRet[-4:]
hash = Hash(secret)
cs32 = hash[0:4]
if cs32 != csum:
return None
else:
return secret
def str_to_long(b):
res = 0
pos = 1
for a in reversed(b):
res += ord(a) * pos
pos *= 256
return res
def PrivKeyToSecret(privkey):
if len(privkey) == 279:
return privkey[9:9+32]
else:
return privkey[8:8+32]
def SecretToASecret(secret, compressed=False):
prefix = chr((addrtype+128)&255)
if addrtype==48: #assuming Litecoin
prefix = chr(128)
vchIn = prefix + secret
if compressed: vchIn += '\01'
return EncodeBase58Check(vchIn)
def ASecretToSecret(sec):
vch = DecodeBase58Check(sec)
if not vch:
return False
if vch[0] != chr((addrtype+128)&255):
print 'Warning: adress prefix seems bad (%d vs %d)'%(ord(vch[0]), (addrtype+128)&255)
return vch[1:]
def regenerate_key(sec):
b = ASecretToSecret(sec)
if not b:
return False
b = b[0:32]
secret = int('0x' + b.encode('hex'), 16)
return EC_KEY(secret)
def GetPubKey(pkey, compressed=False):
return i2o_ECPublicKey(pkey, compressed)
def GetPrivKey(pkey, compressed=False):
return i2d_ECPrivateKey(pkey, compressed)
def GetSecret(pkey):
return ('%064x' % pkey.secret).decode('hex')
def is_compressed(sec):
b = ASecretToSecret(sec)
return len(b) == 33
# bitcointools wallet.dat handling code
def create_env(db_dir):
db_env = DBEnv(0)
r = db_env.open(db_dir, (DB_CREATE|DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_MPOOL|DB_INIT_TXN|DB_THREAD|DB_RECOVER))
return db_env
def parse_CAddress(vds):
d = {'ip':'0.0.0.0','port':0,'nTime': 0}
try:
d['nVersion'] = vds.read_int32()
d['nTime'] = vds.read_uint32()
d['nServices'] = vds.read_uint64()
d['pchReserved'] = vds.read_bytes(12)
d['ip'] = socket.inet_ntoa(vds.read_bytes(4))
d['port'] = vds.read_uint16()
except:
pass
return d
def deserialize_CAddress(d):
return d['ip']+":"+str(d['port'])
def parse_BlockLocator(vds):
d = { 'hashes' : [] }
nHashes = vds.read_compact_size()
for i in xrange(nHashes):
d['hashes'].append(vds.read_bytes(32))
return d
def deserialize_BlockLocator(d):
result = "Block Locator top: "+d['hashes'][0][::-1].encode('hex_codec')
return result
def parse_setting(setting, vds):
if setting[0] == "f": # flag (boolean) settings
return str(vds.read_boolean())
elif setting[0:4] == "addr": # CAddress
d = parse_CAddress(vds)
return deserialize_CAddress(d)
elif setting == "nTransactionFee":
return vds.read_int64()
elif setting == "nLimitProcessors":
return vds.read_int32()
return 'unknown setting'
class SerializationError(Exception):
""" Thrown when there's a problem deserializing or serializing """
class BCDataStream(object):
def __init__(self):
self.input = None
self.read_cursor = 0
def clear(self):
self.input = None
self.read_cursor = 0
def write(self, bytes): # Initialize with string of bytes
if self.input is None:
self.input = bytes
else:
self.input += bytes
def map_file(self, file, start): # Initialize with bytes from file
self.input = mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ)
self.read_cursor = start
def seek_file(self, position):
self.read_cursor = position
def close_file(self):
self.input.close()
def read_string(self):
# Strings are encoded depending on length:
# 0 to 252 : 1-byte-length followed by bytes (if any)
# 253 to 65,535 : byte'253' 2-byte-length followed by bytes
# 65,536 to 4,294,967,295 : byte '254' 4-byte-length followed by bytes
# ... and the Bitcoin client is coded to understand:
# greater than 4,294,967,295 : byte '255' 8-byte-length followed by bytes of string
# ... but I don't think it actually handles any strings that big.
if self.input is None:
raise SerializationError("call write(bytes) before trying to deserialize")
try:
length = self.read_compact_size()
except IndexError:
raise SerializationError("attempt to read past end of buffer")
return self.read_bytes(length)
def write_string(self, string):
# Length-encoded as with read-string
self.write_compact_size(len(string))
self.write(string)
def read_bytes(self, length):
try:
result = self.input[self.read_cursor:self.read_cursor+length]
self.read_cursor += length
return result
except IndexError:
raise SerializationError("attempt to read past end of buffer")
return ''
def read_boolean(self): return self.read_bytes(1)[0] != chr(0)
def read_int16(self): return self._read_num('<h')
def read_uint16(self): return self._read_num('<H')
def read_int32(self): return self._read_num('<i')
def read_uint32(self): return self._read_num('<I')
def read_int64(self): return self._read_num('<q')
def read_uint64(self): return self._read_num('<Q')
def write_boolean(self, val): return self.write(chr(bool_to_int(val)))
def write_int16(self, val): return self._write_num('<h', val)
def write_uint16(self, val): return self._write_num('<H', val)
def write_int32(self, val): return self._write_num('<i', val)
def write_uint32(self, val): return self._write_num('<I', val)
def write_int64(self, val): return self._write_num('<q', val)
def write_uint64(self, val): return self._write_num('<Q', val)
def read_compact_size(self):
size = ord(self.input[self.read_cursor])
self.read_cursor += 1
if size == 253:
size = self._read_num('<H')
elif size == 254:
size = self._read_num('<I')
elif size == 255:
size = self._read_num('<Q')
return size
def write_compact_size(self, size):
if size < 0:
raise SerializationError("attempt to write size < 0")
elif size < 253:
self.write(chr(size))
elif size < 2**16:
self.write('\xfd')
self._write_num('<H', size)
elif size < 2**32:
self.write('\xfe')
self._write_num('<I', size)
elif size < 2**64:
self.write('\xff')
self._write_num('<Q', size)
def _read_num(self, format):
(i,) = struct.unpack_from(format, self.input, self.read_cursor)
self.read_cursor += struct.calcsize(format)
return i
def _write_num(self, format, num):
s = struct.pack(format, num)
self.write(s)
def random_string(l, alph="0123456789abcdef"):
r=""
la=len(alph)
for i in range(l):
r+=alph[int(la*(random.random()))]
return r
def iais(a):
if a>= 2:
return 's'
else:
return ''
def aversions(n):
return 'Version '+str(n)
###################################
# pywallet crypter implementation #
###################################
crypter = None
try:
from Crypto.Cipher import AES
crypter = 'pycrypto'
except:
pass
class Crypter_pycrypto( object ):
def SetKeyFromPassphrase(self, vKeyData, vSalt, nDerivIterations, nDerivationMethod):
if nDerivationMethod != 0:
return 0
data = vKeyData + vSalt
for i in xrange(nDerivIterations):
data = hashlib.sha512(data).digest()
self.SetKey(data[0:32])
self.SetIV(data[32:32+16])
return len(data)
def SetKey(self, key):
self.chKey = key
def SetIV(self, iv):
self.chIV = iv[0:16]
def Encrypt(self, data):
return AES.new(self.chKey,AES.MODE_CBC,self.chIV).encrypt(data)[0:32]
def Decrypt(self, data):
return AES.new(self.chKey,AES.MODE_CBC,self.chIV).decrypt(data)[0:32]
try:
if not crypter:
import ctypes
import ctypes.util
module_ssl = ctypes.cdll.LoadLibrary (ctypes.util.find_library ('ssl') or 'libeay32')
crypter = 'ssl'
except:
pass
class Crypter_ssl(object):
def __init__(self):
self.chKey = ctypes.create_string_buffer (32)
self.chIV = ctypes.create_string_buffer (16)
def SetKeyFromPassphrase(self, vKeyData, vSalt, nDerivIterations, nDerivationMethod):
if nDerivationMethod != 0:
return 0
strKeyData = ctypes.create_string_buffer (vKeyData)
chSalt = ctypes.create_string_buffer (vSalt)
return module_ssl.EVP_BytesToKey(module_ssl.EVP_aes_256_cbc(), module_ssl.EVP_sha512(), chSalt, strKeyData,
len(vKeyData), nDerivIterations, ctypes.byref(self.chKey), ctypes.byref(self.chIV))
def SetKey(self, key):
self.chKey = ctypes.create_string_buffer(key)
def SetIV(self, iv):
self.chIV = ctypes.create_string_buffer(iv)
def Encrypt(self, data):
buf = ctypes.create_string_buffer(len(data) + 16)
written = ctypes.c_int(0)
final = ctypes.c_int(0)
ctx = module_ssl.EVP_CIPHER_CTX_new()
module_ssl.EVP_CIPHER_CTX_init(ctx)
module_ssl.EVP_EncryptInit_ex(ctx, module_ssl.EVP_aes_256_cbc(), None, self.chKey, self.chIV)
module_ssl.EVP_EncryptUpdate(ctx, buf, ctypes.byref(written), data, len(data))
output = buf.raw[:written.value]
module_ssl.EVP_EncryptFinal_ex(ctx, buf, ctypes.byref(final))
output += buf.raw[:final.value]
return output
def Decrypt(self, data):
buf = ctypes.create_string_buffer(len(data) + 16)
written = ctypes.c_int(0)
final = ctypes.c_int(0)
ctx = module_ssl.EVP_CIPHER_CTX_new()
module_ssl.EVP_CIPHER_CTX_init(ctx)
module_ssl.EVP_DecryptInit_ex(ctx, module_ssl.EVP_aes_256_cbc(), None, self.chKey, self.chIV)
module_ssl.EVP_DecryptUpdate(ctx, buf, ctypes.byref(written), data, len(data))
output = buf.raw[:written.value]
module_ssl.EVP_DecryptFinal_ex(ctx, buf, ctypes.byref(final))
output += buf.raw[:final.value]
return output
class Crypter_pure(object):
def __init__(self):
self.m = AESModeOfOperation()
self.cbc = self.m.modeOfOperation["CBC"]
self.sz = self.m.aes.keySize["SIZE_256"]
def SetKeyFromPassphrase(self, vKeyData, vSalt, nDerivIterations, nDerivationMethod):
if nDerivationMethod != 0:
return 0
data = vKeyData + vSalt
for i in xrange(nDerivIterations):
data = hashlib.sha512(data).digest()
self.SetKey(data[0:32])
self.SetIV(data[32:32+16])
return len(data)
def SetKey(self, key):
self.chKey = [ord(i) for i in key]
def SetIV(self, iv):
self.chIV = [ord(i) for i in iv]
def Encrypt(self, data):
mode, size, cypher = self.m.encrypt(data, self.cbc, self.chKey, self.sz, self.chIV)
return ''.join(map(chr, cypher))
def Decrypt(self, data):
chData = [ord(i) for i in data]
return self.m.decrypt(chData, self.sz, self.cbc, self.chKey, self.sz, self.chIV)
if crypter == 'pycrypto':
crypter = Crypter_pycrypto()
# print "Crypter: pycrypto"
elif crypter == 'ssl':
crypter = Crypter_ssl()
# print "Crypter: ssl"
else:
crypter = Crypter_pure()
# print "Crypter: pure"
logging.warning("pycrypto or libssl not found, decryption may be slow")
##########################################
# end of pywallet crypter implementation #
##########################################
def npw_update_wallet(db, types, datas, paramsAreLists=False):
"""Write a single item to the wallet.
db must be open with writable=True.
type and data are the type code and data dictionary as parse_wallet would
give to item_callback.
data's __key__, __value__ and __type__ are ignored; only the primary data
fields are used.
"""
if not paramsAreLists:
types=[types]
datas=[datas]
if len(types)!=len(datas):
raise Exception("UpdateWallet: sizes are different")
for it,type in enumerate(types):
data=datas[it]
d = data
kds = BCDataStream()
vds = BCDataStream()
# Write the type code to the key
kds.write_string(type)
vds.write("") # Ensure there is something
try:
if type == "tx":
# raise NotImplementedError("Writing items of type 'tx'")
kds.write(d['txi'][6:].decode('hex_codec'))
vds.write(d['txv'].decode('hex_codec'))
elif type == "name":
kds.write_string(d['hash'])
vds.write_string(d['name'])
elif type == "version":
vds.write_uint32(d['version'])
elif type == "minversion":
vds.write_uint32(d['minversion'])
elif type == "setting":
raise NotImplementedError("Writing items of type 'setting'")
kds.write_string(d['setting'])
#d['value'] = parse_setting(d['setting'], vds)
elif type == "key":
kds.write_string(d['public_key'])
vds.write_string(d['private_key'])
elif type == "wkey":
kds.write_string(d['public_key'])
vds.write_string(d['private_key'])
vds.write_int64(d['created'])
vds.write_int64(d['expires'])
vds.write_string(d['comment'])
elif type == "defaultkey":
vds.write_string(d['key'])
elif type == "pool":
kds.write_int64(d['n'])
vds.write_int32(d['nVersion'])
vds.write_int64(d['nTime'])
vds.write_string(d['public_key'])
elif type == "acc":
kds.write_string(d['account'])
vds.write_int32(d['nVersion'])
vds.write_string(d['public_key'])
elif type == "acentry":
kds.write_string(d['account'])
kds.write_uint64(d['n'])
vds.write_int32(d['nVersion'])
vds.write_int64(d['nCreditDebit'])
vds.write_int64(d['nTime'])
vds.write_string(d['otherAccount'])
vds.write_string(d['comment'])
elif type == "bestblock":
vds.write_int32(d['nVersion'])
vds.write_compact_size(len(d['hashes']))
for h in d['hashes']:
vds.write(h)
elif type == "ckey":
kds.write_string(d['public_key'])
vds.write_string(d['encrypted_private_key'])
elif type == "mkey":
kds.write_uint32(d['nID'])
vds.write_string(d['encrypted_key'])
vds.write_string(d['salt'])
vds.write_uint32(d['nDerivationMethod'])
vds.write_uint32(d['nDerivationIterations'])
vds.write_string(d['otherParams'])
else:
print "Unknown key type: "+type
# Write the key/value pair to the database
db.put(kds.input, vds.input)
except Exception, e:
print("ERROR writing to wallet.dat, type %s"%type)
print("data dictionary: %r"%data)
traceback.print_exc()
def is_compressed(sec):
b = ASecretToSecret(sec)
return len(b) == 33
def npw_import_csv_keys_to_wallet(filename, db, json_db, passphrase, fct_callback=False, nbremax=9999999):
# global global_merging_message
if filename[0]=="\x00": #yeah, dirty workaround
content=filename[1:]
else:
filen = open(filename, "r")
content = filen.read()
filen.close()
content=content.split('\n')
content=content[:min(nbremax, len(content))]
lencontent=len(content)
for i in range(lencontent):
c=content[i]
if fct_callback:
fct_callback(i, lencontent)
# global_merging_message = ["Merging: "+str(round(100.0*(i+1)/lencontent,1))+"%" for j in range(2)]
if ';' in c and len(c)>0 and c[0]!="#":
cs=c.split(';')
sec,label=cs[0:2]
v=0
if len(cs)>2:
v=int(cs[2])
reserve=False
if label=="#Reserve":
reserve=True
keyishex=None
if abs(len(sec)-65)==1:
keyishex=True
npw_importprivkey(db, json_db, sec, label, reserve, 'keyishex', False, 0, passphrase)
# global_merging_message = ["Merging done.", ""]
return True
def npw_importprivkey(db, json_db, sec, label, reserve, keyishex, verbose=True, addrv=0, passphrase=''):
if len(sec) == 64:
pkey = EC_KEY(str_to_long(sec.decode('hex')))
compressed = False
elif len(sec) == 66:
pkey = EC_KEY(str_to_long(sec[:-2].decode('hex')))
compressed = True
else:
pkey = regenerate_key(sec)
compressed = is_compressed(sec)
if not pkey:
print "Bad private key (length:"+str(len(sec))+")"
return False
secret = GetSecret(pkey)
private_key = GetPrivKey(pkey, compressed)
public_key = GetPubKey(pkey, compressed)
addr = public_key_to_bc_address(public_key, addrv)
if verbose:
print "Address (%s): %s"%(aversions(addrv), addr)
print "Privkey (%s): %s"%(aversions(addrv), SecretToASecret(secret, compressed))
print "Hexprivkey: %s"%(secret.encode('hex'))
print "Hash160: %s"%(bc_address_to_hash_160(addr).encode('hex'))
if not compressed:
print "Pubkey: 04%.64x%.64x"%(pkey.pubkey.point.x(), pkey.pubkey.point.y())
else:
print "Pubkey: 0%d%.64x"%(2+(pkey.pubkey.point.y()&1), pkey.pubkey.point.x())
if int(secret.encode('hex'), 16)>_r:
print 'Beware, 0x%s is equivalent to 0x%.33x</b>'%(secret.encode('hex'), int(secret.encode('hex'), 16)-_r)
global crypter
crypted = False
if 'mkey' in json_db.keys() and 'salt' in json_db['mkey']:
crypted = True
if crypted:
if passphrase:
cry_master = json_db['mkey']['encrypted_key'].decode('hex')
cry_salt = json_db['mkey']['salt'].decode('hex')
cry_rounds = json_db['mkey']['nDerivationIterations']
cry_method = json_db['mkey']['nDerivationMethod']
crypter.SetKeyFromPassphrase(passphrase, cry_salt, cry_rounds, cry_method)
masterkey = crypter.Decrypt(cry_master)
crypter.SetKey(masterkey)
crypter.SetIV(Hash(public_key))
e = crypter.Encrypt(secret)
ck_epk=e
npw_update_wallet(db, 'ckey', { 'public_key' : public_key, 'encrypted_private_key' : ck_epk })
else:
npw_update_wallet(db, 'key', { 'public_key' : public_key, 'private_key' : private_key })
if not reserve:
npw_update_wallet(db, 'name', { 'hash' : addr, 'name' : label })
return True
def parse_wallet(db, item_callback):
kds = BCDataStream()
vds = BCDataStream()
def parse_TxIn(vds):
d = {}
d['prevout_hash'] = vds.read_bytes(32).encode('hex')
d['prevout_n'] = vds.read_uint32()
d['scriptSig'] = vds.read_bytes(vds.read_compact_size()).encode('hex')
d['sequence'] = vds.read_uint32()
return d
def parse_TxOut(vds):
d = {}
d['value'] = vds.read_int64()/1e8
d['scriptPubKey'] = vds.read_bytes(vds.read_compact_size()).encode('hex')
return d
for (key, value) in db.items():
d = { }
kds.clear(); kds.write(key)
vds.clear(); vds.write(value)
type = kds.read_string()
d["__key__"] = key
d["__value__"] = value
d["__type__"] = type
try:
if type == "tx":
d["tx_id"] = inversetxid(kds.read_bytes(32).encode('hex_codec'))
start = vds.read_cursor
d['version'] = vds.read_int32()
n_vin = vds.read_compact_size()
d['txIn'] = []
for i in xrange(n_vin):
d['txIn'].append(parse_TxIn(vds))
n_vout = vds.read_compact_size()
d['txOut'] = []
for i in xrange(n_vout):
d['txOut'].append(parse_TxOut(vds))
d['lockTime'] = vds.read_uint32()
d['tx'] = vds.input[start:vds.read_cursor].encode('hex_codec')
d['txv'] = value.encode('hex_codec')
d['txk'] = key.encode('hex_codec')
elif type == "name":
d['hash'] = kds.read_string()
d['name'] = vds.read_string()
elif type == "version":
d['version'] = vds.read_uint32()
elif type == "minversion":
d['minversion'] = vds.read_uint32()
elif type == "setting":
d['setting'] = kds.read_string()
d['value'] = parse_setting(d['setting'], vds)
elif type == "key":
d['public_key'] = kds.read_bytes(kds.read_compact_size())
d['private_key'] = vds.read_bytes(vds.read_compact_size())
elif type == "wkey":
d['public_key'] = kds.read_bytes(kds.read_compact_size())
d['private_key'] = vds.read_bytes(vds.read_compact_size())
d['created'] = vds.read_int64()
d['expires'] = vds.read_int64()
d['comment'] = vds.read_string()
elif type == "defaultkey":
d['key'] = vds.read_bytes(vds.read_compact_size())
elif type == "pool":
d['n'] = kds.read_int64()
d['nVersion'] = vds.read_int32()
d['nTime'] = vds.read_int64()
d['public_key'] = vds.read_bytes(vds.read_compact_size())
elif type == "acc":
d['account'] = kds.read_string()
d['nVersion'] = vds.read_int32()
d['public_key'] = vds.read_bytes(vds.read_compact_size())
elif type == "acentry":
d['account'] = kds.read_string()
d['n'] = kds.read_uint64()
d['nVersion'] = vds.read_int32()
d['nCreditDebit'] = vds.read_int64()
d['nTime'] = vds.read_int64()
d['otherAccount'] = vds.read_string()
d['comment'] = vds.read_string()
elif type == "bestblock":
d['nVersion'] = vds.read_int32()
d.update(parse_BlockLocator(vds))
elif type == "ckey":
d['public_key'] = kds.read_bytes(kds.read_compact_size())
d['encrypted_private_key'] = vds.read_bytes(vds.read_compact_size())
elif type == "mkey":
d['nID'] = kds.read_uint32()
d['encrypted_key'] = vds.read_string()
d['salt'] = vds.read_string()
d['nDerivationMethod'] = vds.read_uint32()
d['nDerivationIterations'] = vds.read_uint32()
d['otherParams'] = vds.read_string()
item_callback(type, d)
except Exception, e:
traceback.print_exc()
print("ERROR parsing wallet.dat, type %s" % type)
print("key data: %s"%key)
print("key data in hex: %s"%key.encode('hex_codec'))
print("value data in hex: %s"%value.encode('hex_codec'))
sys.exit(1)
def create_env(db_dir,log=False):
db_env = DBEnv(0)
print db_dir
flags=(DB_CREATE|DB_INIT_LOCK|DB_INIT_MPOOL|DB_INIT_TXN|DB_THREAD|DB_RECOVER)
if log:
flags|=DB_INIT_LOG
# r = db_env.open(db_dir, (DB_CREATE|DB_INIT_LOCK|DB_INIT_LOG|DB_INIT_MPOOL|DB_INIT_TXN|DB_THREAD|DB_RECOVER))
r = db_env.open(db_dir, flags)
# print 'pre sleep', db_env
# print dir(db_env)
# time.sleep(15)
# print 'post sleep'
return db_env
def npw_open_wallet(path, writable=False):
walletdir,walletfile=os.path.split(path)
db = DB()
if writable:
DB_TYPEOPEN = DB_CREATE
else:
DB_TYPEOPEN = DB_RDONLY
flags = DB_THREAD | DB_TYPEOPEN
try:
r = db.open(path, "main", DB_BTREE, flags)
except DBError:
r = True
if r is not None:
traceback.print_exc()
print "Couldn't open '%s'. Try quitting Bitcoin and running this again."%path
sys.exit(1)
return db
def npw_read_wallet(walletpath, passphrase='', addrv=0):
crypted=False
db = npw_open_wallet(walletpath)
json_db={}
json_db['keys'] = []
json_db['pool'] = []
json_db['tx'] = []
json_db['names'] = {}
json_db['ckey'] = []
json_db['mkey'] = {}
def item_callback(type, d):
if type == "tx":
json_db['tx'].append({"tx_id" : d['tx_id'], "txin" : d['txIn'], "txout" : d['txOut'], "tx_v" : d['txv'], "tx_k" : d['txk']})
elif type == "name":
json_db['names'][d['hash']] = d['name']