objtest.py 9.8 KB

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