objtest.py 10 KB

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