objtest.py 11 KB

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