objtest.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2019 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. test/objtest.py: Test MMGen data objects
  20. """
  21. import sys,os
  22. pn = os.path.dirname(sys.argv[0])
  23. os.chdir(os.path.join(pn,os.pardir))
  24. sys.path.__setitem__(0,os.path.abspath(os.curdir))
  25. from binascii import hexlify
  26. # Import these _after_ local path's been added to sys.path
  27. from mmgen.common import *
  28. from mmgen.obj import *
  29. from mmgen.seed import *
  30. opts_data = lambda: {
  31. 'desc': 'Test MMGen data objects',
  32. 'sets': ( ('super_silent', True, 'silent', True), ),
  33. 'usage':'[options] [object]',
  34. 'options': """
  35. -h, --help Print this help message
  36. --, --longhelp Print help message for long options (common options)
  37. -q, --quiet Produce quieter output
  38. -s, --silent Silence output of tested objects
  39. -S, --super-silent Silence all output except for errors
  40. -v, --verbose Produce more verbose output
  41. """
  42. }
  43. cmd_args = opts.init(opts_data)
  44. def run_test(test,arg,input_data):
  45. arg_copy = arg
  46. kwargs = {'on_fail':'silent'} if opt.silent else {}
  47. ret_chk = arg
  48. if input_data == 'good' and type(arg) == tuple: arg,ret_chk = arg
  49. if type(arg) == dict: # pass one arg + kwargs to constructor
  50. arg_copy = arg.copy()
  51. if 'arg' in arg:
  52. args = [arg['arg']]
  53. ret_chk = args[0]
  54. del arg['arg']
  55. else:
  56. args = []
  57. ret_chk = list(arg.values())[0] # assume only one key present
  58. if 'ret' in arg:
  59. ret_chk = arg['ret']
  60. del arg['ret']
  61. del arg_copy['ret']
  62. kwargs.update(arg)
  63. else:
  64. args = [arg]
  65. try:
  66. if not opt.super_silent:
  67. msg_r((orange,green)[input_data=='good']('{:<22}'.format(repr(arg_copy)+':')))
  68. cls = globals()[test]
  69. ret = cls(*args,**kwargs)
  70. bad_ret = list() if issubclass(cls,list) else None
  71. if issubclass(type(ret_chk),str): ret_chk = ret_chk.encode()
  72. if issubclass(type(ret),str): ret = ret.encode()
  73. if (opt.silent and input_data=='bad' and ret!=bad_ret) or (not opt.silent and input_data=='bad'):
  74. raise UserWarning("Non-'None' return value {} with bad input data".format(repr(ret)))
  75. if opt.silent and input_data=='good' and ret==bad_ret:
  76. raise UserWarning("'None' returned with good input data")
  77. if input_data=='good' and ret != ret_chk and repr(ret) != repr(ret_chk):
  78. raise UserWarning("Return value ({!r}) doesn't match expected value ({!r})".format(ret,ret_chk))
  79. if not opt.super_silent:
  80. msg('==> {}'.format(ret))
  81. if opt.verbose and issubclass(cls,MMGenObject):
  82. ret.pmsg() if hasattr(ret,'pmsg') else pmsg(ret)
  83. except SystemExit as e:
  84. if input_data == 'good':
  85. raise ValueError('Error on good input data')
  86. if opt.verbose:
  87. msg('exitval: {}'.format(e.code))
  88. except UserWarning as e:
  89. msg('==> {!r}'.format(ret))
  90. die(2,red('{}'.format(e.args[0])))
  91. r32,r24,r16,r17,r18 = os.urandom(32),os.urandom(24),os.urandom(16),os.urandom(17),os.urandom(18)
  92. tw_pfx = g.proto.base_coin.lower()+':'
  93. utf8_text = '[α-$ample UTF-8 text-ω]' * 10 # 230 chars, unicode types L,N,P,S,Z
  94. utf8_text_combining = '[α-$ámple UTF-8 téxt-ω]' * 10 # L,N,P,S,Z,M
  95. utf8_text_control = '[α-$ample\nUTF-8\ntext-ω]' * 10 # L,N,P,S,Z,C
  96. from collections import OrderedDict
  97. tests = OrderedDict([
  98. ('AddrIdx', {
  99. 'bad': ('s',1.1,12345678,-1),
  100. 'good': (('7',7),)
  101. }),
  102. ('AddrIdxList', {
  103. 'bad': ('x','5,9,1-2-3','8,-11','66,3-2'),
  104. 'good': (
  105. ('3,2,2',[2,3]),
  106. ('101,1,3,5,2-7,99',[1,2,3,4,5,6,7,99,101]),
  107. ({'idx_list':AddrIdxList('1-5')},[1,2,3,4,5])
  108. )}),
  109. ('BTCAmt', {
  110. 'bad': ('-3.2','0.123456789',123,'123L','22000000',20999999.12345678),
  111. 'good': (('20999999.12345678',Decimal('20999999.12345678')),)
  112. }),
  113. ('LTCAmt', {
  114. 'bad': ('-3.2','0.123456789',123,'123L','88000000',80999999.12345678),
  115. 'good': (('80999999.12345678',Decimal('80999999.12345678')),)
  116. }),
  117. ('CoinAddr', {
  118. 'bad': (1,'x','я'),
  119. 'good': {
  120. 'btc': (('1MjjELEy6EJwk8fSNfpS8b5teFRo4X5fZr','32GiSWo9zJQgkCmjAaLRrbPwXhKry2jHhj'),
  121. ('n2FgXPKwuFkCXF946EnoxWJDWF2VwQ6q8J','2MspvWFjBbkv2wzQGqhxJUYPCk3Y2jMaxLN')),
  122. 'ltc': (('LXYx4j8PDGE8GEwDFnEQhcLyHFGsRxSJwt','MEnuCzUGHaQx9fK5WYvLwR1NK4SAo8HmSr'),
  123. ('n2D3joAy3yE5fqxUeCp38X6uPUcVn7EFw9','QN59YbnHsPQcbKWSq9PmTpjrhBnHGQqRmf'))
  124. }[g.coin.lower()][bool(g.testnet)]
  125. }),
  126. ('SeedID', {
  127. 'bad': (
  128. {'sid':'я'},
  129. {'sid':'F00F00'},
  130. {'sid':'xF00F00x'},
  131. {'sid':1},
  132. {'sid':'F00BAA123'},
  133. {'sid':'f00baa12'},
  134. 'я',r32,'abc'),
  135. 'good': (({'sid':'F00BAA12'},'F00BAA12'),(Seed(r16),Seed(r16).sid))
  136. }),
  137. ('MMGenID', {
  138. 'bad': ('x',1,'f00f00f','a:b','x:L:3','F00BAA12:0','F00BAA12:Z:99'),
  139. 'good': (('F00BAA12:99','F00BAA12:L:99'),'F00BAA12:L:99','F00BAA12:S:99')
  140. }),
  141. ('TwMMGenID', {
  142. 'bad': ('x','я','я:я',1,'f00f00f','a:b','x:L:3','F00BAA12:0','F00BAA12:Z:99',tw_pfx,tw_pfx+'я'),
  143. 'good': (('F00BAA12:99','F00BAA12:L:99'),'F00BAA12:L:99','F00BAA12:S:9999999',tw_pfx+'x')
  144. }),
  145. ('TwLabel', {
  146. 'bad': ('x x','x я','я:я',1,'f00f00f','a:b','x:L:3','F00BAA12:0 x',
  147. 'F00BAA12:Z:99',tw_pfx+' x',tw_pfx+'я x'),
  148. 'good': (
  149. ('F00BAA12:99 a comment','F00BAA12:L:99 a comment'),
  150. 'F00BAA12:L:99 comment (UTF-8) α',
  151. 'F00BAA12:S:9999999 comment',
  152. tw_pfx+'x comment')
  153. }),
  154. ('HexBytes', {
  155. 'bad': (1,[],'\0','\1','я','g','gg','FF','f00'),
  156. 'good': ('deadbeef','f00baa12')
  157. }),
  158. ('MMGenTxID', {
  159. 'bad': (1,[],'\0','\1','я','g','gg','FF','f00','F00F0012'),
  160. 'good': ('DEADBE','F00BAA')
  161. }),
  162. ('CoinTxID',{
  163. 'bad': (1,[],'\0','\1','я','g','gg','FF','f00','F00F0012',hexlify(r16),hexlify(r32)+b'ee'),
  164. 'good': (hexlify(r32),)
  165. }),
  166. ('WifKey', {
  167. 'bad': (1,[],'\0','\1','я','g','gg','FF','f00',hexlify(r16),'2MspvWFjBbkv2wzQGqhxJUYPCk3Y2jMaxLN'),
  168. 'good': {
  169. 'btc': (('5KXEpVzjWreTcQoG5hX357s1969MUKNLuSfcszF6yu84kpsNZKb',
  170. 'KwWr9rDh8KK5TtDa3HLChEvQXNYcUXpwhRFUPc5uSNnMtqNKLFhk'),
  171. ('93HsQEpH75ibaUJYi3QwwiQxnkW4dUuYFPXZxcbcKds7XrqHkY6',
  172. 'cMsqcmDYZP1LdKgqRh9L4ZRU9br28yvdmTPwW2YQwVSN9aQiMAoR')),
  173. 'ltc': (('6udBAGS6B9RfGyvEQDkVDsWy3Kqv9eTULqtEfVkJtTJyHdLvojw',
  174. 'T7kCSp5E71jzV2zEJW4q5qU1SMB5CSz8D9VByxMBkamv1uM3Jjca'),
  175. ('936Fd4qs3Zy2ZiYHH7vZ3UpT23KtCAiGiG2xBTkjHo7jE9aWA2f',
  176. 'cQY3EumdaSNuttvDSUuPdiMYLyw8aVmYfFqxo9kdPuWbJBN4Ny66'))
  177. }[g.coin.lower()][bool(g.testnet)]
  178. }),
  179. ('PubKey', {
  180. 'bad': ({'arg':1,'compressed':False},{'arg':'F00BAA12','compressed':False},),
  181. 'good': ({'arg':'deadbeef','compressed':True},) # TODO: add real pubkeys
  182. }),
  183. ('PrivKey', {
  184. 'bad': ({'wif':1},),
  185. 'good': ({
  186. 'btc': (({'wif':'5KXEpVzjWreTcQoG5hX357s1969MUKNLuSfcszF6yu84kpsNZKb',
  187. 'ret':'e0aef965b905a2fedf907151df8e0a6bac832aa697801c51f58bd2ecb4fd381c'},
  188. {'wif':'KwWr9rDh8KK5TtDa3HLChEvQXNYcUXpwhRFUPc5uSNnMtqNKLFhk',
  189. 'ret':'08d0ed83b64b68d56fa064be48e2385060ed205be2b1e63cd56d218038c3a05f'}),
  190. ({'wif':'93HsQEpH75ibaUJYi3QwwiQxnkW4dUuYFPXZxcbcKds7XrqHkY6',
  191. 'ret':'e0aef965b905a2fedf907151df8e0a6bac832aa697801c51f58bd2ecb4fd381c'},
  192. {'wif':'cMsqcmDYZP1LdKgqRh9L4ZRU9br28yvdmTPwW2YQwVSN9aQiMAoR',
  193. 'ret':'08d0ed83b64b68d56fa064be48e2385060ed205be2b1e63cd56d218038c3a05f'})),
  194. 'ltc': (({'wif':'6ufJhtQQiRYA3w2QvDuXNXuLgPFp15i3HR1Wp8An2mx1JnhhJAh',
  195. 'ret':'470a974ffca9fca1299b706b09142077bea3acbab6d6480b87dbba79d5fd279b'},
  196. {'wif':'T41Fm7J3mtZLKYPMCLVSFARz4QF8nvSDhLAfW97Ds56Zm9hRJgn8',
  197. 'ret':'1c6feab55a4c3b4ad1823d4ecacd1565c64228c01828cf44fb4db1e2d82c3d56'}),
  198. ({'wif':'92iqzh6NqiKawyB1ronw66YtEHrU4rxRJ5T4aHniZqvuSVZS21f',
  199. 'ret':'95b2aa7912550eacdd3844dcc14bee08ce7bc2434ad4858beb136021e945afeb'},
  200. {'wif':'cSaJAXBAm9ooHpVJgoxqjDG3AcareFy29Cz8mhnNTRijjv2HLgta',
  201. 'ret':'94fa8b90c11fea8fb907c9376b919534b0a75b9a9621edf71a78753544b4101c'})),
  202. }[g.coin.lower()][bool(g.testnet)],
  203. {'s':r32,'compressed':False,'pubkey_type':'std','ret':hexlify(r32)},
  204. {'s':r32,'compressed':True,'pubkey_type':'std','ret':hexlify(r32)}
  205. )
  206. }),
  207. ('AddrListID', { # a rather pointless test, but do it anyway
  208. 'bad': (
  209. {'sid':SeedID(sid='F00BAA12'),'mmtype':'Z','ret':'F00BAA12:Z'},
  210. ),
  211. 'good': (
  212. {'sid':SeedID(sid='F00BAA12'),'mmtype':MMGenAddrType('S'),'ret':'F00BAA12:S'},
  213. {'sid':SeedID(sid='F00BAA12'),'mmtype':MMGenAddrType('L'),'ret':'F00BAA12:L'},
  214. )
  215. }),
  216. ('MMGenWalletLabel', {
  217. 'bad': (utf8_text[:49],utf8_text_combining[:48],utf8_text_control[:48]),
  218. 'good': (utf8_text[:48],)
  219. }),
  220. ('TwComment', {
  221. 'bad': (utf8_text[:41],utf8_text_combining[:40],utf8_text_control[:40]),
  222. 'good': (utf8_text[:40],)
  223. }),
  224. ('MMGenTXLabel',{
  225. 'bad': (utf8_text[:73],utf8_text_combining[:72],utf8_text_control[:72]),
  226. 'good': (utf8_text[:72],)
  227. }),
  228. ('MMGenPWIDString', { # forbidden = list(u' :/\\')
  229. 'bad': ('foo/','foo:','foo:\\'),
  230. 'good': ('qwerty@яяя',)
  231. }),
  232. ('MMGenAddrType', {
  233. 'bad': ('U','z','xx',1,'dogecoin'),
  234. 'good': (
  235. {'s':'legacy','ret':'L'},
  236. {'s':'L','ret':'L'},
  237. {'s':'compressed','ret':'C'},
  238. {'s':'C','ret':'C'},
  239. {'s':'segwit','ret':'S'},
  240. {'s':'S','ret':'S'},
  241. {'s':'bech32','ret':'B'},
  242. {'s':'B','ret':'B'},
  243. )}),
  244. ('MMGenPasswordType', {
  245. 'bad': ('U','z','я',1,'passw0rd'),
  246. 'good': (
  247. {'s':'password','ret':'P'},
  248. {'s':'P','ret':'P'},
  249. )}),
  250. ])
  251. def do_loop():
  252. utests = cmd_args
  253. for test in tests:
  254. if utests and test not in utests: continue
  255. msg((blue,nocolor)[bool(opt.super_silent)]('Testing {}'.format(test)))
  256. for k in ('bad','good'):
  257. for arg in tests[test][k]:
  258. run_test(test,arg,input_data=k)
  259. do_loop()