-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathoffline
375 lines (319 loc) · 14.7 KB
/
offline
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
#! /usr/bin/python3
# Simple script to save typos and other frustrations for offline wallets.
# Licenced under CC0 (Public domain), by Rusty Russell
import argparse
import glob
import json
import os
import readline
import subprocess
import sys
import time
DEBS={
'bitcoind_0.16.0-bionic1_amd64.deb': 'd9ac2eada58aeeae671ce4c2c355ab7e4717bb7a2844eeb143a23a8a433ddd48',
'libboost-chrono1.65.1_1.65.1+dfsg-0ubuntu5_amd64.deb': 'ecb75ff0dbc0956585a6cddd7fd8c863593948b47c0c9b27ec734f5560283956',
'libboost-filesystem1.65.1_1.65.1+dfsg-0ubuntu5_amd64.deb': '8756b023a86222524cf6ef7884da92fd21ad53207b38e705f568a745dcea4cef',
'libboost-program-options1.65.1_1.65.1+dfsg-0ubuntu5_amd64.deb': 'dc13c690524ad6258b7897b2dd6723a3b3df29d745657a6ccbe7440d57f1b453',
'libboost-system1.65.1_1.65.1+dfsg-0ubuntu5_amd64.deb': '390e93c275504a03101de7e35d898f224dff2594ff802dcc83a936b5fca690cc',
'libboost-thread1.65.1_1.65.1+dfsg-0ubuntu5_amd64.deb': '3748600e4dbadfb84df6873d23117a3728ad1f3b71505062037d4caa346696b3',
'libdb4.8++_4.8.30-bionic3_amd64.deb': 'b3ddd5da73816484304a747b526039ec143fe70c969168981813461ba4080233',
'libevent-core-2.1-6_2.1.8-stable-4build1_amd64.deb': 'b3cffa9ac341236250ef786dd55d4cd7eac6a36c87541df1cf4038239761256b',
'libevent-pthreads-2.1-6_2.1.8-stable-4build1_amd64.deb': '67a8152b242882100487f6ea5c364e142b163777f6b4490902e374719726fdaf',
'libminiupnpc10_1.9.20140610-4ubuntu2_amd64.deb': '11902e06fda5689053b5bbf3f5861343eef4f2e725c70833bdcaa105f0e033ce',
'libpgm-5.2-0_5.2.122~dfsg-2_amd64.deb': '22db07cf0d827a1b96ae2243fc832f8b55d91543faebc0fbb374893b7b079b1b',
'libsodium23_1.0.16-2_amd64.deb': '2620628ebe077a92003464d544e273e00ac58c29d62c7a7d7178dc13ee913152',
'libssl1.1_1.1.0g-2ubuntu4_amd64.deb': '82e424d50e144320319414a1964d3a980abde4bc39fc7d8c2885819328cb5cb4',
'libzmq5_4.2.5-1_amd64.deb': 'a584e32363a975735aefec1a11edc84cc8444eca8157b590d44c229d7500ead5',
'libqrencode3_3.4.4-1build1_amd64.deb': 'e2815703e5ed29f47a8434fbc23535b7bdd938e4483c925bfbc92414f2715d56',
'qrencode_3.4.4-1build1_amd64.deb': '7b46f0f4d2a985f7130c14902b1cbfae1b26558d2609f4b38e4196d6321fe18c',
'libnorm1_1.5r6+dfsg1-6_amd64.deb': 'd16894811280faa258b132786870b9adfc264d50bf844c0ee990291114652da9',
}
def prefilled_input(prompt, text):
def prefill_hook():
if text is not None:
readline.insert_text(text)
readline.redisplay()
readline.set_pre_input_hook(prefill_hook)
result = input(prompt)
readline.set_pre_input_hook()
return result
def check_ubuntu():
size=1921843200
cdrom='a55353d837cbf7bc006cf49eeff05ae5044e757498e30643a9199b9a25bc9a34'
output=subprocess.run('dd status=none if=/dev/cdrom count={} | sha256sum'.format(int(size / 512)),
shell=True, check=True, universal_newlines=True,
stdout=subprocess.PIPE).stdout
if output != cdrom + " -\n":
sys.exit('Bad ubuntu image')
def goto_debdir():
offline=glob.glob('/media/ubuntu/*/offline')
if len(offline) != 1:
sys.exit('More than one offline script found inserted?')
os.chdir(os.path.dirname(offline[0]))
def check_debs():
for d in DEBS.keys():
output=subprocess.run(['sha256sum', d],
universal_newlines=True, check=True,
stdout=subprocess.PIPE).stdout
if output != '{} {}\n'.format(DEBS[d], d):
sys.exit('Bad package {}'.format(d))
def install_debs():
cmd=['sudo', 'dpkg', '-i']
cmd.extend(DEBS.keys())
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL)
def stop_bitcoin():
subprocess.run(['bitcoin-cli', 'stop'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
print("stopping bitcoind")
def start_bitcoin():
subprocess.Popen('bitcoind')
# Make sure it's started.
end=time.clock() + 10
while time.clock() < end:
if subprocess.run(['bitcoin-cli', 'ping'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0:
return
time.sleep(0.5)
# Try stopping, just in case.
stop_bitcoin()
raise Exception('Starting bitcoind timed out')
# Helper to run bitcoin-cli
def bitcoin_cli(*args):
cmd=['bitcoin-cli']
cmd.extend(args)
return subprocess.run(cmd,
universal_newlines=True,
stdout=subprocess.PIPE)
# Helper to run bitcoin-cli, which shouldn't fail. Returns stdout.
def bitcoin_cli_nofail(*args):
cmd=['bitcoin-cli']
cmd.extend(args)
return subprocess.run(cmd,
check=True,
universal_newlines=True,
stdout=subprocess.PIPE).stdout
# Helper to run bitcoin-cli, which shouldn't fail. Returns stdout, \n removed.
def bitcoin_cli_simple(*args):
return bitcoin_cli_nofail(*args).rstrip()
# Helper to parse bitcoin-cli output as JSON.
def json_from_bitcoin_cli(*args):
return json.loads(bitcoin_cli_nofail(*args))
def new_key():
print('Generating address', end='...', flush=True)
time.sleep(1)
tmpaddr=bitcoin_cli_simple('getnewaddress', 'p2sh-segwit')
tmpprivkey=bitcoin_cli_simple('dumpprivkey', tmpaddr)
print('SUCCESS')
print('')
print('Public address: {}'.format(tmpaddr))
print('Private key (keep secret!): {}'.format(tmpprivkey))
print('Split in two: {} {}'.format(tmpprivkey[:24],tmpprivkey[24:]))
print('Split in three: {} {} {}'.format(tmpprivkey[:16],tmpprivkey[16:31],tmpprivkey[31:]))
print('')
input('Press Enter')
# See https://en.bitcoin.it/wiki/Proper_Money_Handling_(JSON-RPC)
def bitcoin_to_satoshi(value):
return int(round(value * 1e8))
def satoshi_to_bitcoin(amount):
return float(amount / 1e8)
def get_p2sh_addresses():
# We want the P2SH addresses.
P2SH_prefix='3'
return [addr for addr in json_from_bitcoin_cli('getaddressesbyaccount', '') if addr.startswith(P2SH_prefix)]
def check_key():
global addr
global privkey
addr=None
privkey=prefilled_input('Enter your private key (UPPER and lower case matters!): ',
privkey)
# There's no good way to figure out the address, except diff before
# and after. Blech!
before_addresses=set(get_p2sh_addresses())
if bitcoin_cli('importprivkey', privkey.replace(" ", "")).returncode == 0:
print('Key is VALID!')
after_addresses=set(get_p2sh_addresses())
diff=after_addresses - before_addresses
if len(diff) == 1:
addr=diff.pop()
print('Public address is {}'.format(addr))
elif len(diff) == 0:
print('Re-import of existing key? One of:')
for k in after_addresses:
print(' ' + k)
addr=input('Please enter the address: ')
if addr not in after_addresses:
print('{} is not one of those. Try again'.format(addr))
addr=None
else:
raise Exception('More than one address created from that privkey?')
else:
print('Invalid private key (starts with L or K)')
def spend_tx():
global addr
global privkey
global tx
global vout
global input_amount
global fee_rate
global dest_addr
global change_addr
print('Generating public keyscript for {}'.format(addr), end='...', flush=True)
scriptpubkey = json_from_bitcoin_cli('validateaddress', addr)['scriptPubKey']
print('SUCCESS')
tx=prefilled_input('Enter transaction ID (64 characters) or raw transaction: ',
tx)
if len(tx) == 64:
# Make sure it's hex!
try:
int(tx,16)
except ValueError:
print('Bad transaction ID. Try again')
return
txid=tx
vout=int(prefilled_input('Enter output number which paid to {} (first is 0, second is 1, etc): '.format(addr), vout))
input_amount=float(prefilled_input('Enter amount it paid (in bitcoins): ', input_amount))
else:
decode=bitcoin_cli('decoderawtransaction', tx)
if decode.returncode != 0:
print('Decoding transaction FAILED. Typo? Try again')
return
txjson=json.loads(decode.stdout)
txid=txjson['txid']
print('Transaction ID: {}'.format(txid))
vout=None
for v in txjson['vout']:
if v['scriptPubKey']['hex'] == scriptpubkey:
print('Output {} pays {} to us'.format(v['n'], v['value']))
if vout is not None:
print('More than one output pays to us. Failing.')
return
vout=v['n']
input_amount=v['value']
if vout is None:
print('No output pays to us. Failing.')
return
input_amount_satoshis=bitcoin_to_satoshi(input_amount)
fee_rate=int(prefilled_input('Fee per kilobyte (in satoshis, eg 100000): ', fee_rate))
dest_addr=prefilled_input('Address to send to: ', dest_addr)
dest_amount=input('Amount to send (hit ENTER to send as much as possible): ')
if dest_amount != '':
dest_amount_satoshis=bitcoin_to_satoshi(float(dest_amount))
change_addr=prefilled_input('Address for change: ', change_addr)
# Tx with two outputs is about 170 vbytes.
fee_satoshis=int(fee_rate * 170 / 1000)
change_amount_satoshis=input_amount_satoshis - dest_amount_satoshis - fee_satoshis
# Sanity check for tiny or negative change (or weird fee).
if change_amount_satoshis < fee_satoshis:
print("Change amount {:.8f} too small (fee is {:.8f})".format(satoshi_to_bitcoin(change_amount_satoshis), satoshi_to_bitcoin(fee_satoshis)))
return
else:
# Tx with one output is about 135 vbytes.
fee_satoshis=int(fee_rate * 135 / 1000)
dest_amount_satoshis=input_amount_satoshis - fee_satoshis
change_addr=None
# Sanity check fee.
if fee_satoshis > input_amount_satoshis:
print('Fee {:.8f} is greater than input amount {:.8f}'
.format(satoshi_to_bitcoin(fee_satoshis),
satoshi_to_bitcoin(input_amount_satoshis)))
return
if change_addr is None:
changestr=''
else:
changestr=' (change to {})'.format(change_addr)
print('')
print('Spending {:.8f} to send {:.8f} to {}{}'.format(satoshi_to_bitcoin(input_amount_satoshis), satoshi_to_bitcoin(dest_amount_satoshis), dest_addr, changestr))
print('Paying miners a fee of {:.8f} bitcoins ({:5f}%)'.format(satoshi_to_bitcoin(fee_satoshis), fee_satoshis * 100 / dest_amount_satoshis))
if fee_satoshis > bitcoin_to_satoshi(0.001):
print('WARNING: Fee of {} bitcoins seems really large.'
.format(satoshi_to_bitcoin(fee_satoshis)))
print('This fee goes straight to the miners.')
# Simply refuse to pay more than 5% fee ever.
if fee_satoshis * 20 >= dest_amount_satoshis:
print('Refusing to let you do that. Sorry.')
return
# Create transaction.
print('Creating raw transaction', end='...', flush=True)
if change_addr is not None:
# Random order of dest, change
if os.urandom(1)[0] >= 128:
outputs='{{"{}":{},"{}":{}}}'.format(dest_addr, satoshi_to_bitcoin(dest_amount_satoshis), change_addr, satoshi_to_bitcoin(change_amount_satoshis))
our_output=1
else:
outputs='{{"{}":{},"{}":{}}}'.format(change_addr, satoshi_to_bitcoin(change_amount_satoshis), dest_addr, satoshi_to_bitcoin(dest_amount_satoshis))
our_output=0
else:
outputs='{{"{}":{}}}'.format(dest_addr, satoshi_to_bitcoin(dest_amount_satoshis))
raw_tx=bitcoin_cli('createrawtransaction',
'[{{"txid":"{}","vout":{}}}]'.format(txid, vout),
outputs)
if raw_tx.returncode != 0:
print('FAILED.')
print('Malformed transaction or addresses? Try again.')
return
print('SUCCESS')
redeemscript=json_from_bitcoin_cli('validateaddress', addr)['hex']
print('Signing raw transaction', end='...', flush=True)
signed_tx=json_from_bitcoin_cli('signrawtransaction', raw_tx.stdout.rstrip(),
'[{{"txid":"{}","vout":{},"scriptPubKey":"{}","redeemScript":"{}","amount":{}}}]'.format(txid, vout, scriptpubkey, redeemscript,input_amount))
print('SUCCESS')
if change_addr is not None:
output_txid=json_from_bitcoin_cli('decoderawtransaction', raw_tx.stdout.rstrip())['txid']
print("Transaction (change) to spend next time: {} output #{} amount {}"
.format(output_txid, our_output, satoshi_to_bitcoin(change_amount_satoshis)))
print('Payment to broadcast: {}'.format(signed_tx['hex']))
input('Press Enter to show qrcode')
subprocess.run(['qrencode', '-i', '-t', 'UTF8', signed_tx['hex']])
# Because sys.tracebacklimit=0 doesn't work in python3. From
# http://stackoverflow.com/questions/27674602/hide-traceback-unless-a-debug-flag-is-set
def exceptionHandler(exception_type, exception, traceback):
print('{}: {}'.format(exception_type.__name__, exception))
parser = argparse.ArgumentParser(description='Offline bitcoin helper script')
parser.add_argument('--verbose', action='store_true', help='Verbose debug mode')
args=parser.parse_args()
# No tracebacks for normal users please.
if args.verbose is False:
sys.excepthook = exceptionHandler
# These are globals. Typos are common, so we use previous answers to
# pre-populate input fields.
addr=None
privkey=None
tx=None
vout=None
input_amount=None
fee_rate=None
dest_addr=None
change_addr=None
print("Rusty's Remarkable Unreliable Bitcoin Storage Script")
print('----------------------------------------------------');
goto_debdir()
print('Checking bitcoin and friends', end='...', flush=True)
check_debs()
print('OK')
print('Installing bitcoin and friends', end='...', flush=True)
install_debs()
print('OK')
print('Starting bitcoin', end='...', flush=True)
start_bitcoin()
print('OK')
try:
while True:
print('')
print('create - Create a new private key and public address.')
print('restore - Restore a private key and check it is valid.')
if addr is not None:
print('spend - spend a transaction with a private key.')
print('(To quit, just power off the entire machine)')
choice=input('What do you want to do? ')
if choice == 'create':
new_key()
elif choice == 'restore':
check_key()
elif choice == 'spend':
if addr is None:
print("Use 'restore' to enter the private key first")
else:
spend_tx()
else:
print("I don't understand '{}'".format(choice))
finally:
stop_bitcoin()
sys.exit(1)