mmgen-autosign 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. #!/usr/bin/env python
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2017 Philemon <mmgen-py@yandex.com>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. mmgen-autosign: Auto-sign MMGen transactions
  20. """
  21. import sys,os,subprocess,time,signal
  22. from stat import *
  23. mountpoint = '/mnt/tx'
  24. tx_dir = os.path.join(mountpoint,'tx')
  25. part_label = 'MMGEN_TX'
  26. shm_dir = '/dev/shm'
  27. secret_fn = 'txsign-secret'
  28. from mmgen.common import *
  29. prog_name = os.path.basename(sys.argv[0])
  30. opts_data = lambda: {
  31. 'desc': 'Auto-sign MMGen transactions',
  32. 'usage':'[opts] [command]',
  33. 'options': """
  34. -h, --help Print this help message
  35. -c, --coins=c Coins to sign for (comma-separated list)
  36. -l, --led Use status LED to signal standby, busy and error
  37. -s, --stealth-led Stealth LED mode - signal busy and error only, and only
  38. after successful authorization.
  39. -q, --quiet Produce quieter output
  40. -v, --verbose Produce more verbose output
  41. """,
  42. 'notes': """
  43. COMMANDS
  44. gen_secret - generate the shared secret and copy to /dev/shm and USB stick
  45. wait - start in loop mode: wait - mount - sign - unmount - wait
  46. USAGE NOTES
  47. If invoked with no command, the program mounts the USB stick, signs any
  48. unsigned transactions, unmounts the USB stick and exits.
  49. If invoked with 'wait', the program waits in a loop, mounting, signing and
  50. unmounting every time the USB stick is inserted. On supported platforms,
  51. the status LED indicates whether the program is busy or in standby mode,
  52. i.e. ready for USB stick insertion or removal.
  53. The USB stick must have a partition labeled MMGEN_TX and a user-writable
  54. directory '/tx', where unsigned MMGen transactions are placed.
  55. On the signing machine the directory /mnt/tx must exist and /etc/fstab must
  56. contain the following entry:
  57. LABEL='MMGEN_TX' /mnt/tx auto noauto,user 0 0
  58. The signing wallet or wallets must be in MMGen mnemonic format and
  59. present in /dev/shm. The wallet(s) can be created interactively with
  60. the following command:
  61. $ mmgen-walletconv -i words -o words -d /dev/shm
  62. {} checks that a shared secret is present on the USB stick
  63. before signing transactions. The shared secret is generated by invoking
  64. the command with 'gen_secret' with the USB stick inserted. For good
  65. security, it's advisable to re-generate a new shared secret before each
  66. signing session.
  67. Status LED functionality is supported on Orange Pi and Raspberry Pi boards.
  68. This program is a helper script and is not installed by default. You
  69. may copy it to your executable path if you wish, or just run it in place
  70. in the scripts directory of the MMGen repository root where it resides.
  71. """.format(prog_name)
  72. }
  73. cmd_args = opts.init(opts_data,add_opts=['mmgen_keys_from_file','in_fmt'])
  74. import mmgen.tx
  75. from mmgen.txsign import txsign
  76. from mmgen.protocol import CoinProtocol
  77. if opt.stealth_led: opt.led = True
  78. opt.outdir = tx_dir
  79. def check_daemons_running():
  80. if opt.coin:
  81. die(1,'--coin option not supported with this command. Use --coins instead')
  82. if opt.coins:
  83. coins = opt.coins.split(',')
  84. else:
  85. ymsg('Warning: no coins specified, so defaulting to BTC only')
  86. coins = ['btc']
  87. for coin in coins:
  88. cmd = [ 'mmgen-tool',
  89. '--coin={}'.format(coin),
  90. '--testnet={}'.format(opt.testnet or 0)
  91. ] + ([],['--quiet'])[bool(opt.quiet)] + ['getbalance']
  92. vmsg('Executing: {}'.format(' '.join(cmd)))
  93. try: subprocess.check_output(cmd)
  94. except: die(1,'{} daemon not running'.format(coin.upper()))
  95. def get_wallet_files():
  96. wfs = [f for f in os.listdir(shm_dir) if f[-8:] == '.mmwords']
  97. if not wfs:
  98. die(1,'No mnemonic files present!')
  99. return [os.path.join(shm_dir,w) for w in wfs]
  100. def get_secret_in_dir(d,on_fail='die'):
  101. fn = os.path.join(d,secret_fn)
  102. try:
  103. with open(fn) as f: ret = f.read().rstrip()
  104. assert is_hex_str(ret) and len(ret) == 32
  105. return ret
  106. except:
  107. msg("Secret file '{}' non-existent, unreadable or in incorrect format!".format(fn))
  108. if on_fail == 'die': sys.exit(1)
  109. else: return None
  110. def do_mount():
  111. if not os.path.ismount(mountpoint):
  112. msg('Mounting '+mountpoint)
  113. subprocess.call(['mount',mountpoint])
  114. try:
  115. ds = os.stat(tx_dir)
  116. assert S_ISDIR(ds.st_mode)
  117. assert ds.st_mode & S_IWUSR|S_IRUSR == S_IWUSR|S_IRUSR
  118. except:
  119. die(1,'{} missing, or not read/writable by user!'.format(tx_dir))
  120. def do_umount():
  121. if os.path.ismount(mountpoint):
  122. subprocess.call(['sync'])
  123. msg('Unmounting '+mountpoint)
  124. subprocess.call(['umount',mountpoint])
  125. def sign_tx_file(txfile):
  126. try:
  127. g.coin = mmgen.tx.MMGenTX(txfile,md_only=True).coin
  128. g.proto = CoinProtocol(g.coin,g.testnet)
  129. reload(sys.modules['mmgen.tx'])
  130. tx = mmgen.tx.MMGenTX(txfile)
  131. rpc_init(reinit=True)
  132. txsign(tx,wfs,None,None)
  133. tx.write_to_file(ask_write=False)
  134. return True
  135. except:
  136. return False
  137. def sign():
  138. dirlist = os.listdir(tx_dir)
  139. raw = [f for f in dirlist if f[-6:] == '.rawtx']
  140. signed = [f[:-6] for f in dirlist if f[-6:] == '.sigtx']
  141. unsigned = [os.path.join(tx_dir,f) for f in raw if f[:-6] not in signed]
  142. if unsigned:
  143. fails = 0
  144. for txfile in unsigned:
  145. ret = sign_tx_file(txfile)
  146. if not ret:
  147. fails += 1
  148. qmsg('')
  149. if fails: ymsg('{} failed signs'.format(fails))
  150. time.sleep(0.3)
  151. return False if fails else True
  152. else:
  153. msg('No unsigned transactions')
  154. time.sleep(1)
  155. return True
  156. def do_sign():
  157. if not opt.stealth_led: set_led('busy')
  158. do_mount()
  159. ret = get_secret_in_dir(tx_dir,on_fail='return')
  160. if ret == secret:
  161. if opt.stealth_led: set_led('busy')
  162. ret = sign()
  163. do_umount()
  164. set_led(('standby','off','error')[(not ret)*2 or bool(opt.stealth_led)])
  165. else:
  166. if ret != None:
  167. msg('Secret is incorrect!')
  168. do_umount()
  169. if not opt.stealth_led: set_led('error')
  170. def wipe_existing_secret_files():
  171. for d in (tx_dir,shm_dir):
  172. fn = os.path.join(d,secret_fn)
  173. try:
  174. os.stat(fn)
  175. except:
  176. pass
  177. else:
  178. msg('\nWiping existing key {}'.format(fn))
  179. subprocess.call(['wipe','-c',fn])
  180. def create_secret_files():
  181. from binascii import hexlify
  182. secret = hexlify(os.urandom(16))
  183. for d in (tx_dir,shm_dir):
  184. fn = os.path.join(d,secret_fn)
  185. desc = 'secret file in {}'.format(d)
  186. msg('Creating ' + desc)
  187. try:
  188. with open(fn,'w') as f: f.write(secret+'\n')
  189. os.chmod(fn,0400)
  190. msg('Wrote ' + desc)
  191. except:
  192. die(2,'Unable to write ' + desc)
  193. def do_create_secret_files():
  194. if not get_insert_status():
  195. die(2,'USB stick not present!')
  196. do_mount()
  197. wipe_existing_secret_files()
  198. create_secret_files()
  199. do_umount()
  200. def ev_sleep(secs):
  201. ev.wait(secs)
  202. return (False,True)[ev.isSet()]
  203. def do_led(on,off):
  204. if not on:
  205. with open(status_ctl,'w') as f: f.write('0\n')
  206. while True:
  207. if ev_sleep(3600): return
  208. while True:
  209. with open(status_ctl,'w') as f: f.write('255\n')
  210. if ev_sleep(on): return
  211. with open(status_ctl,'w') as f: f.write('0\n')
  212. if ev_sleep(off): return
  213. def set_led(cmd):
  214. if not opt.led: return
  215. vmsg("Setting LED state to '{}'".format(cmd))
  216. timings = {
  217. 'off': ( 0, 0 ),
  218. 'standby': ( 2.2, 0.2 ),
  219. 'busy': ( 0.06, 0.06 ),
  220. 'error': ( 0.5, 0.5 )}[cmd]
  221. global led_thread
  222. if led_thread:
  223. ev.set(); led_thread.join(); ev.clear()
  224. led_thread = threading.Thread(target=do_led,name='LED loop',args=timings)
  225. led_thread.start()
  226. def get_insert_status():
  227. try: os.stat(os.path.join('/dev/disk/by-label/',part_label))
  228. except: return False
  229. else: return True
  230. def do_loop():
  231. n,prev_status = 0,False
  232. if not opt.stealth_led:
  233. set_led('standby')
  234. while True:
  235. status = get_insert_status()
  236. if status and not prev_status:
  237. msg('Running command...')
  238. do_sign()
  239. prev_status = status
  240. if not n % 10:
  241. msg_r('\r{}\rWaiting'.format(' '*17))
  242. time.sleep(1)
  243. msg_r('.')
  244. n += 1
  245. def check_access(fn,desc='status LED control',init_val=None):
  246. try:
  247. with open(fn) as f: b = f.read().strip()
  248. with open(fn,'w') as f:
  249. f.write('{}\n'.format(init_val or b))
  250. return True
  251. except:
  252. m1 = "You do not have access to the {} file\n".format(desc)
  253. m2 = "To allow access, run 'sudo chmod 0666 {}'".format(fn)
  254. msg(m1+m2)
  255. return False
  256. def check_wipe_present():
  257. try:
  258. subprocess.Popen(['wipe','-v'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
  259. except:
  260. die(2,"The 'wipe' utility must be installed before running this program")
  261. def at_exit(nl=True):
  262. if opt.led:
  263. set_led('off')
  264. ev.set()
  265. led_thread.join()
  266. if board == 'rpi':
  267. with open(trigger[board],'w') as f: f.write('mmc0\n')
  268. if nl: msg('')
  269. raise SystemExit
  270. def handler(a,b): at_exit()
  271. # main()
  272. if len(cmd_args) == 1 and cmd_args[0] == 'gen_secret':
  273. do_create_secret_files()
  274. sys.exit()
  275. if opt.led:
  276. import threading
  277. status = {
  278. 'opi': '/sys/class/leds/orangepi:red:status/brightness',
  279. 'rpi': '/sys/class/leds/led0/brightness'
  280. }
  281. trigger = {
  282. 'rpi': '/sys/class/leds/led0/trigger', # mmc,none
  283. }
  284. for k in ('opi','rpi'):
  285. try: os.stat(status[k])
  286. except: pass
  287. else:
  288. board = k
  289. status_ctl = status[board]
  290. break
  291. else:
  292. die(2,'Control files not found! LED option not supported')
  293. if not check_access(status_ctl) or (
  294. board == 'rpi' and not check_access(trigger[board],desc='LED trigger',init_val='none')):
  295. sys.exit(1)
  296. ev = threading.Event()
  297. led_thread = None
  298. if board == 'rpi':
  299. with open(trigger[board],'w') as f: f.write('none\n')
  300. check_wipe_present()
  301. wfs = get_wallet_files()
  302. secret = get_secret_in_dir(shm_dir,on_fail='die')
  303. check_daemons_running()
  304. #sign(); sys.exit()
  305. signal.signal(signal.SIGTERM,handler)
  306. signal.signal(signal.SIGINT,handler)
  307. try:
  308. if len(cmd_args) == 1 and cmd_args[0] == 'wait':
  309. do_loop()
  310. elif len(cmd_args) == 0:
  311. do_sign()
  312. at_exit(nl=False)
  313. else:
  314. msg('Invalid invocation')
  315. except IOError:
  316. at_exit()
  317. except KeyboardInterrupt:
  318. at_exit()