util.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2022 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: Frequently-used variables, classes and utility functions for the MMGen suite
  20. """
  21. import sys,os,time,re
  22. from .color import *
  23. from .globalvars import g
  24. from .opts import opt
  25. ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
  26. hexdigits = '0123456789abcdefABCDEF'
  27. hexdigits_uc = '0123456789ABCDEF'
  28. hexdigits_lc = '0123456789abcdef'
  29. if g.platform == 'win':
  30. def msg_r(s):
  31. try:
  32. g.stderr.write(s)
  33. g.stderr.flush()
  34. except:
  35. os.write(2,s.encode())
  36. def msg(s):
  37. msg_r(s + '\n')
  38. def Msg_r(s):
  39. try:
  40. g.stdout.write(s)
  41. g.stdout.flush()
  42. except:
  43. os.write(1,s.encode())
  44. def Msg(s):
  45. Msg_r(s + '\n')
  46. else:
  47. def msg(s):
  48. g.stderr.write(s + '\n')
  49. def msg_r(s):
  50. g.stderr.write(s)
  51. g.stderr.flush()
  52. def Msg(s):
  53. g.stdout.write(s + '\n')
  54. def Msg_r(s):
  55. g.stdout.write(s)
  56. g.stdout.flush()
  57. def rmsg(s):
  58. msg(red(s))
  59. def ymsg(s):
  60. msg(yellow(s))
  61. def gmsg(s):
  62. msg(green(s))
  63. def gmsg_r(s):
  64. msg_r(green(s))
  65. def bmsg(s):
  66. msg(blue(s))
  67. def pumsg(s):
  68. msg(purple(s))
  69. def qmsg(s):
  70. if not opt.quiet:
  71. msg(s)
  72. def qmsg_r(s):
  73. if not opt.quiet:
  74. msg_r(s)
  75. def vmsg(s,force=False):
  76. if opt.verbose or force:
  77. msg(s)
  78. def vmsg_r(s,force=False):
  79. if opt.verbose or force:
  80. msg_r(s)
  81. def Vmsg(s,force=False):
  82. if opt.verbose or force:
  83. Msg(s)
  84. def Vmsg_r(s,force=False):
  85. if opt.verbose or force:
  86. Msg_r(s)
  87. def dmsg(s):
  88. if opt.debug:
  89. msg(s)
  90. def mmsg(*args):
  91. for d in args:
  92. Msg(repr(d))
  93. def mdie(*args):
  94. mmsg(*args)
  95. sys.exit(0)
  96. def die(ev,s='',stdout=False):
  97. if isinstance(ev,int):
  98. from .exception import MMGenSystemExit,MMGenError
  99. if ev <= 2:
  100. raise MMGenSystemExit(ev,s,stdout)
  101. else:
  102. raise MMGenError(ev,s,stdout)
  103. elif isinstance(ev,str):
  104. import mmgen.exception
  105. raise getattr(mmgen.exception,ev)(s)
  106. else:
  107. raise ValueError(f'{ev}: exit value must be string or int instance')
  108. def Die(ev=0,s=''):
  109. die(ev=ev,s=s,stdout=True)
  110. def pp_fmt(d):
  111. import pprint
  112. return pprint.PrettyPrinter(indent=4,compact=False).pformat(d)
  113. def pp_msg(d):
  114. msg(pp_fmt(d))
  115. def fmt(s,indent='',strip_char=None,append='\n'):
  116. "de-indent multiple lines of text, or indent with specified string"
  117. return indent + ('\n'+indent).join([l.strip(strip_char) for l in s.strip().splitlines()]) + append
  118. def fmt_list(iterable,fmt='dfl',indent=''):
  119. "pretty-format a list"
  120. sep,lq,rq = {
  121. 'utf8': ("“, ”", "“", "”"),
  122. 'dfl': ("', '", "'", "'"),
  123. 'bare': (' ', '', '' ),
  124. 'no_quotes': (', ', '', '' ),
  125. 'no_spc': ("','", "'", "'"),
  126. 'min': (",", "'", "'"),
  127. 'col': ('\n'+indent, indent, '' ),
  128. }[fmt]
  129. return lq + sep.join(str(i) for i in iterable) + rq
  130. def list_gen(*data):
  131. """
  132. add element to list if condition is true or absent
  133. """
  134. assert type(data) in (list,tuple), f'{type(data).__name__} not in (list,tuple)'
  135. def gen():
  136. for i in data:
  137. assert type(i) == list, f'{type(i).__name__} != list'
  138. assert len(i) in (1,2), f'{len(i)} not in (1,2)'
  139. if len(i) == 1 or i[1]:
  140. yield i[0]
  141. return list(gen())
  142. def remove_dups(iterable,edesc='element',desc='list',quiet=False,hide=False):
  143. """
  144. Remove duplicate occurrences of iterable elements, preserving first occurrence
  145. If iterable is a generator, return a list, else type(iterable)
  146. """
  147. ret = []
  148. for e in iterable:
  149. if e in ret:
  150. if not quiet:
  151. ymsg(f'Warning: removing duplicate {edesc} {"(hidden)" if hide else e} in {desc}')
  152. else:
  153. ret.append(e)
  154. return ret if type(iterable).__name__ == 'generator' else type(iterable)(ret)
  155. def suf(arg,suf_type='s',verb='none'):
  156. suf_types = {
  157. 'none': {
  158. 's': ('s', ''),
  159. 'es': ('es', ''),
  160. 'ies': ('ies','y'),
  161. },
  162. 'is': {
  163. 's': ('s are', ' is'),
  164. 'es': ('es are', ' is'),
  165. 'ies': ('ies are','y is'),
  166. },
  167. 'has': {
  168. 's': ('s have', ' has'),
  169. 'es': ('es have', ' has'),
  170. 'ies': ('ies have','y has'),
  171. },
  172. }
  173. if isinstance(arg,int):
  174. n = arg
  175. elif isinstance(arg,(list,tuple,set,dict)):
  176. n = len(arg)
  177. else:
  178. die(2,f'{arg}: invalid parameter for suf()')
  179. return suf_types[verb][suf_type][n == 1]
  180. def get_extension(fn):
  181. return os.path.splitext(fn)[1][1:]
  182. def remove_extension(fn,ext):
  183. a,b = os.path.splitext(fn)
  184. return a if b[1:] == ext else fn
  185. def make_chksum_N(s,nchars,sep=False):
  186. if isinstance(s,str):
  187. s = s.encode()
  188. if nchars%4 or not (4 <= nchars <= 64):
  189. return False
  190. from hashlib import sha256
  191. s = sha256(sha256(s).digest()).hexdigest().upper()
  192. sep = ('',' ')[bool(sep)]
  193. return sep.join([s[i*4:i*4+4] for i in range(nchars//4)])
  194. def make_chksum_8(s,sep=False):
  195. from .obj import HexStr
  196. from hashlib import sha256
  197. s = HexStr(sha256(sha256(s).digest()).hexdigest()[:8].upper(),case='upper')
  198. return '{} {}'.format(s[:4],s[4:]) if sep else s
  199. def make_chksum_6(s):
  200. from .obj import HexStr
  201. from hashlib import sha256
  202. if isinstance(s,str):
  203. s = s.encode()
  204. return HexStr(sha256(s).hexdigest()[:6])
  205. def is_chksum_6(s):
  206. return len(s) == 6 and set(s) <= set(hexdigits_lc)
  207. def split_into_cols(col_wid,s):
  208. return ' '.join([s[col_wid*i:col_wid*(i+1)] for i in range(len(s)//col_wid+1)]).rstrip()
  209. def capfirst(s): # different from str.capitalize() - doesn't downcase any uc in string
  210. return s if len(s) == 0 else s[0].upper() + s[1:]
  211. def decode_timestamp(s):
  212. # tz_save = open('/etc/timezone').read().rstrip()
  213. os.environ['TZ'] = 'UTC'
  214. # os.environ['TZ'] = tz_save
  215. return int(time.mktime( time.strptime(s,'%Y%m%d_%H%M%S') ))
  216. def make_timestamp(secs=None):
  217. return '{:04d}{:02d}{:02d}_{:02d}{:02d}{:02d}'.format(*time.gmtime(
  218. int(secs) if secs != None else time.time() )[:6])
  219. def make_timestr(secs=None):
  220. return '{}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}'.format(*time.gmtime(
  221. int(secs) if secs != None else time.time() )[:6])
  222. def secs_to_dhms(secs):
  223. hrs = secs // 3600
  224. return '{}{:02d}:{:02d}:{:02d} h/m/s'.format(
  225. ('{} day{}, '.format(hrs//24,suf(hrs//24)) if hrs > 24 else ''),
  226. hrs % 24,
  227. (secs // 60) % 60,
  228. secs % 60
  229. )
  230. def secs_to_hms(secs):
  231. return '{:02d}:{:02d}:{:02d}'.format(secs//3600, (secs//60) % 60, secs % 60)
  232. def secs_to_ms(secs):
  233. return '{:02d}:{:02d}'.format(secs//60, secs % 60)
  234. def is_int(s):
  235. try:
  236. int(str(s))
  237. return True
  238. except:
  239. return False
  240. def check_int_between(val,imin,imax,desc):
  241. if not imin <= int(val) <= imax:
  242. die(1,f'{val}: invalid value for {desc} (must be between {imin} and {imax})')
  243. return int(val)
  244. def is_hex_str(s):
  245. return set(s) <= set(hexdigits)
  246. def is_hex_str_lc(s):
  247. return set(s) <= set(hexdigits_lc)
  248. def is_utf8(s):
  249. try: s.decode('utf8')
  250. except: return False
  251. else: return True
  252. def remove_whitespace(s,ws='\t\r\n '):
  253. return s.translate(dict((ord(e),None) for e in ws))
  254. def strip_comment(line):
  255. return re.sub('#.*','',line).rstrip()
  256. def strip_comments(lines):
  257. pat = re.compile('#.*')
  258. return [m for m in [pat.sub('',l).rstrip() for l in lines] if m != '']
  259. def compare_chksums(chk1,desc1,chk2,desc2,hdr='',die_on_fail=False,verbose=False):
  260. if not chk1 == chk2:
  261. fs = "{} ERROR: {} checksum ({}) doesn't match {} checksum ({})"
  262. m = fs.format((hdr+':\n ' if hdr else 'CHECKSUM'),desc2,chk2,desc1,chk1)
  263. if die_on_fail:
  264. die(3,m)
  265. else:
  266. vmsg(m,force=verbose)
  267. return False
  268. vmsg(f'{capfirst(desc1)} checksum OK ({chk1})')
  269. return True
  270. def compare_or_die(val1, desc1, val2, desc2, e='Error'):
  271. if val1 != val2:
  272. die(3,f"{e}: {desc2} ({val2}) doesn't match {desc1} ({val1})")
  273. dmsg(f'{capfirst(desc2)} OK ({val2})')
  274. return True
  275. def make_full_path(outdir,outfile):
  276. return os.path.normpath(os.path.join(outdir, os.path.basename(outfile)))
  277. class oneshot_warning:
  278. color = 'nocolor'
  279. def __init__(self,div=None,fmt_args=[],reverse=False):
  280. self.do(type(self),div,fmt_args,reverse)
  281. def do(self,wcls,div,fmt_args,reverse):
  282. def do_warning():
  283. import mmgen.color
  284. message = getattr(wcls,'message')
  285. color = getattr( mmgen.color, getattr(wcls,'color') )
  286. msg(color('WARNING: ' + message.format(*fmt_args)))
  287. if not hasattr(wcls,'data'):
  288. setattr(wcls,'data',[])
  289. data = getattr(wcls,'data')
  290. condition = (div in data) if reverse else (not div in data)
  291. if not div in data:
  292. data.append(div)
  293. if condition:
  294. do_warning()
  295. self.warning_shown = True
  296. else:
  297. self.warning_shown = False
  298. class oneshot_warning_group(oneshot_warning):
  299. def __init__(self,wcls,div=None,fmt_args=[],reverse=False):
  300. self.do(getattr(self,wcls),div,fmt_args,reverse)
  301. def stdout_or_pager(s):
  302. if opt.pager:
  303. from .ui import do_pager
  304. do_pager(s)
  305. else:
  306. Msg_r(s)
  307. def get_subclasses(cls,names=False):
  308. def gen(cls):
  309. for i in cls.__subclasses__():
  310. yield i
  311. for j in gen(i):
  312. yield j
  313. return tuple((c.__name__ for c in gen(cls)) if names else gen(cls))
  314. def async_run(coro):
  315. import asyncio
  316. return asyncio.run(coro)
  317. def wrap_ripemd160(called=[]):
  318. if not called:
  319. try:
  320. import hashlib
  321. hashlib.new('ripemd160')
  322. except ValueError:
  323. def hashlib_new_wrapper(name,*args,**kwargs):
  324. if name == 'ripemd160':
  325. return ripemd160(*args,**kwargs)
  326. else:
  327. return hashlib_new(name,*args,**kwargs)
  328. from .contrib.ripemd160 import ripemd160
  329. hashlib_new = hashlib.new
  330. hashlib.new = hashlib_new_wrapper
  331. called.append(True)
  332. def exit_if_mswin(feature):
  333. if g.platform == 'win':
  334. die(2, capfirst(feature) + ' not supported on the MSWin / MSYS2 platform' )