util2.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, a command-line cryptocurrency wallet
  4. # Copyright (C)2013-2024 The MMGen Project <mmgen@tuta.io>
  5. # Licensed under the GNU General Public License, Version 3:
  6. # https://www.gnu.org/licenses
  7. # Public project repositories:
  8. # https://github.com/mmgen/mmgen-wallet
  9. # https://gitlab.com/mmgen/mmgen-wallet
  10. """
  11. util2: Less frequently-used variables, classes and utility functions for the MMGen suite
  12. """
  13. import sys,re,time
  14. from .util import msg,suf,hexdigits,die
  15. def die_wait(delay,ev=0,s=''):
  16. assert isinstance(delay,int)
  17. assert isinstance(ev,int)
  18. if s:
  19. msg(s)
  20. time.sleep(delay)
  21. sys.exit(ev)
  22. def die_pause(ev=0,s=''):
  23. assert isinstance(ev,int)
  24. if s:
  25. msg(s)
  26. input('Press ENTER to exit')
  27. sys.exit(ev)
  28. def removeprefix(s,pfx): # workaround for pre-Python 3.9
  29. return s[len(pfx):] if s.startswith(pfx) else s
  30. def removesuffix(s,sfx): # workaround for pre-Python 3.9
  31. return s[:-len(sfx)] if s.endswith(sfx) else s
  32. # monkey-patch function for monero-python: permits its use with pycryptodome (e.g. MSYS2)
  33. # instead of the expected pycryptodomex
  34. def load_cryptodomex():
  35. try:
  36. import Cryptodome # cryptodomex
  37. except ImportError:
  38. try:
  39. import Crypto # cryptodome
  40. except ImportError:
  41. die(2,'Unable to import either the ‘pycryptodomex’ or ‘pycryptodome’ package')
  42. else:
  43. sys.modules['Cryptodome'] = Crypto
  44. # called with no arguments by pyethereum.utils:
  45. def get_keccak(cfg=None,cached_ret=[]):
  46. if not cached_ret:
  47. if cfg and cfg.use_internal_keccak_module:
  48. cfg._util.qmsg('Using internal keccak module by user request')
  49. from .contrib.keccak import keccak_256
  50. else:
  51. try:
  52. from Cryptodome.Hash import keccak
  53. except ImportError as e:
  54. try:
  55. from Crypto.Hash import keccak
  56. except ImportError as e2:
  57. msg(f'{e2} and {e}')
  58. die('MMGenImportError',
  59. 'Please install the ‘pycryptodome’ or ‘pycryptodomex’ package on your system')
  60. def keccak_256(data):
  61. return keccak.new(data=data,digest_bytes=32)
  62. cached_ret.append(keccak_256)
  63. return cached_ret[0]
  64. # From 'man dd':
  65. # c=1, w=2, b=512, kB=1000, K=1024, MB=1000*1000, M=1024*1024,
  66. # GB=1000*1000*1000, G=1024*1024*1024, and so on for T, P, E, Z, Y.
  67. bytespec_map = (
  68. ('c', 1),
  69. ('w', 2),
  70. ('b', 512),
  71. ('kB', 1000),
  72. ('K', 1024),
  73. ('MB', 1000000),
  74. ('M', 1048576),
  75. ('GB', 1000000000),
  76. ('G', 1073741824),
  77. ('TB', 1000000000000),
  78. ('T', 1099511627776),
  79. ('PB', 1000000000000000),
  80. ('P', 1125899906842624),
  81. ('EB', 1000000000000000000),
  82. ('E', 1152921504606846976),
  83. )
  84. def int2bytespec(n,spec,fmt,print_sym=True,strip=False,add_space=False):
  85. def spec2int(spec):
  86. for k,v in bytespec_map:
  87. if k == spec:
  88. return v
  89. else:
  90. die(1,f'{spec!r}: unrecognized bytespec')
  91. ret = f'{n/spec2int(spec):{fmt}f}'
  92. if strip:
  93. ret = ret.rstrip('0')
  94. return (
  95. ret
  96. + ('0' if ret.endswith('.') else '')
  97. + ((' ' if add_space else '') + spec if print_sym else '') )
  98. else:
  99. return (
  100. ret
  101. + ((' ' if add_space else '') + spec if print_sym else '') )
  102. def parse_bytespec(nbytes):
  103. m = re.match(r'([0123456789.]+)(.*)',nbytes)
  104. if m:
  105. if m.group(2):
  106. for k,v in bytespec_map:
  107. if k == m.group(2):
  108. from decimal import Decimal
  109. return int(Decimal(m.group(1)) * v)
  110. else:
  111. msg("Valid byte specifiers: '{}'".format("' '".join([i[0] for i in bytespec_map])))
  112. elif '.' in nbytes:
  113. raise ValueError('fractional bytes not allowed')
  114. else:
  115. return int(nbytes)
  116. die(1,f'{nbytes!r}: invalid byte specifier')
  117. def format_elapsed_days_hr(t,now=None,cached={}):
  118. e = int((now or time.time()) - t)
  119. if not e in cached:
  120. days = abs(e) // 86400
  121. cached[e] = f'{days} day{suf(days)} ' + ('ago' if e > 0 else 'in the future')
  122. return cached[e]
  123. def format_elapsed_hr(t,now=None,cached={}):
  124. e = int((now or time.time()) - t)
  125. if not e in cached:
  126. abs_e = abs(e)
  127. cached[e] = ' '.join(
  128. f'{n} {desc}{suf(n)}' for desc,n in (
  129. ('day', abs_e // 86400),
  130. ('hour', abs_e // 3600 % 24),
  131. ('minute', abs_e // 60 % 60),
  132. ) if n
  133. ) + (' ago' if e > 0 else ' in the future') if abs_e // 60 else 'just now'
  134. return cached[e]
  135. def pretty_format(s,width=80,pfx=''):
  136. out = []
  137. while s:
  138. if len(s) <= width:
  139. out.append(s)
  140. break
  141. i = s[:width].rfind(' ')
  142. out.append(s[:i])
  143. s = s[i+1:]
  144. return pfx + ('\n'+pfx).join(out)
  145. def block_format(data,gw=2,cols=8,line_nums=None,data_is_hex=False):
  146. assert line_nums in (None,'hex','dec'),"'line_nums' must be one of None, 'hex' or 'dec'"
  147. ln_fs = '{:06x}: ' if line_nums == 'hex' else '{:06}: '
  148. bytes_per_chunk = gw
  149. if data_is_hex:
  150. gw *= 2
  151. nchunks = len(data)//gw + bool(len(data)%gw)
  152. return ''.join(
  153. ('' if (line_nums is None or i % cols) else ln_fs.format(i*bytes_per_chunk))
  154. + data[i*gw:i*gw+gw]
  155. + (' ' if (not cols or (i+1) % cols) else '\n')
  156. for i in range(nchunks)
  157. ).rstrip() + '\n'
  158. def pretty_hexdump(data,gw=2,cols=8,line_nums=None):
  159. return block_format(data.hex(),gw,cols,line_nums,data_is_hex=True)
  160. def decode_pretty_hexdump(data):
  161. pat = re.compile(fr'^[{hexdigits}]+:\s+')
  162. lines = [pat.sub('',line) for line in data.splitlines()]
  163. try:
  164. return bytes.fromhex(''.join((''.join(lines).split())))
  165. except:
  166. msg('Data not in hexdump format')
  167. return False