objtest.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. from collections import OrderedDict
  92. tests = OrderedDict([
  93. ('AddrIdx', {
  94. 'bad': ('s',1.1,12345678,-1),
  95. 'good': (('7',7),)
  96. }),
  97. ('AddrIdxList', {
  98. 'bad': ('x','5,9,1-2-3','8,-11','66,3-2'),
  99. 'good': (
  100. ('3,2,2',[2,3]),
  101. ('101,1,3,5,2-7,99',[1,2,3,4,5,6,7,99,101]),
  102. ({'idx_list':AddrIdxList('1-5')},[1,2,3,4,5])
  103. )}),
  104. ('BTCAmt', {
  105. 'bad': ('-3.2','0.123456789',123L,'123L',22000000,20999999.12345678),
  106. 'good': (('20999999.12345678',Decimal('20999999.12345678')),)
  107. }),
  108. ('BTCAddr', {
  109. 'bad': (1,'x','я'),
  110. 'good': (
  111. '1MjjELEy6EJwk8fSNfpS8b5teFRo4X5fZr',
  112. '32GiSWo9zJQgkCmjAaLRrbPwXhKry2jHhj',
  113. 'n2FgXPKwuFkCXF946EnoxWJDWF2VwQ6q8J',
  114. '2MspvWFjBbkv2wzQGqhxJUYPCk3Y2jMaxLN'
  115. )}),
  116. ('SeedID', {
  117. 'bad': (
  118. {'sid':'я'},
  119. {'sid':'F00F00'},
  120. {'sid':'xF00F00x'},
  121. {'sid':1},
  122. {'sid':'F00BAA123'},
  123. {'sid':'f00baa12'},
  124. 'я',r32,'abc'),
  125. 'good': (({'sid':'F00BAA12'},'F00BAA12'),(Seed(r16),Seed(r16).sid))
  126. }),
  127. ('MMGenID', {
  128. 'bad': ('x',1,'f00f00f','a:b','x:L:3','F00BAA12:0','F00BAA12:Z:99'),
  129. 'good': (('F00BAA12:99','F00BAA12:L:99'),'F00BAA12:L:99','F00BAA12:S:99')
  130. }),
  131. ('TwMMGenID', {
  132. 'bad': ('x','я','я:я',1,'f00f00f','a:b','x:L:3','F00BAA12:0','F00BAA12:Z:99','btc:','btc:я'),
  133. 'good': (('F00BAA12:99','F00BAA12:L:99'),'F00BAA12:L:99','F00BAA12:S:9999999','btc:x')
  134. }),
  135. ('TwComment', {
  136. 'bad': ('я',"comment too long for tracking wallet",),
  137. 'good': ('OK comment',)
  138. }),
  139. ('TwLabel', {
  140. 'bad': ('x x','x я','я:я',1,'f00f00f','a:b','x:L:3','F00BAA12:0 x',
  141. 'F00BAA12:Z:99','F00BAA12:L:99 я','btc: x','btc:я x'),
  142. 'good': (
  143. ('F00BAA12:99 a comment','F00BAA12:L:99 a comment'),
  144. 'F00BAA12:L:99 comment',
  145. 'F00BAA12:S:9999999 comment',
  146. 'btc:x comment')
  147. }),
  148. ('HexStr', {
  149. 'bad': (1,[],'\0','\1','я','g','gg','FF','f00'),
  150. 'good': ('deadbeef','f00baa12')
  151. }),
  152. ('MMGenTxID', {
  153. 'bad': (1,[],'\0','\1','я','g','gg','FF','f00','F00F0012'),
  154. 'good': ('DEADBE','F00BAA')
  155. }),
  156. ('BitcoinTxID',{
  157. 'bad': (1,[],'\0','\1','я','g','gg','FF','f00','F00F0012',hexlify(r16),hexlify(r32)+'ee'),
  158. 'good': (hexlify(r32),)
  159. }),
  160. ('WifKey', {
  161. 'bad': (1,[],'\0','\1','я','g','gg','FF','f00',hexlify(r16),'2MspvWFjBbkv2wzQGqhxJUYPCk3Y2jMaxLN'),
  162. 'good': (
  163. '5KXEpVzjWreTcQoG5hX357s1969MUKNLuSfcszF6yu84kpsNZKb',
  164. 'KwWr9rDh8KK5TtDa3HLChEvQXNYcUXpwhRFUPc5uSNnMtqNKLFhk',
  165. {'arg':'93HsQEpH75ibaUJYi3QwwiQxnkW4dUuYFPXZxcbcKds7XrqHkY6','testnet':True},
  166. {'arg':'cMsqcmDYZP1LdKgqRh9L4ZRU9br28yvdmTPwW2YQwVSN9aQiMAoR','testnet':True}
  167. )
  168. }),
  169. ('PubKey', {
  170. 'bad': ({'arg':1,'compressed':False},{'arg':'F00BAA12','compressed':False},),
  171. 'good': ({'arg':'deadbeef','compressed':True},) # TODO: add real pubkeys
  172. }),
  173. ('PrivKey', {
  174. 'bad': ({'wif':1},),
  175. 'good': (
  176. {'wif':'5KXEpVzjWreTcQoG5hX357s1969MUKNLuSfcszF6yu84kpsNZKb',
  177. 'ret':'e0aef965b905a2fedf907151df8e0a6bac832aa697801c51f58bd2ecb4fd381c'},
  178. {'wif':'KwWr9rDh8KK5TtDa3HLChEvQXNYcUXpwhRFUPc5uSNnMtqNKLFhk',
  179. 'ret':'08d0ed83b64b68d56fa064be48e2385060ed205be2b1e63cd56d218038c3a05f'},
  180. {'wif':'93HsQEpH75ibaUJYi3QwwiQxnkW4dUuYFPXZxcbcKds7XrqHkY6','testnet':True,
  181. 'ret':'e0aef965b905a2fedf907151df8e0a6bac832aa697801c51f58bd2ecb4fd381c'},
  182. {'wif':'cMsqcmDYZP1LdKgqRh9L4ZRU9br28yvdmTPwW2YQwVSN9aQiMAoR','testnet':True,
  183. 'ret':'08d0ed83b64b68d56fa064be48e2385060ed205be2b1e63cd56d218038c3a05f'},
  184. {'s':r32,'compressed':False,'ret':hexlify(r32)},
  185. {'s':r32,'compressed':True,'ret':hexlify(r32)}
  186. )
  187. }),
  188. ('AddrListID', { # a rather pointless test, but do it anyway
  189. 'bad': (
  190. {'sid':SeedID(sid='F00BAA12'),'mmtype':'Z','ret':'F00BAA12:Z'},
  191. ),
  192. 'good': (
  193. {'sid':SeedID(sid='F00BAA12'),'mmtype':MMGenAddrType('S'),'ret':'F00BAA12:S'},
  194. {'sid':SeedID(sid='F00BAA12'),'mmtype':MMGenAddrType('L'),'ret':'F00BAA12:L'},
  195. )
  196. }),
  197. ('MMGenWalletLabel', {
  198. 'bad': ('яqwerty','This text is too long to fit in an MMGen wallet label'),
  199. 'good': ('a good label',)
  200. }),
  201. ('TwComment', {
  202. 'bad': (u'яqwerty','This text is too long for a TW comment'),
  203. 'good': ('a good comment',)
  204. }),
  205. ('MMGenTXLabel',{
  206. 'bad': ('This text is too long for a transaction comment. '*2,),
  207. 'good': (u'UTF-8 is OK: я','a good comment',)
  208. }),
  209. ('MMGenPWIDString', { # forbidden = list(u' :/\\')
  210. 'bad': ('foo/','foo:','foo:\\'),
  211. 'good': (u'qwerty@яяя',)
  212. }),
  213. ('MMGenAddrType', {
  214. 'bad': ('U','z','xx',1,'dogecoin'),
  215. 'good': (
  216. {'s':'segwit','ret':'S'},
  217. {'s':'S','ret':'S'},
  218. {'s':'legacy','ret':'L'},
  219. {'s':'L','ret':'L'},
  220. {'s':'compressed','ret':'C'},
  221. {'s':'C','ret':'C'}
  222. )}),
  223. ('MMGenPasswordType', {
  224. 'bad': ('U','z','я',1,'passw0rd'),
  225. 'good': (
  226. {'s':'password','ret':'P'},
  227. {'s':'P','ret':'P'},
  228. )}),
  229. ])
  230. def do_loop():
  231. utests = cmd_args
  232. for test in tests:
  233. if utests and test not in utests: continue
  234. msg((blue,nocolor)[bool(opt.super_silent)]('Testing {}'.format(test)))
  235. for k in ('bad','good'):
  236. for arg in tests[test][k]:
  237. run_test(test,arg,input_data=k)
  238. do_loop()