util.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2023 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: 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. 'list': ('\n- '+indent, '- '+indent, '' ),
  129. }[fmt]
  130. return lq + sep.join(str(i) for i in iterable) + rq
  131. def list_gen(*data):
  132. """
  133. add element to list if condition is true or absent
  134. """
  135. assert type(data) in (list,tuple), f'{type(data).__name__} not in (list,tuple)'
  136. def gen():
  137. for i in data:
  138. assert type(i) == list, f'{type(i).__name__} != list'
  139. assert len(i) in (1,2), f'{len(i)} not in (1,2)'
  140. if len(i) == 1 or i[1]:
  141. yield i[0]
  142. return list(gen())
  143. def remove_dups(iterable,edesc='element',desc='list',quiet=False,hide=False):
  144. """
  145. Remove duplicate occurrences of iterable elements, preserving first occurrence
  146. If iterable is a generator, return a list, else type(iterable)
  147. """
  148. ret = []
  149. for e in iterable:
  150. if e in ret:
  151. if not quiet:
  152. ymsg(f'Warning: removing duplicate {edesc} {"(hidden)" if hide else e} in {desc}')
  153. else:
  154. ret.append(e)
  155. return ret if type(iterable).__name__ == 'generator' else type(iterable)(ret)
  156. def contains_any(target_list,source_list):
  157. return any(map(target_list.count,source_list))
  158. def suf(arg,suf_type='s',verb='none'):
  159. suf_types = {
  160. 'none': {
  161. 's': ('s', ''),
  162. 'es': ('es', ''),
  163. 'ies': ('ies','y'),
  164. },
  165. 'is': {
  166. 's': ('s are', ' is'),
  167. 'es': ('es are', ' is'),
  168. 'ies': ('ies are','y is'),
  169. },
  170. 'has': {
  171. 's': ('s have', ' has'),
  172. 'es': ('es have', ' has'),
  173. 'ies': ('ies have','y has'),
  174. },
  175. }
  176. if isinstance(arg,int):
  177. n = arg
  178. elif isinstance(arg,(list,tuple,set,dict)):
  179. n = len(arg)
  180. else:
  181. die(2,f'{arg}: invalid parameter for suf()')
  182. return suf_types[verb][suf_type][n == 1]
  183. def get_extension(fn):
  184. return os.path.splitext(fn)[1][1:]
  185. def remove_extension(fn,ext):
  186. a,b = os.path.splitext(fn)
  187. return a if b[1:] == ext else fn
  188. def make_chksum_N(s,nchars,sep=False):
  189. if isinstance(s,str):
  190. s = s.encode()
  191. if nchars%4 or not (4 <= nchars <= 64):
  192. return False
  193. from hashlib import sha256
  194. s = sha256(sha256(s).digest()).hexdigest().upper()
  195. sep = ('',' ')[bool(sep)]
  196. return sep.join([s[i*4:i*4+4] for i in range(nchars//4)])
  197. def make_chksum_8(s,sep=False):
  198. from .obj import HexStr
  199. from hashlib import sha256
  200. s = HexStr(sha256(sha256(s).digest()).hexdigest()[:8].upper(),case='upper')
  201. return '{} {}'.format(s[:4],s[4:]) if sep else s
  202. def make_chksum_6(s):
  203. from .obj import HexStr
  204. from hashlib import sha256
  205. if isinstance(s,str):
  206. s = s.encode()
  207. return HexStr(sha256(s).hexdigest()[:6])
  208. def is_chksum_6(s):
  209. return len(s) == 6 and set(s) <= set(hexdigits_lc)
  210. def split_into_cols(col_wid,s):
  211. return ' '.join([s[col_wid*i:col_wid*(i+1)] for i in range(len(s)//col_wid+1)]).rstrip()
  212. def capfirst(s): # different from str.capitalize() - doesn't downcase any uc in string
  213. return s if len(s) == 0 else s[0].upper() + s[1:]
  214. def decode_timestamp(s):
  215. # tz_save = open('/etc/timezone').read().rstrip()
  216. os.environ['TZ'] = 'UTC'
  217. # os.environ['TZ'] = tz_save
  218. return int(time.mktime( time.strptime(s,'%Y%m%d_%H%M%S') ))
  219. def make_timestamp(secs=None):
  220. return '{:04d}{:02d}{:02d}_{:02d}{:02d}{:02d}'.format(*time.gmtime(
  221. int(secs) if secs != None else time.time() )[:6])
  222. def make_timestr(secs=None):
  223. return '{}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}'.format(*time.gmtime(
  224. int(secs) if secs != None else time.time() )[:6])
  225. def secs_to_dhms(secs):
  226. hrs = secs // 3600
  227. return '{}{:02d}:{:02d}:{:02d} h/m/s'.format(
  228. ('{} day{}, '.format(hrs//24,suf(hrs//24)) if hrs > 24 else ''),
  229. hrs % 24,
  230. (secs // 60) % 60,
  231. secs % 60
  232. )
  233. def secs_to_hms(secs):
  234. return '{:02d}:{:02d}:{:02d}'.format(secs//3600, (secs//60) % 60, secs % 60)
  235. def secs_to_ms(secs):
  236. return '{:02d}:{:02d}'.format(secs//60, secs % 60)
  237. def is_int(s):
  238. try:
  239. int(str(s))
  240. return True
  241. except:
  242. return False
  243. def check_int_between(val,imin,imax,desc):
  244. if not imin <= int(val) <= imax:
  245. die(1,f'{val}: invalid value for {desc} (must be between {imin} and {imax})')
  246. return int(val)
  247. def is_hex_str(s):
  248. return set(s) <= set(hexdigits)
  249. def is_hex_str_lc(s):
  250. return set(s) <= set(hexdigits_lc)
  251. def is_utf8(s):
  252. try: s.decode('utf8')
  253. except: return False
  254. else: return True
  255. def remove_whitespace(s,ws='\t\r\n '):
  256. return s.translate(dict((ord(e),None) for e in ws))
  257. def strip_comment(line):
  258. return re.sub('#.*','',line).rstrip()
  259. def strip_comments(lines):
  260. pat = re.compile('#.*')
  261. return [m for m in [pat.sub('',l).rstrip() for l in lines] if m != '']
  262. def compare_chksums(chk1,desc1,chk2,desc2,hdr='',die_on_fail=False,verbose=False):
  263. if not chk1 == chk2:
  264. fs = "{} ERROR: {} checksum ({}) doesn't match {} checksum ({})"
  265. m = fs.format((hdr+':\n ' if hdr else 'CHECKSUM'),desc2,chk2,desc1,chk1)
  266. if die_on_fail:
  267. die(3,m)
  268. else:
  269. vmsg(m,force=verbose)
  270. return False
  271. vmsg(f'{capfirst(desc1)} checksum OK ({chk1})')
  272. return True
  273. def compare_or_die(val1, desc1, val2, desc2, e='Error'):
  274. if val1 != val2:
  275. die(3,f"{e}: {desc2} ({val2}) doesn't match {desc1} ({val1})")
  276. dmsg(f'{capfirst(desc2)} OK ({val2})')
  277. return True
  278. def make_full_path(outdir,outfile):
  279. return os.path.normpath(os.path.join(outdir, os.path.basename(outfile)))
  280. class oneshot_warning:
  281. color = 'nocolor'
  282. def __init__(self,div=None,fmt_args=[],reverse=False):
  283. self.do(type(self),div,fmt_args,reverse)
  284. def do(self,wcls,div,fmt_args,reverse):
  285. def do_warning():
  286. import mmgen.color
  287. message = getattr(wcls,'message')
  288. color = getattr( mmgen.color, getattr(wcls,'color') )
  289. msg(color('WARNING: ' + message.format(*fmt_args)))
  290. if not hasattr(wcls,'data'):
  291. setattr(wcls,'data',[])
  292. data = getattr(wcls,'data')
  293. condition = (div in data) if reverse else (not div in data)
  294. if not div in data:
  295. data.append(div)
  296. if condition:
  297. do_warning()
  298. self.warning_shown = True
  299. else:
  300. self.warning_shown = False
  301. class oneshot_warning_group(oneshot_warning):
  302. def __init__(self,wcls,div=None,fmt_args=[],reverse=False):
  303. self.do(getattr(self,wcls),div,fmt_args,reverse)
  304. def stdout_or_pager(s):
  305. if opt.pager:
  306. from .ui import do_pager
  307. do_pager(s)
  308. else:
  309. Msg_r(s)
  310. def get_subclasses(cls,names=False):
  311. def gen(cls):
  312. for i in cls.__subclasses__():
  313. yield i
  314. for j in gen(i):
  315. yield j
  316. return tuple((c.__name__ for c in gen(cls)) if names else gen(cls))
  317. def async_run(coro):
  318. import asyncio
  319. return asyncio.run(coro)
  320. def wrap_ripemd160(called=[]):
  321. if not called:
  322. try:
  323. import hashlib
  324. hashlib.new('ripemd160')
  325. except ValueError:
  326. def hashlib_new_wrapper(name,*args,**kwargs):
  327. if name == 'ripemd160':
  328. return ripemd160(*args,**kwargs)
  329. else:
  330. return hashlib_new(name,*args,**kwargs)
  331. from .contrib.ripemd160 import ripemd160
  332. hashlib_new = hashlib.new
  333. hashlib.new = hashlib_new_wrapper
  334. called.append(True)
  335. def exit_if_mswin(feature):
  336. if g.platform == 'win':
  337. die(2, capfirst(feature) + ' not supported on the MSWin / MSYS2 platform' )