util.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  1. #!/usr/bin/env python
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2018 The MMGen Project <mmgen@tuta.io>
  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.encode('utf8') + '\n')
  27. def msg_r(s): sys.stderr.write(s.encode('utf8'))
  28. def Msg(s): sys.stdout.write(s.encode('utf8') + '\n')
  29. def Msg_r(s): sys.stdout.write(s.encode('utf8'))
  30. def msgred(s): msg(red(s))
  31. def rmsg(s): msg(red(s))
  32. def rmsg_r(s): msg_r(red(s))
  33. def ymsg(s): msg(yellow(s))
  34. def ymsg_r(s): msg_r(yellow(s))
  35. def gmsg(s): msg(green(s))
  36. def gmsg_r(s): msg_r(green(s))
  37. def mmsg(*args):
  38. for d in args: Msg(repr(d))
  39. def mdie(*args):
  40. mmsg(*args); sys.exit(0)
  41. def die_wait(delay,ev=0,s=''):
  42. assert type(delay) == int
  43. assert type(ev) == int
  44. if s: msg(s)
  45. time.sleep(delay)
  46. sys.exit(ev)
  47. def die_pause(ev=0,s=''):
  48. assert type(ev) == int
  49. if s: msg(s)
  50. raw_input('Press ENTER to exit')
  51. sys.exit(ev)
  52. def die(ev=0,s=''):
  53. assert type(ev) == int
  54. if s: msg(s)
  55. sys.exit(ev)
  56. def Die(ev=0,s=''):
  57. assert type(ev) == int
  58. if s: Msg(s)
  59. sys.exit(ev)
  60. def rdie(ev=0,s=''): die(ev,red(s))
  61. def ydie(ev=0,s=''): die(ev,yellow(s))
  62. def hi(): sys.stdout.write(yellow('hi'))
  63. def pformat(d):
  64. import pprint
  65. return pprint.PrettyPrinter(indent=4).pformat(d)
  66. def pmsg(*args):
  67. if not args: return
  68. msg(pformat(args if len(args) > 1 else args[0]))
  69. def pdie(*args):
  70. if not args: sys.exit(1)
  71. die(1,(pformat(args if len(args) > 1 else args[0])))
  72. def set_for_type(val,refval,desc,invert_bool=False,src=None):
  73. src_str = (''," in '{}'".format(src))[bool(src)]
  74. if type(refval) == bool:
  75. v = unicode(val).lower()
  76. if v in ('true','yes','1'): ret = True
  77. elif v in ('false','no','none','0'): ret = False
  78. else: die(1,"'{}': invalid value for '{}'{} (must be of type '{}')".format(
  79. val,desc,src_str,'bool'))
  80. if invert_bool: ret = not ret
  81. else:
  82. try:
  83. ret = type(refval)((val,not val)[invert_bool])
  84. except:
  85. die(1,u"'{}': invalid value for '{}'{} (must be of type '{}')".format(
  86. val,desc,src_str,type(refval).__name__))
  87. return ret
  88. # From 'man dd':
  89. # c=1, w=2, b=512, kB=1000, K=1024, MB=1000*1000, M=1024*1024,
  90. # GB=1000*1000*1000, G=1024*1024*1024, and so on for T, P, E, Z, Y.
  91. def parse_nbytes(nbytes):
  92. import re
  93. m = re.match(r'([0123456789]+)(.*)',nbytes)
  94. smap = ('c',1),('w',2),('b',512),('kB',1000),('K',1024),('MB',1000*1000),\
  95. ('M',1024*1024),('GB',1000*1000*1000),('G',1024*1024*1024)
  96. if m:
  97. if m.group(2):
  98. for k,v in smap:
  99. if k == m.group(2):
  100. return int(m.group(1)) * v
  101. else:
  102. msg("Valid byte specifiers: '{}'".format("' '".join([i[0] for i in smap])))
  103. else:
  104. return int(nbytes)
  105. die(1,"'{}': invalid byte specifier".format(nbytes))
  106. def check_or_create_dir(path):
  107. path_enc = path.encode('utf8')
  108. try:
  109. os.listdir(path_enc)
  110. except:
  111. try:
  112. os.makedirs(path_enc,0700)
  113. except:
  114. die(2,u"ERROR: unable to read or create path '{}'".format(path))
  115. from mmgen.opts import opt
  116. def qmsg(s,alt=None):
  117. if opt.quiet:
  118. if alt != None: msg(alt)
  119. else: msg(s)
  120. def qmsg_r(s,alt=None):
  121. if opt.quiet:
  122. if alt != None: msg_r(alt)
  123. else: msg_r(s)
  124. def vmsg(s,force=False):
  125. if opt.verbose or force: msg(s)
  126. def vmsg_r(s,force=False):
  127. if opt.verbose or force: msg_r(s)
  128. def Vmsg(s,force=False):
  129. if opt.verbose or force: Msg(s)
  130. def Vmsg_r(s,force=False):
  131. if opt.verbose or force: Msg_r(s)
  132. def dmsg(s):
  133. if opt.debug: msg(s)
  134. def suf(arg,suf_type='s'):
  135. suf_types = { 's': ('s',''), 'es': ('es','') }
  136. assert suf_type in suf_types
  137. t = type(arg)
  138. if t == int:
  139. n = arg
  140. elif any(issubclass(t,c) for c in (list,tuple,set,dict)):
  141. n = len(arg)
  142. else:
  143. die(2,'{}: invalid parameter for suf()'.format(arg))
  144. return suf_types[suf_type][n==1]
  145. def get_extension(f):
  146. a,b = os.path.splitext(f)
  147. return ('',b[1:])[len(b) > 1]
  148. def remove_extension(f,e):
  149. a,b = os.path.splitext(f)
  150. return (f,a)[len(b)>1 and b[1:]==e]
  151. def make_chksum_N(s,nchars,sep=False):
  152. if nchars%4 or not (4 <= nchars <= 64): return False
  153. s = sha256(sha256(s).digest()).hexdigest().upper()
  154. sep = ('',' ')[bool(sep)]
  155. return sep.join([s[i*4:i*4+4] for i in range(nchars/4)])
  156. def make_chksum_8(s,sep=False):
  157. from mmgen.obj import HexStr
  158. s = HexStr(sha256(sha256(s).digest()).hexdigest()[:8].upper(),case='upper')
  159. return '{} {}'.format(s[:4],s[4:]) if sep else s
  160. def make_chksum_6(s):
  161. from mmgen.obj import HexStr
  162. return HexStr(sha256(s).hexdigest()[:6])
  163. def is_chksum_6(s): return len(s) == 6 and is_hex_str_lc(s)
  164. def make_iv_chksum(s): return sha256(s).hexdigest()[:8].upper()
  165. def splitN(s,n,sep=None): # always return an n-element list
  166. ret = s.split(sep,n-1)
  167. return ret + ['' for i in range(n-len(ret))]
  168. def split2(s,sep=None): return splitN(s,2,sep) # always return a 2-element list
  169. def split3(s,sep=None): return splitN(s,3,sep) # always return a 3-element list
  170. def split_into_cols(col_wid,s):
  171. return ' '.join([s[col_wid*i:col_wid*(i+1)]
  172. for i in range(len(s)/col_wid+1)]).rstrip()
  173. def capfirst(s): # different from str.capitalize() - doesn't downcase any uc in string
  174. return s if len(s) == 0 else s[0].upper() + s[1:]
  175. def decode_timestamp(s):
  176. # with open('/etc/timezone') as f:
  177. # tz_save = f.read().rstrip()
  178. os.environ['TZ'] = 'UTC'
  179. ts = time.strptime(s,'%Y%m%d_%H%M%S')
  180. t = time.mktime(ts)
  181. # os.environ['TZ'] = tz_save
  182. return int(t)
  183. def make_timestamp(secs=None):
  184. t = int(secs) if secs else time.time()
  185. tv = time.gmtime(t)[:6]
  186. return '{:04d}{:02d}{:02d}_{:02d}{:02d}{:02d}'.format(*tv)
  187. def make_timestr(secs=None):
  188. t = int(secs) if secs else time.time()
  189. tv = time.gmtime(t)[:6]
  190. return '{:04d}/{:02d}/{:02d} {:02d}:{:02d}:{:02d}'.format(*tv)
  191. def secs_to_dhms(secs):
  192. dsecs = secs/3600
  193. return '{}{:02d}:{:02d}:{:02d}'.format(
  194. ('','{} day{}, '.format(dsecs/24,suf(dsecs/24)))[dsecs > 24],
  195. dsecs % 24, (secs/60) % 60, secs % 60)
  196. def secs_to_hms(secs):
  197. return '{:02d}:{:02d}:{:02d}'.format(secs/3600, (secs/60) % 60, secs % 60)
  198. def secs_to_ms(secs):
  199. return '{:02d}:{:02d}'.format(secs/60, secs % 60)
  200. def is_int(s):
  201. try:
  202. int(str(s))
  203. return True
  204. except:
  205. return False
  206. # https://en.wikipedia.org/wiki/Base32#RFC_4648_Base32_alphabet
  207. # https://tools.ietf.org/html/rfc4648
  208. def is_hex_str(s): return set(list(s.lower())) <= set(list(hexdigits.lower()))
  209. def is_hex_str_lc(s): return set(list(s)) <= set(list(hexdigits.lower()))
  210. def is_hex_str_uc(s): return set(list(s)) <= set(list(hexdigits.upper()))
  211. def is_b58_str(s): return set(list(s)) <= set(baseconv.digits['b58'])
  212. def is_b32_str(s): return set(list(s)) <= set(baseconv.digits['b32'])
  213. def is_ascii(s,enc='ascii'):
  214. try: s.decode(enc)
  215. except: return False
  216. else: return True
  217. def is_utf8(s): return is_ascii(s,enc='utf8')
  218. class baseconv(object):
  219. mn_base = 1626 # tirosh list is 1633 words long!
  220. digits = {
  221. 'electrum': tuple(__import__('mmgen.mn_electrum',fromlist=['words']).words.split()),
  222. 'tirosh': tuple(__import__('mmgen.mn_tirosh',fromlist=['words']).words.split()[:mn_base]),
  223. 'b58': tuple('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'),
  224. 'b32': tuple('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'),
  225. 'b16': tuple('0123456789abcdef'),
  226. 'b10': tuple('0123456789'),
  227. 'b8': tuple('01234567'),
  228. }
  229. wl_chksums = {
  230. 'electrum': '5ca31424',
  231. 'tirosh': '48f05e1f', # tirosh truncated to mn_base (1626)
  232. # 'tirosh1633': '1a5faeff'
  233. }
  234. b58pad_lens = [(16,22), (24,33), (32,44)]
  235. b58pad_lens_rev = [(v,k) for k,v in b58pad_lens]
  236. @classmethod
  237. def b58encode(cls,s,pad=None):
  238. pad = cls.get_pad(s,pad,'en',cls.b58pad_lens,[bytes])
  239. return cls.fromhex(hexlify(s),'b58',pad=pad,tostr=True)
  240. @classmethod
  241. def b58decode(cls,s,pad=None):
  242. pad = cls.get_pad(s,pad,'de',cls.b58pad_lens_rev,[bytes,unicode])
  243. return unhexlify(cls.tohex(s,'b58',pad=pad*2 if pad else None))
  244. @staticmethod
  245. def get_pad(s,pad,op,pad_map,ok_types):
  246. m = "b58{}code() input must be one of {}, not '{}'"
  247. assert type(s) in ok_types, m.format(op,repr([t.__name__ for t in ok_types]),type(s).__name__)
  248. if pad:
  249. assert type(pad) == bool, "'pad' must be boolean type"
  250. d = dict(pad_map)
  251. assert len(s) in d, 'Invalid data length for b58{}code(pad=True)'.format(op)
  252. return d[len(s)]
  253. else:
  254. return None
  255. @classmethod
  256. def get_wordlist_chksum(cls,wl_id):
  257. return sha256(' '.join(cls.digits[wl_id])).hexdigest()[:8]
  258. @classmethod
  259. def check_wordlists(cls):
  260. for k,v in cls.wl_chksums.items(): assert cls.get_wordlist_chksum(k) == v
  261. @classmethod
  262. def check_wordlist(cls,wl_id):
  263. wl = baseconv.digits[wl_id]
  264. Msg('Wordlist: {}\nLength: {} words'.format(capfirst(wl_id),len(wl)))
  265. new_chksum = cls.get_wordlist_chksum(wl_id)
  266. a,b = 'generated checksum','saved checksum'
  267. compare_chksums(new_chksum,a,cls.wl_chksums[wl_id],b,die_on_fail=True)
  268. Msg('Checksum {} matches'.format(new_chksum))
  269. Msg('List is sorted') if tuple(sorted(wl)) == wl else die(3,'ERROR: List is not sorted!')
  270. @classmethod
  271. def tohex(cls,words_arg,wl_id,pad=None):
  272. words = words_arg if type(words_arg) in (list,tuple) else tuple(words_arg.strip())
  273. wl = cls.digits[wl_id]
  274. base = len(wl)
  275. if not set(words) <= set(wl):
  276. die(2,'{} is not in {} (base{}) format'.format(repr(words_arg),wl_id,base))
  277. deconv = [wl.index(words[::-1][i])*(base**i) for i in range(len(words))]
  278. ret = ('{:0{w}x}'.format(sum(deconv),w=pad or 0))
  279. return ('','0')[len(ret) % 2] + ret
  280. @classmethod
  281. def fromhex(cls,hexnum,wl_id,pad=None,tostr=False):
  282. hexnum = hexnum.strip()
  283. if not is_hex_str(hexnum):
  284. die(2,"'{}': not a hexadecimal number".format(hexnum))
  285. wl = cls.digits[wl_id]
  286. base = len(wl)
  287. num,ret = int(hexnum,16),[]
  288. while num:
  289. ret.append(num % base)
  290. num /= base
  291. o = [wl[n] for n in [0] * ((pad or 0)-len(ret)) + ret[::-1]]
  292. return ''.join(o) if tostr else o
  293. baseconv.check_wordlists()
  294. def match_ext(addr,ext):
  295. return addr.split('.')[-1] == ext
  296. def file_exists(f):
  297. try:
  298. os.stat(f)
  299. return True
  300. except:
  301. return False
  302. def file_is_readable(f):
  303. from stat import S_IREAD
  304. try:
  305. assert os.stat(f).st_mode & S_IREAD
  306. except:
  307. return False
  308. else:
  309. return True
  310. def get_from_brain_opt_params():
  311. l,p = opt.from_brain.split(',')
  312. return(int(l),p)
  313. def pretty_hexdump(data,gw=2,cols=8,line_nums=False):
  314. r = (0,1)[bool(len(data) % gw)]
  315. return ''.join(
  316. [
  317. ('' if (line_nums == False or i % cols) else '{:06x}: '.format(i*gw)) +
  318. hexlify(data[i*gw:i*gw+gw]) + ('\n',' ')[bool((i+1) % cols)]
  319. for i in range(len(data)/gw + r)
  320. ]
  321. ).rstrip() + '\n'
  322. def decode_pretty_hexdump(data):
  323. from string import hexdigits
  324. pat = r'^[{}]+:\s+'.format(hexdigits)
  325. lines = [re.sub(pat,'',l) for l in data.splitlines()]
  326. try:
  327. return unhexlify(''.join((''.join(lines).split())))
  328. except:
  329. msg('Data not in hexdump format')
  330. return False
  331. def strip_comments(line):
  332. return re.sub(ur'\s+$',u'',re.sub(ur'#.*',u'',line,1))
  333. def remove_comments(lines):
  334. return [m for m in [strip_comments(l) for l in lines] if m != '']
  335. from mmgen.globalvars import g
  336. def start_mscolor():
  337. try:
  338. import colorama
  339. colorama.init(strip=True,convert=True)
  340. except:
  341. msg('Import of colorama module failed')
  342. def get_hash_params(hash_preset):
  343. if hash_preset in g.hash_presets:
  344. return g.hash_presets[hash_preset] # N,p,r,buflen
  345. else: # Shouldn't be here
  346. die(3,"{}: invalid 'hash_preset' value".format(hash_preset))
  347. def compare_chksums(chk1,desc1,chk2,desc2,hdr='',die_on_fail=False,verbose=False):
  348. if not chk1 == chk2:
  349. fs = "{} ERROR: {} checksum ({}) doesn't match {} checksum ({})"
  350. m = fs.format((hdr+':\n ' if hdr else 'CHECKSUM'),desc2,chk2,desc1,chk1)
  351. if die_on_fail:
  352. die(3,m)
  353. else:
  354. vmsg(m,force=verbose)
  355. return False
  356. vmsg('{} checksum OK ({})'.format(capfirst(desc1),chk1))
  357. return True
  358. def compare_or_die(val1, desc1, val2, desc2, e='Error'):
  359. if cmp(val1,val2):
  360. die(3,"{}: {} ({}) doesn't match {} ({})".format(e,desc2,val2,desc1,val1))
  361. dmsg('{} OK ({})'.format(capfirst(desc2),val2))
  362. return True
  363. def open_file_or_exit(filename,mode,silent=False):
  364. try:
  365. f = open(filename, mode)
  366. except:
  367. op = ('writing','reading')['r' in mode]
  368. die(2,("Unable to open file '{}' for {}".format(filename,op),'')[silent])
  369. return f
  370. def check_file_type_and_access(fname,ftype,blkdev_ok=False):
  371. a = ((os.R_OK,'read'),(os.W_OK,'writ'))
  372. access,m = a[ftype in ('output file','output directory')]
  373. ok_types = [
  374. (stat.S_ISREG,'regular file'),
  375. (stat.S_ISLNK,'symbolic link')
  376. ]
  377. if blkdev_ok: ok_types.append((stat.S_ISBLK,'block device'))
  378. if ftype == 'output directory': ok_types = [(stat.S_ISDIR, 'output directory')]
  379. try: mode = os.stat(fname).st_mode
  380. except:
  381. die(1,u"Unable to stat requested {} '{}'".format(ftype,fname))
  382. for t in ok_types:
  383. if t[0](mode): break
  384. else:
  385. die(1,"Requested {} '{}' is not a {}".format(ftype,fname,' or '.join([t[1] for t in ok_types])))
  386. if not os.access(fname, access):
  387. die(1,"Requested {} '{}' is not {}able by you".format(ftype,fname,m))
  388. return True
  389. def check_infile(f,blkdev_ok=False):
  390. return check_file_type_and_access(f,'input file',blkdev_ok=blkdev_ok)
  391. def check_outfile(f,blkdev_ok=False):
  392. return check_file_type_and_access(f,'output file',blkdev_ok=blkdev_ok)
  393. def check_outdir(f):
  394. return check_file_type_and_access(f,'output directory')
  395. def make_full_path(outdir,outfile):
  396. return os.path.normpath(os.path.join(outdir, os.path.basename(outfile)))
  397. def get_seed_file(cmd_args,nargs,invoked_as=None):
  398. from mmgen.filename import find_file_in_dir
  399. from mmgen.seed import Wallet
  400. wf = find_file_in_dir(Wallet,g.data_dir)
  401. wd_from_opt = bool(opt.hidden_incog_input_params or opt.in_fmt) # have wallet data from opt?
  402. import mmgen.opts as opts
  403. if len(cmd_args) + (wd_from_opt or bool(wf)) < nargs:
  404. if not wf:
  405. msg('No default wallet found, and no other seed source was specified')
  406. opts.usage()
  407. elif len(cmd_args) > nargs:
  408. opts.usage()
  409. elif len(cmd_args) == nargs and wf and invoked_as != 'gen':
  410. msg('Warning: overriding default wallet with user-supplied wallet')
  411. if cmd_args or wf:
  412. check_infile(cmd_args[0] if cmd_args else wf)
  413. return cmd_args[0] if cmd_args else (wf,None)[wd_from_opt]
  414. def get_new_passphrase(desc,passchg=False):
  415. w = '{}passphrase for {}'.format(('','new ')[bool(passchg)], desc)
  416. if opt.passwd_file:
  417. pw = ' '.join(get_words_from_file(opt.passwd_file,w))
  418. elif opt.echo_passphrase:
  419. pw = ' '.join(get_words_from_user('Enter {}: '.format(w)))
  420. else:
  421. for i in range(g.passwd_max_tries):
  422. pw = ' '.join(get_words_from_user('Enter {}: '.format(w)))
  423. pw2 = ' '.join(get_words_from_user('Repeat passphrase: '))
  424. dmsg('Passphrases: [{}] [{}]'.format(pw,pw2))
  425. if pw == pw2:
  426. vmsg('Passphrases match'); break
  427. else: msg('Passphrases do not match. Try again.')
  428. else:
  429. die(2,'User failed to duplicate passphrase in {} attempts'.format(g.passwd_max_tries))
  430. if pw == '': qmsg('WARNING: Empty passphrase')
  431. return pw
  432. def confirm_or_exit(message,q,expect='YES',exit_msg='Exiting at user request'):
  433. m = message.strip()
  434. if m: msg(m)
  435. a = q+' ' if q[0].isupper() else 'Are you sure you want to {}?\n'.format(q)
  436. b = "Type uppercase '{}' to confirm: ".format(expect)
  437. if my_raw_input(a+b).strip() != expect:
  438. die(1,exit_msg)
  439. def write_data_to_file(
  440. outfile,
  441. data,
  442. desc='data',
  443. ask_write=False,
  444. ask_write_prompt='',
  445. ask_write_default_yes=True,
  446. ask_overwrite=True,
  447. ask_tty=True,
  448. no_tty=False,
  449. silent=False,
  450. binary=False
  451. ):
  452. if silent: ask_tty = ask_overwrite = False
  453. if opt.quiet: ask_overwrite = False
  454. if ask_write_default_yes == False or ask_write_prompt:
  455. ask_write = True
  456. if not binary and type(data) == unicode:
  457. data = data.encode('utf8')
  458. def do_stdout():
  459. qmsg('Output to STDOUT requested')
  460. if sys.stdout.isatty():
  461. if no_tty:
  462. die(2,'Printing {} to screen is not allowed'.format(desc))
  463. if (ask_tty and not opt.quiet) or binary:
  464. confirm_or_exit('','output {} to screen'.format(desc))
  465. else:
  466. try: of = os.readlink('/proc/{}/fd/1'.format(os.getpid())) # Linux
  467. except: of = None # Windows
  468. if of:
  469. if of[:5] == 'pipe:':
  470. if no_tty:
  471. die(2,'Writing {} to pipe is not allowed'.format(desc))
  472. if ask_tty and not opt.quiet:
  473. confirm_or_exit('','output {} to pipe'.format(desc))
  474. msg('')
  475. of2,pd = os.path.relpath(of),os.path.pardir
  476. msg(u"Redirecting output to file '{}'".format((of2,of)[of2[:len(pd)] == pd]))
  477. else:
  478. msg('Redirecting output to file')
  479. if binary and g.platform == 'win':
  480. import msvcrt
  481. msvcrt.setmode(sys.stdout.fileno(),os.O_BINARY)
  482. sys.stdout.write(data)
  483. def do_file(outfile,ask_write_prompt):
  484. if opt.outdir and not os.path.isabs(outfile):
  485. outfile = make_full_path(opt.outdir,outfile)
  486. if ask_write:
  487. if not ask_write_prompt: ask_write_prompt = 'Save {}?'.format(desc)
  488. if not keypress_confirm(ask_write_prompt,
  489. default_yes=ask_write_default_yes):
  490. die(1,'{} not saved'.format(capfirst(desc)))
  491. hush = False
  492. if file_exists(outfile) and ask_overwrite:
  493. q = u"File '{}' already exists\nOverwrite?".format(outfile)
  494. confirm_or_exit('',q)
  495. msg(u"Overwriting file '{}'".format(outfile))
  496. hush = True
  497. f = open_file_or_exit(outfile,('w','wb')[bool(binary)])
  498. try:
  499. f.write(data)
  500. except:
  501. die(2,u"Failed to write {} to file '{}'".format(desc,outfile))
  502. f.close
  503. if not (hush or silent):
  504. msg(u"{} written to file '{}'".format(capfirst(desc),outfile))
  505. return True
  506. if opt.stdout or outfile in ('','-'):
  507. do_stdout()
  508. elif sys.stdin.isatty() and not sys.stdout.isatty():
  509. do_stdout()
  510. else:
  511. do_file(outfile,ask_write_prompt)
  512. def get_words_from_user(prompt):
  513. # split() also strips
  514. words = my_raw_input(prompt, echo=opt.echo_passphrase).split()
  515. dmsg('Sanitized input: [{}]'.format(' '.join(words)))
  516. return words
  517. def get_words_from_file(infile,desc,silent=False):
  518. if not silent:
  519. qmsg(u"Getting {} from file '{}'".format(desc,infile))
  520. f = open_file_or_exit(infile, 'r')
  521. # split() also strips
  522. words = f.read().split()
  523. f.close()
  524. dmsg('Sanitized input: [{}]'.format(' '.join(words)))
  525. return words
  526. def get_words(infile,desc,prompt):
  527. if infile:
  528. return get_words_from_file(infile,desc)
  529. else:
  530. return get_words_from_user(prompt)
  531. def mmgen_decrypt_file_maybe(fn,desc='',silent=False):
  532. d = get_data_from_file(fn,desc,binary=True,silent=silent)
  533. have_enc_ext = get_extension(fn) == g.mmenc_ext
  534. if have_enc_ext or not is_utf8(d):
  535. m = ('Attempting to decrypt','Decrypting')[have_enc_ext]
  536. msg(u"{} {} '{}'".format(m,desc,fn))
  537. from mmgen.crypto import mmgen_decrypt_retry
  538. d = mmgen_decrypt_retry(d,desc)
  539. return d
  540. def get_lines_from_file(fn,desc='',trim_comments=False,silent=False):
  541. dec = mmgen_decrypt_file_maybe(fn,desc,silent=silent)
  542. ret = dec.decode('utf8').splitlines() # DOS-safe
  543. if trim_comments: ret = remove_comments(ret)
  544. dmsg(u"Got {} lines from file '{}'".format(len(ret),fn))
  545. return ret
  546. def get_data_from_user(desc='data',silent=False):
  547. p = ('','Enter {}: '.format(desc))[g.stdin_tty]
  548. data = my_raw_input(p,echo=opt.echo_passphrase)
  549. dmsg('User input: [{}]'.format(data))
  550. return data
  551. def get_data_from_file(infile,desc='data',dash=False,silent=False,binary=False):
  552. if dash and infile == '-': return sys.stdin.read()
  553. if not opt.quiet and not silent and desc:
  554. qmsg(u"Getting {} from file '{}'".format(desc,infile))
  555. f = open_file_or_exit(infile,('r','rb')[bool(binary)],silent=silent)
  556. data = f.read()
  557. f.close()
  558. return data
  559. def pwfile_reuse_warning():
  560. if 'passwd_file_used' in globals():
  561. qmsg(u"Reusing passphrase from file '{}' at user request".format(opt.passwd_file))
  562. return True
  563. globals()['passwd_file_used'] = True
  564. return False
  565. def get_mmgen_passphrase(desc,passchg=False):
  566. prompt ='Enter {}passphrase for {}: '.format(('','old ')[bool(passchg)],desc)
  567. if opt.passwd_file:
  568. pwfile_reuse_warning()
  569. return ' '.join(get_words_from_file(opt.passwd_file,'passphrase'))
  570. else:
  571. return ' '.join(get_words_from_user(prompt))
  572. def my_raw_input(prompt,echo=True,insert_txt='',use_readline=True):
  573. try: import readline
  574. except: use_readline = False # Windows
  575. if use_readline and sys.stdout.isatty():
  576. def st_hook(): readline.insert_text(insert_txt)
  577. readline.set_startup_hook(st_hook)
  578. else:
  579. msg_r(prompt)
  580. prompt = ''
  581. from mmgen.term import kb_hold_protect
  582. kb_hold_protect()
  583. if echo or not sys.stdin.isatty():
  584. reply = raw_input(prompt.encode('utf8'))
  585. else:
  586. from getpass import getpass
  587. reply = getpass(prompt)
  588. kb_hold_protect()
  589. return reply.strip()
  590. def keypress_confirm(prompt,default_yes=False,verbose=False,no_nl=False):
  591. from mmgen.term import get_char
  592. q = ('(y/N)','(Y/n)')[bool(default_yes)]
  593. p = u'{} {}: '.format(prompt,q)
  594. nl = ('\n','\r{}\r'.format(' '*len(p)))[no_nl]
  595. if opt.accept_defaults:
  596. msg(p)
  597. return (False,True)[default_yes]
  598. while True:
  599. reply = get_char(p).strip('\n\r')
  600. if not reply:
  601. if default_yes: msg_r(nl); return True
  602. else: msg_r(nl); return False
  603. elif reply in 'yY': msg_r(nl); return True
  604. elif reply in 'nN': msg_r(nl); return False
  605. else:
  606. if verbose: msg('\nInvalid reply')
  607. else: msg_r('\r')
  608. def prompt_and_get_char(prompt,chars,enter_ok=False,verbose=False):
  609. from mmgen.term import get_char
  610. while True:
  611. reply = get_char('{}: '.format(prompt)).strip('\n\r')
  612. if reply in chars or (enter_ok and not reply):
  613. msg('')
  614. return reply
  615. if verbose: msg('\nInvalid reply')
  616. else: msg_r('\r')
  617. def do_pager(text):
  618. pagers,shell = ['less','more'],False
  619. # --- Non-MSYS Windows code deleted ---
  620. # raw, chop, horiz scroll 8 chars, disable buggy line chopping in MSYS
  621. os.environ['LESS'] = (('--shift 8 -RS'),('-cR -#1'))[g.platform=='win']
  622. if 'PAGER' in os.environ and os.environ['PAGER'] != pagers[0]:
  623. pagers = [os.environ['PAGER']] + pagers
  624. text = text.encode('utf8')
  625. for pager in pagers:
  626. end = ('\n(end of text)\n','')[pager=='less']
  627. try:
  628. from subprocess import Popen,PIPE,STDOUT
  629. p = Popen([pager], stdin=PIPE, shell=shell)
  630. except: pass
  631. else:
  632. p.communicate(text+end+'\n')
  633. msg_r('\r')
  634. break
  635. else: Msg(text+end)
  636. def do_license_msg(immed=False):
  637. if opt.quiet or g.no_license or opt.yes or not g.stdin_tty: return
  638. import mmgen.license as gpl
  639. p = "Press 'w' for conditions and warranty info, or 'c' to continue:"
  640. msg(gpl.warning)
  641. prompt = '{} '.format(p.strip())
  642. from mmgen.term import get_char
  643. while True:
  644. reply = get_char(prompt, immed_chars=('','wc')[bool(immed)])
  645. if reply == 'w':
  646. do_pager(gpl.conditions)
  647. elif reply == 'c':
  648. msg(''); break
  649. else:
  650. msg_r('\r')
  651. msg('')
  652. def get_daemon_cfg_options(cfg_keys):
  653. cfg_file = os.path.join(g.proto.daemon_data_dir,g.proto.name+'.conf')
  654. try:
  655. lines = get_lines_from_file(cfg_file,'',silent=bool(opt.quiet))
  656. kv_pairs = [split2(str(line).translate(None,'\t '),'=') for line in lines]
  657. cfg = dict([(k,v) for k,v in kv_pairs if k in cfg_keys])
  658. except:
  659. vmsg("Warning: '{}' does not exist or is unreadable".format(cfg_file))
  660. cfg = {}
  661. for k in set(cfg_keys) - set(cfg.keys()): cfg[k] = ''
  662. return cfg
  663. def get_coin_daemon_auth_cookie():
  664. f = os.path.join(g.proto.daemon_data_dir,g.proto.daemon_data_subdir,'.cookie')
  665. return get_lines_from_file(f,'')[0] if file_is_readable(f) else ''
  666. def rpc_init(reinit=False):
  667. if not 'rpc' in g.proto.mmcaps:
  668. die(1,'Coin daemon operations not supported for coin {}!'.format(g.coin))
  669. if g.rpch != None and not reinit: return g.rpch
  670. def check_chainfork_mismatch(conn):
  671. block0 = conn.getblockhash(0)
  672. latest = conn.getblockcount()
  673. try:
  674. assert block0 == g.proto.block0,'Incorrect Genesis block for {}'.format(g.proto.__name__)
  675. for fork in g.proto.forks:
  676. if fork[0] == None or latest < fork[0]: break
  677. bhash = conn.getblockhash(fork[0])
  678. assert bhash == fork[1], (
  679. 'Bad block hash at fork block {}. Is this the {} chain?'.format(fork[0],fork[2].upper()))
  680. except Exception as e:
  681. die(2,"{}\n'{c}' requested, but this is not the {c} chain!".format(e,c=g.coin))
  682. def check_chaintype_mismatch():
  683. try:
  684. if g.regtest: assert g.chain == 'regtest','--regtest option selected, but chain is not regtest'
  685. if g.testnet: assert g.chain != 'mainnet','--testnet option selected, but chain is mainnet'
  686. if not g.testnet: assert g.chain == 'mainnet','mainnet selected, but chain is not mainnet'
  687. except Exception as e:
  688. die(1,'{}\nChain is {}!'.format(e,g.chain))
  689. cfg = get_daemon_cfg_options(('rpcuser','rpcpassword'))
  690. import mmgen.rpc
  691. conn = mmgen.rpc.CoinDaemonRPCConnection(
  692. g.rpc_host or 'localhost',
  693. g.rpc_port or g.proto.rpc_port,
  694. g.rpc_user or cfg['rpcuser'], # MMGen's rpcuser,rpcpassword override coin daemon's
  695. g.rpc_password or cfg['rpcpassword'],
  696. auth_cookie=get_coin_daemon_auth_cookie())
  697. if not g.daemon_version: # First call
  698. if g.bob or g.alice:
  699. import regtest as rt
  700. rt.user(('alice','bob')[g.bob],quiet=True)
  701. g.daemon_version = int(conn.getnetworkinfo()['version'])
  702. g.chain = conn.getblockchaininfo()['chain']
  703. if g.chain != 'regtest': g.chain += 'net'
  704. assert g.chain in g.chains
  705. check_chaintype_mismatch()
  706. if g.chain == 'mainnet': # skip this for testnet, as Genesis block may change
  707. check_chainfork_mismatch(conn)
  708. g.rpch = conn
  709. return conn
  710. def format_par(s,indent=0,width=80,as_list=False):
  711. words,lines = s.split(),[]
  712. assert width >= indent + 4,'width must be >= indent + 4'
  713. while words:
  714. line = ''
  715. while len(line) <= (width-indent) and words:
  716. if line and len(line) + len(words[0]) + 1 > width-indent: break
  717. line += ('',' ')[bool(line)] + words.pop(0)
  718. lines.append(' '*indent + line)
  719. return lines if as_list else '\n'.join(lines) + '\n'