util.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. #!/usr/bin/env python
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2016 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. util.py: Low-level routines imported by other modules in the MMGen suite
  20. """
  21. import sys,os,time,stat,re
  22. from hashlib import sha256
  23. from binascii import hexlify,unhexlify
  24. from string import hexdigits
  25. from mmgen.color import *
  26. def msg(s): sys.stderr.write(s+'\n')
  27. def msg_r(s): sys.stderr.write(s)
  28. def Msg(s): sys.stdout.write(s + '\n')
  29. def Msg_r(s): sys.stdout.write(s)
  30. def msgred(s): sys.stderr.write(red(s+'\n'))
  31. def mmsg(*args):
  32. for d in args:
  33. sys.stdout.write(repr(d)+'\n')
  34. def mdie(*args):
  35. for d in args:
  36. sys.stdout.write(repr(d)+'\n')
  37. sys.exit()
  38. def die(ev=0,s=''):
  39. assert type(ev) == int
  40. if s: sys.stderr.write(s+'\n')
  41. sys.exit(ev)
  42. def Die(ev=0,s=''):
  43. assert type(ev) == int
  44. if s: sys.stdout.write(s+'\n')
  45. sys.exit(ev)
  46. def pp_format(d):
  47. import pprint
  48. return pprint.PrettyPrinter(indent=4).pformat(d)
  49. def pp_die(d):
  50. import pprint
  51. die(1,pprint.PrettyPrinter(indent=4).pformat(d))
  52. def pp_msg(d):
  53. import pprint
  54. msg(pprint.PrettyPrinter(indent=4).pformat(d))
  55. def set_for_type(val,refval,desc,invert_bool=False,src=None):
  56. src_str = (''," in '{}'".format(src))[bool(src)]
  57. if type(refval) == bool:
  58. v = str(val).lower()
  59. if v in ('true','yes','1'): ret = True
  60. elif v in ('false','no','none','0'): ret = False
  61. else: die(1,"'{}': invalid value for '{}'{} (must be of type '{}')".format(
  62. val,desc,src_str,'bool'))
  63. if invert_bool: ret = not ret
  64. else:
  65. try:
  66. ret = type(refval)((val,not val)[invert_bool])
  67. except:
  68. die(1,"'{}': invalid value for '{}'{} (must be of type '{}')".format(
  69. val,desc,src_str,type(refval).__name__))
  70. return ret
  71. # From 'man dd':
  72. # c=1, w=2, b=512, kB=1000, K=1024, MB=1000*1000, M=1024*1024,
  73. # GB=1000*1000*1000, G=1024*1024*1024, and so on for T, P, E, Z, Y.
  74. def parse_nbytes(nbytes):
  75. import re
  76. m = re.match(r'([0123456789]+)(.*)',nbytes)
  77. smap = ('c',1),('w',2),('b',512),('kB',1000),('K',1024),('MB',1000*1000),\
  78. ('M',1024*1024),('GB',1000*1000*1000),('G',1024*1024*1024)
  79. if m:
  80. if m.group(2):
  81. for k,v in smap:
  82. if k == m.group(2):
  83. return int(m.group(1)) * v
  84. else:
  85. msg("Valid byte specifiers: '%s'" % "' '".join([i[0] for i in smap]))
  86. else:
  87. return int(nbytes)
  88. die(1,"'%s': invalid byte specifier" % nbytes)
  89. def check_or_create_dir(path):
  90. try:
  91. os.listdir(path)
  92. except:
  93. try:
  94. os.makedirs(path,0700)
  95. except:
  96. die(2,"ERROR: unable to read or create path '{}'".format(path))
  97. from mmgen.opts import opt
  98. def qmsg(s,alt=False):
  99. if opt.quiet:
  100. if alt != False: sys.stderr.write(alt + '\n')
  101. else: sys.stderr.write(s + '\n')
  102. def qmsg_r(s,alt=False):
  103. if opt.quiet:
  104. if alt != False: sys.stderr.write(alt)
  105. else: sys.stderr.write(s)
  106. def vmsg(s,force=False):
  107. if opt.verbose or force: sys.stderr.write(s + '\n')
  108. def vmsg_r(s,force=False):
  109. if opt.verbose or force: sys.stderr.write(s)
  110. def Vmsg(s,force=False):
  111. if opt.verbose or force: sys.stdout.write(s + '\n')
  112. def Vmsg_r(s,force=False):
  113. if opt.verbose or force: sys.stdout.write(s)
  114. def dmsg(s):
  115. if opt.debug: sys.stdout.write(s + '\n')
  116. def suf(arg,suf_type):
  117. t = type(arg)
  118. if t == int:
  119. n = arg
  120. elif t in (list,tuple,set,dict):
  121. n = len(arg)
  122. else:
  123. msg('%s: invalid parameter' % arg)
  124. return ''
  125. if suf_type in ('a','es'): return ('es','')[n == 1]
  126. if suf_type in ('k','s'): return ('s','')[n == 1]
  127. def get_extension(f):
  128. a,b = os.path.splitext(f)
  129. return ('',b[1:])[len(b) > 1]
  130. def remove_extension(f,e):
  131. a,b = os.path.splitext(f)
  132. return (f,a)[len(b)>1 and b[1:]==e]
  133. def make_chksum_N(s,nchars,sep=False):
  134. if nchars%4 or not (4 <= nchars <= 64): return False
  135. s = sha256(sha256(s).digest()).hexdigest().upper()
  136. sep = ('',' ')[bool(sep)]
  137. return sep.join([s[i*4:i*4+4] for i in range(nchars/4)])
  138. def make_chksum_8(s,sep=False):
  139. s = sha256(sha256(s).digest()).hexdigest()[:8].upper()
  140. return '{} {}'.format(s[:4],s[4:]) if sep else s
  141. def make_chksum_6(s): return sha256(s).hexdigest()[:6]
  142. def is_chksum_6(s): return len(s) == 6 and is_hexstring_lc(s)
  143. def make_iv_chksum(s): return sha256(s).hexdigest()[:8].upper()
  144. def splitN(s,n,sep=None): # always return an n-element list
  145. ret = s.split(sep,n-1)
  146. return ret + ['' for i in range(n-len(ret))]
  147. def split2(s,sep=None): return splitN(s,2,sep) # always return a 2-element list
  148. def split3(s,sep=None): return splitN(s,3,sep) # always return a 3-element list
  149. def split_into_cols(col_wid,s):
  150. return ' '.join([s[col_wid*i:col_wid*(i+1)]
  151. for i in range(len(s)/col_wid+1)]).rstrip()
  152. def capfirst(s): # different from str.capitalize() - doesn't downcase any uc in string
  153. return s if len(s) == 0 else s[0].upper() + s[1:]
  154. def decode_timestamp(s):
  155. # with open('/etc/timezone') as f:
  156. # tz_save = f.read().rstrip()
  157. os.environ['TZ'] = 'UTC'
  158. ts = time.strptime(s,'%Y%m%d_%H%M%S')
  159. t = time.mktime(ts)
  160. # os.environ['TZ'] = tz_save
  161. return int(t)
  162. def make_timestamp(secs=None):
  163. t = int(secs) if secs else time.time()
  164. tv = time.gmtime(t)[:6]
  165. return '{:04d}{:02d}{:02d}_{:02d}{:02d}{:02d}'.format(*tv)
  166. def make_timestr(secs=None):
  167. t = int(secs) if secs else time.time()
  168. tv = time.gmtime(t)[:6]
  169. return '{:04d}/{:02d}/{:02d} {:02d}:{:02d}:{:02d}'.format(*tv)
  170. def secs_to_hms(secs):
  171. return '{:02d}:{:02d}:{:02d}'.format(secs/3600, (secs/60) % 60, secs % 60)
  172. def secs_to_ms(secs):
  173. return '{:02d}:{:02d}'.format(secs/60, secs % 60)
  174. def _is_whatstring(s,chars):
  175. return set(list(s)) <= set(chars)
  176. def is_int(s):
  177. try:
  178. int(s)
  179. return True
  180. except:
  181. return False
  182. def is_hexstring(s):
  183. return _is_whatstring(s.lower(),hexdigits.lower())
  184. def is_hexstring_lc(s):
  185. return _is_whatstring(s,hexdigits.lower())
  186. def is_hexstring_uc(s):
  187. return _is_whatstring(s,hexdigits.upper())
  188. def is_b58string(s):
  189. from mmgen.bitcoin import b58a
  190. return _is_whatstring(s,b58a)
  191. def is_utf8(s):
  192. try: s.decode('utf8')
  193. except: return False
  194. else: return True
  195. def is_ascii(s):
  196. try: s.decode('ascii')
  197. except: return False
  198. else: return True
  199. def match_ext(addr,ext):
  200. return addr.split('.')[-1] == ext
  201. def file_exists(f):
  202. try:
  203. os.stat(f)
  204. return True
  205. except:
  206. return False
  207. def file_is_readable(f):
  208. from stat import S_IREAD
  209. try:
  210. assert os.stat(f).st_mode & S_IREAD
  211. except:
  212. return False
  213. else:
  214. return True
  215. def get_from_brain_opt_params():
  216. l,p = opt.from_brain.split(',')
  217. return(int(l),p)
  218. def pretty_hexdump(data,gw=2,cols=8,line_nums=False):
  219. r = (0,1)[bool(len(data) % gw)]
  220. return ''.join(
  221. [
  222. ('' if (line_nums == False or i % cols) else '{:06x}: '.format(i*gw)) +
  223. hexlify(data[i*gw:i*gw+gw]) + ('\n',' ')[bool((i+1) % cols)]
  224. for i in range(len(data)/gw + r)
  225. ]
  226. ).rstrip() + '\n'
  227. def decode_pretty_hexdump(data):
  228. from string import hexdigits
  229. pat = r'^[%s]+:\s+' % hexdigits
  230. lines = [re.sub(pat,'',l) for l in data.splitlines()]
  231. try:
  232. return unhexlify(''.join((''.join(lines).split())))
  233. except:
  234. msg('Data not in hexdump format')
  235. return False
  236. def strip_comments(line):
  237. return re.sub(ur'\s+$',u'',re.sub(ur'#.*',u'',line,1))
  238. def remove_comments(lines):
  239. return [m for m in [strip_comments(l) for l in lines] if m != '']
  240. from mmgen.globalvars import g
  241. def start_mscolor():
  242. try:
  243. import colorama
  244. colorama.init(strip=True,convert=True)
  245. except:
  246. msg('Import of colorama module failed')
  247. def get_hash_params(hash_preset):
  248. if hash_preset in g.hash_presets:
  249. return g.hash_presets[hash_preset] # N,p,r,buflen
  250. else: # Shouldn't be here
  251. die(3,"%s: invalid 'hash_preset' value" % hash_preset)
  252. def compare_chksums(chk1,desc1,chk2,desc2,hdr='',die_on_fail=False,verbose=False):
  253. if not chk1 == chk2:
  254. m = "%s ERROR: %s checksum (%s) doesn't match %s checksum (%s)"\
  255. % ((hdr+':\n ' if hdr else 'CHECKSUM'),desc2,chk2,desc1,chk1)
  256. if die_on_fail:
  257. die(3,m)
  258. else:
  259. vmsg(m,force=verbose)
  260. return False
  261. vmsg('%s checksum OK (%s)' % (capfirst(desc1),chk1))
  262. return True
  263. def compare_or_die(val1, desc1, val2, desc2, e='Error'):
  264. if cmp(val1,val2):
  265. die(3,"%s: %s (%s) doesn't match %s (%s)"
  266. % (e,desc2,val2,desc1,val1))
  267. dmsg('%s OK (%s)' % (capfirst(desc2),val2))
  268. return True
  269. def open_file_or_exit(filename,mode):
  270. try:
  271. f = open(filename, mode)
  272. except:
  273. op = ('writing','reading')['r' in mode]
  274. die(2,"Unable to open file '%s' for %s" % (filename,op))
  275. return f
  276. def check_file_type_and_access(fname,ftype,blkdev_ok=False):
  277. a = ((os.R_OK,'read'),(os.W_OK,'writ'))
  278. access,m = a[ftype in ('output file','output directory')]
  279. ok_types = [
  280. (stat.S_ISREG,'regular file'),
  281. (stat.S_ISLNK,'symbolic link')
  282. ]
  283. if blkdev_ok: ok_types.append((stat.S_ISBLK,'block device'))
  284. if ftype == 'output directory': ok_types = [(stat.S_ISDIR, 'output directory')]
  285. try: mode = os.stat(fname).st_mode
  286. except:
  287. die(1,"Unable to stat requested %s '%s'" % (ftype,fname))
  288. for t in ok_types:
  289. if t[0](mode): break
  290. else:
  291. die(1,"Requested %s '%s' is not a %s" % (ftype,fname,
  292. ' or '.join([t[1] for t in ok_types])))
  293. if not os.access(fname, access):
  294. die(1,"Requested %s '%s' is not %sable by you" % (ftype,fname,m))
  295. return True
  296. def check_infile(f,blkdev_ok=False):
  297. return check_file_type_and_access(f,'input file',blkdev_ok=blkdev_ok)
  298. def check_outfile(f,blkdev_ok=False):
  299. return check_file_type_and_access(f,'output file',blkdev_ok=blkdev_ok)
  300. def check_outdir(f):
  301. return check_file_type_and_access(f,'output directory')
  302. def make_full_path(outdir,outfile):
  303. return os.path.normpath(os.path.join(outdir, os.path.basename(outfile)))
  304. def get_seed_file(cmd_args,nargs,invoked_as=None):
  305. from mmgen.filename import find_file_in_dir
  306. from mmgen.seed import Wallet
  307. wf = find_file_in_dir(Wallet,g.data_dir)
  308. wd_from_opt = bool(opt.hidden_incog_input_params or opt.in_fmt) # have wallet data from opt?
  309. import mmgen.opts as opts
  310. if len(cmd_args) + (wd_from_opt or bool(wf)) < nargs:
  311. opts.usage()
  312. elif len(cmd_args) > nargs:
  313. opts.usage()
  314. elif len(cmd_args) == nargs and wf and invoked_as != 'gen':
  315. msg('Warning: overriding wallet in data directory with user-supplied wallet')
  316. if cmd_args or wf:
  317. check_infile(cmd_args[0] if cmd_args else wf)
  318. return cmd_args[0] if cmd_args else (wf,None)[wd_from_opt]
  319. def get_new_passphrase(desc,passchg=False):
  320. w = '{}passphrase for {}'.format(('','new ')[bool(passchg)], desc)
  321. if opt.passwd_file:
  322. pw = ' '.join(get_words_from_file(opt.passwd_file,w))
  323. elif opt.echo_passphrase:
  324. pw = ' '.join(get_words_from_user('Enter {}: '.format(w)))
  325. else:
  326. for i in range(g.passwd_max_tries):
  327. pw = ' '.join(get_words_from_user('Enter {}: '.format(w)))
  328. pw2 = ' '.join(get_words_from_user('Repeat passphrase: '))
  329. dmsg('Passphrases: [%s] [%s]' % (pw,pw2))
  330. if pw == pw2:
  331. vmsg('Passphrases match'); break
  332. else: msg('Passphrases do not match. Try again.')
  333. else:
  334. die(2,'User failed to duplicate passphrase in %s attempts' %
  335. g.passwd_max_tries)
  336. if pw == '': qmsg('WARNING: Empty passphrase')
  337. return pw
  338. def confirm_or_exit(message,question,expect='YES',exit_msg='Exiting at user request'):
  339. m = message.strip()
  340. if m: msg(m)
  341. a = question+' ' if question[0].isupper() else \
  342. 'Are you sure you want to %s?\n' % question
  343. b = "Type uppercase '%s' to confirm: " % expect
  344. if my_raw_input(a+b).strip() != expect:
  345. die(2,exit_msg)
  346. # New function
  347. def write_data_to_file(
  348. outfile,
  349. data,
  350. desc='data',
  351. ask_write=False,
  352. ask_write_prompt='',
  353. ask_write_default_yes=True,
  354. ask_overwrite=True,
  355. ask_tty=True,
  356. no_tty=False,
  357. silent=False,
  358. binary=False
  359. ):
  360. if silent: ask_tty = ask_overwrite = False
  361. if opt.quiet: ask_overwrite = False
  362. if ask_write_default_yes == False or ask_write_prompt:
  363. ask_write = True
  364. def do_stdout():
  365. qmsg('Output to STDOUT requested')
  366. if sys.stdout.isatty():
  367. if no_tty:
  368. die(2,'Printing %s to screen is not allowed' % desc)
  369. if ask_tty and not opt.quiet:
  370. confirm_or_exit('','output %s to screen' % desc)
  371. else:
  372. try: of = os.readlink('/proc/%d/fd/1' % os.getpid()) # Linux
  373. except: of = None # Windows
  374. if of:
  375. if of[:5] == 'pipe:':
  376. if no_tty:
  377. die(2,'Writing %s to pipe is not allowed' % desc)
  378. if ask_tty and not opt.quiet:
  379. confirm_or_exit('','output %s to pipe' % desc)
  380. msg('')
  381. of2,pd = os.path.relpath(of),os.path.pardir
  382. msg("Redirecting output to file '%s'" % (of2,of)[of2[:len(pd)] == pd])
  383. else:
  384. msg('Redirecting output to file')
  385. if binary and g.platform == 'win':
  386. import msvcrt
  387. msvcrt.setmode(sys.stdout.fileno(),os.O_BINARY)
  388. sys.stdout.write(data)
  389. def do_file(outfile,ask_write_prompt):
  390. if opt.outdir and not os.path.isabs(outfile):
  391. outfile = make_full_path(opt.outdir,outfile)
  392. if ask_write:
  393. if not ask_write_prompt: ask_write_prompt = 'Save %s?' % desc
  394. if not keypress_confirm(ask_write_prompt,
  395. default_yes=ask_write_default_yes):
  396. die(1,'%s not saved' % capfirst(desc))
  397. hush = False
  398. if file_exists(outfile) and ask_overwrite:
  399. q = "File '%s' already exists\nOverwrite?" % outfile
  400. confirm_or_exit('',q)
  401. msg("Overwriting file '%s'" % outfile)
  402. hush = True
  403. f = open_file_or_exit(outfile,('w','wb')[bool(binary)])
  404. try:
  405. f.write(data)
  406. except:
  407. die(2,"Failed to write %s to file '%s'" % (desc,outfile))
  408. f.close
  409. if not (hush or silent):
  410. msg("%s written to file '%s'" % (capfirst(desc),outfile))
  411. return True
  412. if opt.stdout or outfile in ('','-'):
  413. do_stdout()
  414. elif sys.stdin.isatty() and not sys.stdout.isatty():
  415. do_stdout()
  416. else:
  417. do_file(outfile,ask_write_prompt)
  418. def get_words_from_user(prompt):
  419. # split() also strips
  420. words = my_raw_input(prompt, echo=opt.echo_passphrase).split()
  421. dmsg('Sanitized input: [%s]' % ' '.join(words))
  422. return words
  423. def get_words_from_file(infile,desc,silent=False):
  424. if not silent:
  425. qmsg("Getting %s from file '%s'" % (desc,infile))
  426. f = open_file_or_exit(infile, 'r')
  427. # split() also strips
  428. words = f.read().split()
  429. f.close()
  430. dmsg('Sanitized input: [%s]' % ' '.join(words))
  431. return words
  432. def get_words(infile,desc,prompt):
  433. if infile:
  434. return get_words_from_file(infile,desc)
  435. else:
  436. return get_words_from_user(prompt)
  437. def mmgen_decrypt_file_maybe(fn,desc=''):
  438. d = get_data_from_file(fn,desc,binary=True)
  439. have_enc_ext = get_extension(fn) == g.mmenc_ext
  440. if have_enc_ext or not is_ascii(d):
  441. m = ('Attempting to decrypt','Decrypting')[have_enc_ext]
  442. msg("%s %s '%s'" % (m,desc,fn))
  443. from mmgen.crypto import mmgen_decrypt_retry
  444. d = mmgen_decrypt_retry(d,desc)
  445. return d
  446. def get_lines_from_file(fn,desc='',trim_comments=False):
  447. dec = mmgen_decrypt_file_maybe(fn,desc)
  448. ret = dec.decode('utf8').splitlines() # DOS-safe
  449. return remove_comments(ret) if trim_comments else ret
  450. def get_data_from_user(desc='data',silent=False):
  451. data = my_raw_input('Enter %s: ' % desc, echo=opt.echo_passphrase)
  452. dmsg('User input: [%s]' % data)
  453. return data
  454. def get_data_from_file(infile,desc='data',dash=False,silent=False,binary=False):
  455. if dash and infile == '-': return sys.stdin.read()
  456. if not silent and desc:
  457. qmsg("Getting %s from file '%s'" % (desc,infile))
  458. f = open_file_or_exit(infile,('r','rb')[bool(binary)])
  459. data = f.read()
  460. f.close()
  461. return data
  462. def pwfile_reuse_warning():
  463. if 'passwd_file_used' in globals():
  464. qmsg("Reusing passphrase from file '%s' at user request" % opt.passwd_file)
  465. return True
  466. globals()['passwd_file_used'] = True
  467. return False
  468. def get_mmgen_passphrase(desc,passchg=False):
  469. prompt ='Enter {}passphrase for {}: '.format(('','old ')[bool(passchg)],desc)
  470. if opt.passwd_file:
  471. pwfile_reuse_warning()
  472. return ' '.join(get_words_from_file(opt.passwd_file,'passphrase'))
  473. else:
  474. return ' '.join(get_words_from_user(prompt))
  475. def my_raw_input(prompt,echo=True,insert_txt='',use_readline=True):
  476. try: import readline
  477. except: use_readline = False # Windows
  478. if use_readline and sys.stdout.isatty():
  479. def st_hook(): readline.insert_text(insert_txt)
  480. readline.set_startup_hook(st_hook)
  481. else:
  482. msg_r(prompt)
  483. prompt = ''
  484. from mmgen.term import kb_hold_protect
  485. kb_hold_protect()
  486. if echo or not sys.stdin.isatty():
  487. reply = raw_input(prompt)
  488. else:
  489. from getpass import getpass
  490. reply = getpass(prompt)
  491. kb_hold_protect()
  492. return reply.strip()
  493. def keypress_confirm(prompt,default_yes=False,verbose=False):
  494. from mmgen.term import get_char
  495. q = ('(y/N)','(Y/n)')[bool(default_yes)]
  496. while True:
  497. reply = get_char('%s %s: ' % (prompt, q)).strip('\n\r')
  498. if not reply:
  499. if default_yes: msg(''); return True
  500. else: msg(''); return False
  501. elif reply in 'yY': msg(''); return True
  502. elif reply in 'nN': msg(''); return False
  503. else:
  504. if verbose: msg('\nInvalid reply')
  505. else: msg_r('\r')
  506. def prompt_and_get_char(prompt,chars,enter_ok=False,verbose=False):
  507. from mmgen.term import get_char
  508. while True:
  509. reply = get_char('%s: ' % prompt).strip('\n\r')
  510. if reply in chars or (enter_ok and not reply):
  511. msg('')
  512. return reply
  513. if verbose: msg('\nInvalid reply')
  514. else: msg_r('\r')
  515. def do_pager(text):
  516. pagers,shell = ['less','more'],False
  517. # --- Non-MSYS Windows code deleted ---
  518. # raw, chop, scroll right 1 char, disable buggy line chopping for Windows
  519. os.environ['LESS'] = (('-RS -#1'),('-cR -#1'))[g.platform=='win']
  520. if 'PAGER' in os.environ and os.environ['PAGER'] != pagers[0]:
  521. pagers = [os.environ['PAGER']] + pagers
  522. for pager in pagers:
  523. end = ('\n(end of text)\n','')[pager=='less']
  524. try:
  525. from subprocess import Popen,PIPE,STDOUT
  526. p = Popen([pager], stdin=PIPE, shell=shell)
  527. except: pass
  528. else:
  529. p.communicate(text+end+'\n')
  530. msg_r('\r')
  531. break
  532. else: Msg(text+end)
  533. def do_license_msg(immed=False):
  534. if opt.quiet or g.no_license: return
  535. import mmgen.license as gpl
  536. p = "Press 'w' for conditions and warranty info, or 'c' to continue:"
  537. msg(gpl.warning)
  538. prompt = '%s ' % p.strip()
  539. from mmgen.term import get_char
  540. while True:
  541. reply = get_char(prompt, immed_chars=('','wc')[bool(immed)])
  542. if reply == 'w':
  543. do_pager(gpl.conditions)
  544. elif reply == 'c':
  545. msg(''); break
  546. else:
  547. msg_r('\r')
  548. msg('')
  549. def get_bitcoind_cfg_options(cfg_keys):
  550. cfg_file = os.path.join(g.bitcoin_data_dir,'bitcoin.conf')
  551. cfg = dict([(k,v) for k,v in [split2(str(line).translate(None,'\t '),'=')
  552. for line in get_lines_from_file(cfg_file,'')] if k in cfg_keys]) \
  553. if file_is_readable(cfg_file) else {}
  554. for k in set(cfg_keys) - set(cfg.keys()): cfg[k] = ''
  555. return cfg
  556. def get_bitcoind_auth_cookie():
  557. f = os.path.join(g.bitcoin_data_dir,('',g.testnet_name)[g.testnet],'.cookie')
  558. if file_is_readable(f):
  559. return get_lines_from_file(f,'')[0]
  560. else:
  561. return ''
  562. def bitcoin_connection():
  563. cfg = get_bitcoind_cfg_options(('rpcuser','rpcpassword'))
  564. import mmgen.rpc
  565. c = mmgen.rpc.BitcoinRPCConnection(
  566. g.rpc_host or 'localhost',
  567. g.rpc_port or (8332,18332)[g.testnet],
  568. g.rpc_user or cfg['rpcuser'], # MMGen's rpcuser,rpcpassword override bitcoind's
  569. g.rpc_password or cfg['rpcpassword'],
  570. auth_cookie=get_bitcoind_auth_cookie())
  571. # do an RPC call to make the function fail if we can't connect
  572. c.client_version = int(c.getinfo()['version'])
  573. return c