objtest.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3. #
  4. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  5. # Copyright (C)2013-2017 Philemon <mmgen-py@yandex.com>
  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 = 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 (opt.silent and input_data=='bad' and ret!=bad_ret) or (not opt.silent and input_data=='bad'):
  73. raise UserWarning,"Non-'None' return value {} with bad input data".format(repr(ret))
  74. if opt.silent and input_data=='good' and ret==bad_ret:
  75. raise UserWarning,"'None' returned with good input data"
  76. if input_data=='good' and ret != ret_chk and repr(ret) != repr(ret_chk):
  77. raise UserWarning,"Return value ({!r}) doesn't match expected value ({!r})".format(ret,ret_chk)
  78. if not opt.super_silent:
  79. msg(u'==> {}'.format(ret))
  80. if opt.verbose and issubclass(cls,MMGenObject):
  81. ret.pmsg()
  82. except SystemExit as e:
  83. if input_data == 'good':
  84. raise ValueError,'Error on good input data'
  85. if opt.verbose:
  86. msg('exitval: {}'.format(e[0]))
  87. except UserWarning as e:
  88. msg('==> {!r}'.format(ret))
  89. die(2,red('{}'.format(e[0])))
  90. r32,r24,r16,r17,r18 = os.urandom(32),os.urandom(24),os.urandom(16),os.urandom(17),os.urandom(18)
  91. tw_pfx = g.proto.base_coin.lower()+':'
  92. from collections import OrderedDict
  93. tests = OrderedDict([
  94. ('AddrIdx', {
  95. 'bad': ('s',1.1,12345678,-1),
  96. 'good': (('7',7),)
  97. }),
  98. ('AddrIdxList', {
  99. 'bad': ('x','5,9,1-2-3','8,-11','66,3-2'),
  100. 'good': (
  101. ('3,2,2',[2,3]),
  102. ('101,1,3,5,2-7,99',[1,2,3,4,5,6,7,99,101]),
  103. ({'idx_list':AddrIdxList('1-5')},[1,2,3,4,5])
  104. )}),
  105. ('BTCAmt', {
  106. 'bad': ('-3.2','0.123456789',123L,'123L','22000000',20999999.12345678),
  107. 'good': (('20999999.12345678',Decimal('20999999.12345678')),)
  108. }),
  109. ('LTCAmt', {
  110. 'bad': ('-3.2','0.123456789',123L,'123L','88000000',80999999.12345678),
  111. 'good': (('80999999.12345678',Decimal('80999999.12345678')),)
  112. }),
  113. ('CoinAddr', {
  114. 'bad': (1,'x','я'),
  115. 'good': {
  116. 'btc': (('1MjjELEy6EJwk8fSNfpS8b5teFRo4X5fZr','32GiSWo9zJQgkCmjAaLRrbPwXhKry2jHhj'),
  117. ('n2FgXPKwuFkCXF946EnoxWJDWF2VwQ6q8J','2MspvWFjBbkv2wzQGqhxJUYPCk3Y2jMaxLN')),
  118. 'ltc': (('LXYx4j8PDGE8GEwDFnEQhcLyHFGsRxSJwt','MEnuCzUGHaQx9fK5WYvLwR1NK4SAo8HmSr'),
  119. ('n2D3joAy3yE5fqxUeCp38X6uPUcVn7EFw9','QN59YbnHsPQcbKWSq9PmTpjrhBnHGQqRmf'))
  120. }[g.coin.lower()][bool(g.testnet)]
  121. }),
  122. ('SeedID', {
  123. 'bad': (
  124. {'sid':'я'},
  125. {'sid':'F00F00'},
  126. {'sid':'xF00F00x'},
  127. {'sid':1},
  128. {'sid':'F00BAA123'},
  129. {'sid':'f00baa12'},
  130. 'я',r32,'abc'),
  131. 'good': (({'sid':'F00BAA12'},'F00BAA12'),(Seed(r16),Seed(r16).sid))
  132. }),
  133. ('MMGenID', {
  134. 'bad': ('x',1,'f00f00f','a:b','x:L:3','F00BAA12:0','F00BAA12:Z:99'),
  135. 'good': (('F00BAA12:99','F00BAA12:L:99'),'F00BAA12:L:99','F00BAA12:S:99')
  136. }),
  137. ('TwMMGenID', {
  138. 'bad': ('x','я','я:я',1,'f00f00f','a:b','x:L:3','F00BAA12:0','F00BAA12:Z:99',tw_pfx,tw_pfx+'я'),
  139. 'good': (('F00BAA12:99','F00BAA12:L:99'),'F00BAA12:L:99','F00BAA12:S:9999999',tw_pfx+'x')
  140. }),
  141. ('TwComment', {
  142. 'bad': ('я',"comment too long for tracking wallet",),
  143. 'good': ('OK comment',)
  144. }),
  145. ('TwLabel', {
  146. 'bad': ('x x','x я','я:я',1,'f00f00f','a:b','x:L:3','F00BAA12:0 x',
  147. 'F00BAA12:Z:99','F00BAA12:L:99 я',tw_pfx+' x',tw_pfx+'я x'),
  148. 'good': (
  149. ('F00BAA12:99 a comment','F00BAA12:L:99 a comment'),
  150. 'F00BAA12:L:99 comment',
  151. 'F00BAA12:S:9999999 comment',
  152. tw_pfx+'x comment')
  153. }),
  154. ('HexStr', {
  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)+'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,'ret':hexlify(r32)},
  204. {'s':r32,'compressed':True,'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': ('яqwerty','This text is too long to fit in an MMGen wallet label'),
  218. 'good': ('a good label',)
  219. }),
  220. ('TwComment', {
  221. 'bad': (u'яqwerty','This text is too long for a TW comment'),
  222. 'good': ('a good comment',)
  223. }),
  224. ('MMGenTXLabel',{
  225. 'bad': ('This text is too long for a transaction comment. '*2,),
  226. 'good': (u'UTF-8 is OK: я','a good comment',)
  227. }),
  228. ('MMGenPWIDString', { # forbidden = list(u' :/\\')
  229. 'bad': ('foo/','foo:','foo:\\'),
  230. 'good': (u'qwerty@яяя',)
  231. }),
  232. ('MMGenAddrType', {
  233. 'bad': ('U','z','xx',1,'dogecoin'),
  234. 'good': (
  235. {'s':'segwit','ret':'S'},
  236. {'s':'S','ret':'S'},
  237. {'s':'legacy','ret':'L'},
  238. {'s':'L','ret':'L'},
  239. {'s':'compressed','ret':'C'},
  240. {'s':'C','ret':'C'}
  241. )}),
  242. ('MMGenPasswordType', {
  243. 'bad': ('U','z','я',1,'passw0rd'),
  244. 'good': (
  245. {'s':'password','ret':'P'},
  246. {'s':'P','ret':'P'},
  247. )}),
  248. ])
  249. def do_loop():
  250. utests = cmd_args
  251. for test in tests:
  252. if utests and test not in utests: continue
  253. msg((blue,nocolor)[bool(opt.super_silent)]('Testing {}'.format(test)))
  254. for k in ('bad','good'):
  255. for arg in tests[test][k]:
  256. run_test(test,arg,input_data=k)
  257. do_loop()