common.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2020 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. common.py: Shared routines and data for the MMGen test suites
  20. """
  21. class TestSuiteException(Exception): pass
  22. class TestSuiteFatalException(Exception): pass
  23. import os
  24. from mmgen.common import *
  25. from mmgen.devtools import *
  26. ascii_uc = ''.join(map(chr,list(range(65,91)))) # 26 chars
  27. ascii_lc = ''.join(map(chr,list(range(97,123)))) # 26 chars
  28. lat_accent = ''.join(map(chr,list(range(192,383)))) # 191 chars, L,S
  29. ru_uc = ''.join(map(chr,list(range(1040,1072)))) # 32 chars
  30. gr_uc = ''.join(map(chr,list(range(913,930)) + list(range(931,940)))) # 26 chars (930 is ctrl char)
  31. gr_uc_w_ctrl = ''.join(map(chr,list(range(913,940)))) # 27 chars, L,C
  32. lat_cyr_gr = lat_accent[:130:5] + ru_uc + gr_uc # 84 chars
  33. ascii_cyr_gr = ascii_uc + ru_uc + gr_uc # 84 chars
  34. utf8_text = '[α-$ample UTF-8 text-ω]' * 10 # 230 chars, L,N,P,S,Z
  35. utf8_combining = '[α-$ámple UTF-8 téxt-ω]' * 10 # L,N,P,S,Z,M
  36. utf8_ctrl = '[α-$ample\nUTF-8\ntext-ω]' * 10 # L,N,P,S,Z,C
  37. text_jp = '必要なのは、信用ではなく暗号化された証明に基づく電子取引システムであり、これにより希望する二者が信用できる第三者機関を介さずに直接取引できるよう' # 72 chars ('W'ide)
  38. text_zh = '所以,我們非常需要這樣一種電子支付系統,它基於密碼學原理而不基於信用,使得任何達成一致的雙方,能夠直接進行支付,從而不需要協力廠商仲介的參與。。' # 72 chars ('F'ull + 'W'ide)
  39. sample_text = 'The Times 03/Jan/2009 Chancellor on brink of second bailout for banks'
  40. sample_mn = {
  41. 'mmgen': { # 'able': 0, 'youth': 1625, 'after' == 'afternoon'[:5]
  42. 'mn': 'able cast forgive master funny gaze after afternoon million paint moral youth',
  43. 'hex': '0005685ab4e94cbe3b228cf92112bc5f',
  44. },
  45. 'bip39': { # len('sun') < uniq_ss_len
  46. 'mn': 'vessel ladder alter error federal sibling chat ability sun glass valve picture',
  47. 'hex': 'f30f8c1da665478f49b001d94c5fc452',
  48. },
  49. 'xmrseed': {
  50. 'mn': 'viewpoint donuts ardent template unveil agile meant unafraid urgent athlete rustled mime azure jaded hawk baby jagged haystack baby jagged haystack ramped oncoming point template',
  51. 'hex': 'e8164dda6d42bd1e261a3406b2038dcbddadbeefdeadbeefdeadbeefdeadbe0f',
  52. },
  53. }
  54. ref_kafile_pass = 'kafile password'
  55. ref_kafile_hash_preset = '1'
  56. def getrandnum(n): return int(os.urandom(n).hex(),16)
  57. def getrandhex(n): return os.urandom(n).hex()
  58. def getrandnum_range(nbytes,rn_max):
  59. while True:
  60. rn = int(os.urandom(nbytes).hex(),16)
  61. if rn < rn_max: return rn
  62. def getrandstr(num_chars,no_space=False):
  63. n,m = 95,32
  64. if no_space: n,m = 94,33
  65. return ''.join([chr(i%n+m) for i in list(os.urandom(num_chars))])
  66. def get_data_dir():
  67. return os.path.join('test','data_dir' + ('','-α')[bool(os.getenv('MMGEN_DEBUG_UTF8'))])
  68. # Windows uses non-UTF8 encodings in filesystem, so use raw bytes here
  69. def cleandir(d,do_msg=False):
  70. d_enc = d.encode()
  71. try: files = os.listdir(d_enc)
  72. except: return
  73. from shutil import rmtree
  74. if do_msg: gmsg("Cleaning directory '{}'".format(d))
  75. for f in files:
  76. try:
  77. os.unlink(os.path.join(d_enc,f))
  78. except:
  79. rmtree(os.path.join(d_enc,f),ignore_errors=True)
  80. def mk_tmpdir(d):
  81. try: os.mkdir(d,0o755)
  82. except OSError as e:
  83. if e.errno != 17: raise
  84. else:
  85. vmsg("Created directory '{}'".format(d))
  86. def get_tmpfile(cfg,fn):
  87. return os.path.join(cfg['tmpdir'],fn)
  88. def write_to_file(fn,data,binary=False):
  89. write_data_to_file( fn,
  90. data,
  91. quiet = True,
  92. binary = binary,
  93. ignore_opt_outdir = True )
  94. def write_to_tmpfile(cfg,fn,data,binary=False):
  95. write_to_file( os.path.join(cfg['tmpdir'],fn), data=data, binary=binary )
  96. def read_from_file(fn,binary=False):
  97. from mmgen.util import get_data_from_file
  98. return get_data_from_file(fn,quiet=True,binary=binary)
  99. def read_from_tmpfile(cfg,fn,binary=False):
  100. return read_from_file(os.path.join(cfg['tmpdir'],fn),binary=binary)
  101. def joinpath(*args,**kwargs):
  102. return os.path.join(*args,**kwargs)
  103. def ok():
  104. if opt.profile: return
  105. if opt.verbose or opt.exact_output:
  106. gmsg('OK')
  107. else: msg(' OK')
  108. def cmp_or_die(s,t,desc=None):
  109. if s != t:
  110. m = 'ERROR: recoded data:\n{!r}\ndiffers from original data:\n{!r}'
  111. if desc: m = 'For {}:\n{}'.format(desc,m)
  112. raise TestSuiteFatalException(m.format(t,s))
  113. def init_coverage():
  114. coverdir = os.path.join('test','trace')
  115. acc_file = os.path.join('test','trace.acc')
  116. try: os.mkdir(coverdir,0o755)
  117. except: pass
  118. return coverdir,acc_file
  119. devnull_fh = open(('/dev/null','null.out')[g.platform == 'win'],'w')
  120. def silence():
  121. if not (opt.verbose or (hasattr(opt,'exact_output') and opt.exact_output)):
  122. g.stdout = g.stderr = devnull_fh
  123. def end_silence():
  124. if not (opt.verbose or (hasattr(opt,'exact_output') and opt.exact_output)):
  125. g.stdout = sys.stdout
  126. g.stderr = sys.stderr
  127. def omsg(s):
  128. sys.stderr.write(s + '\n')
  129. def omsg_r(s):
  130. sys.stderr.write(s)
  131. sys.stderr.flush()
  132. def imsg(s):
  133. if opt.verbose or (hasattr(opt,'exact_output') and opt.exact_output):
  134. omsg(s)
  135. def imsg_r(s):
  136. if opt.verbose or (hasattr(opt,'exact_output') and opt.exact_output):
  137. omsg_r(s)
  138. def iqmsg(s):
  139. if not opt.quiet: omsg(s)
  140. def iqmsg_r(s):
  141. if not opt.quiet: omsg_r(s)
  142. def start_test_daemons(*network_ids):
  143. if not opt.no_daemon_autostart:
  144. return test_daemons_ops(*network_ids,op='start')
  145. def stop_test_daemons(*network_ids):
  146. if not opt.no_daemon_stop:
  147. return test_daemons_ops(*network_ids,op='stop')
  148. def restart_test_daemons(*network_ids):
  149. stop_test_daemons(*network_ids)
  150. return start_test_daemons(*network_ids)
  151. def test_daemons_ops(*network_ids,op):
  152. if not opt.no_daemon_autostart:
  153. from mmgen.daemon import CoinDaemon
  154. silent = not opt.verbose and not getattr(opt,'exact_output',False)
  155. for network_id in network_ids:
  156. if network_id.lower() not in CoinDaemon.network_ids: # silently ignore invalid IDs
  157. continue
  158. CoinDaemon(network_id,test_suite=True).cmd(op,silent=silent)