unit_tests.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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/unit_tests.py: Unit tests for the MMGen suite
  20. """
  21. import sys,os,time
  22. from decimal import Decimal
  23. from pprint import pprint,pformat
  24. repo_root = os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]),os.pardir)))
  25. os.chdir(repo_root)
  26. sys.path[0] = repo_root
  27. os.environ['MMGEN_TEST_SUITE'] = '1'
  28. # Import these _after_ prepending repo_root to sys.path
  29. from mmgen.common import *
  30. opts_data = lambda: {
  31. 'desc': "Unit tests for the MMGen suite",
  32. 'usage':'[options] [tests]',
  33. 'options': """
  34. -h, --help Print this help message
  35. -l, --list List available tests
  36. -n, --names Print command names instead of descriptions
  37. -q, --quiet Produce quieter output
  38. -v, --verbose Produce more verbose output
  39. """,
  40. 'notes': """
  41. If no test is specified, all available tests are run
  42. """
  43. }
  44. sys.argv = [sys.argv[0]] + ['--skip-cfg-file'] + sys.argv[1:]
  45. cmd_args = opts.init(opts_data)
  46. class UnitTests(object):
  47. def _get_core_repo_root(self):
  48. self.core_repo_root = os.getenv('CORE_REPO_ROOT')
  49. if not self.core_repo_root:
  50. die(1,'The environmental variable CORE_REPO_ROOT must be set before running this test')
  51. def tx_deserialize(self,name):
  52. def test_tx(txhex,desc,n):
  53. def has_nonstandard_outputs(outputs):
  54. for o in outputs:
  55. t = o['scriptPubKey']['type']
  56. if t in ('nonstandard','pubkey','nulldata'):
  57. return True
  58. return False
  59. d = g.rpch.decoderawtransaction(txhex)
  60. if has_nonstandard_outputs(d['vout']): return False
  61. dt = DeserializedTX(txhex)
  62. if opt.verbose:
  63. Msg('\n====================================================')
  64. Msg_r('.' if opt.quiet else '{:>3}) {}\n'.format(n,desc))
  65. if opt.verbose:
  66. Pmsg(d)
  67. Msg('----------------------------------------------------')
  68. Pmsg(dt)
  69. # metadata
  70. assert dt['txid'] == d['txid'],'TXID does not match'
  71. assert dt['lock_time'] == d['locktime'],'Locktime does not match'
  72. assert dt['version'] == d['version'],'Version does not match'
  73. # inputs
  74. a,b = d['vin'],dt['txins']
  75. for i in range(len(a)):
  76. assert a[i]['txid'] == b[i]['txid'],'TxID of input {} does not match'.format(i)
  77. assert a[i]['vout'] == b[i]['vout'],'vout of input {} does not match'.format(i)
  78. assert a[i]['sequence'] == int(b[i]['nSeq'],16),(
  79. 'nSeq of input {} does not match'.format(i))
  80. if 'txinwitness' in a[i]:
  81. assert a[i]['txinwitness'] == b[i]['witness'],(
  82. 'witness of input {} does not match'.format(i))
  83. # outputs
  84. a,b = d['vout'],dt['txouts']
  85. for i in range(len(a)):
  86. assert a[i]['scriptPubKey']['addresses'][0] == b[i]['address'],(
  87. 'address of ouput {} does not match'.format(i))
  88. assert a[i]['value'] == b[i]['amount'],'value of ouput {} does not match'.format(i)
  89. assert a[i]['scriptPubKey']['hex'] == b[i]['scriptPubKey'],(
  90. 'scriptPubKey of ouput {} does not match'.format(i))
  91. return True
  92. def print_info(fn,extra_desc):
  93. if opt.names:
  94. Msg_r('{} {} ({}){}'.format(
  95. purple('Testing'),
  96. cyan(name),
  97. extra_desc,
  98. '' if opt.quiet else '\n'))
  99. else:
  100. Msg('Testing transactions from {!r}'.format(fn))
  101. def test_core_vectors():
  102. self._get_core_repo_root()
  103. fn = os.path.join(self.core_repo_root,'src/test/data/tx_valid.json')
  104. data = json.loads(open(fn).read())
  105. print_info(fn,'Core test vectors')
  106. n = 1
  107. for e in data:
  108. if type(e[0]) == list:
  109. test_tx(e[1],desc,n)
  110. n += 1
  111. else:
  112. desc = e[0]
  113. Msg('OK')
  114. def test_mmgen_txs():
  115. fns = ( ('btc',False,'test/ref/0B8D5A[15.31789,14,tl=1320969600].rawtx'),
  116. ('btc',True,'test/ref/0C7115[15.86255,14,tl=1320969600].testnet.rawtx'),
  117. ('bch',False,'test/ref/460D4D-BCH[10.19764,tl=1320969600].rawtx') )
  118. from mmgen.protocol import init_coin
  119. from mmgen.tx import MMGenTX
  120. from importlib import reload
  121. print_info('test/ref/*rawtx','MMGen reference transactions')
  122. for n,(coin,tn,fn) in enumerate(fns):
  123. init_coin(coin,tn)
  124. rpc_init(reinit=True)
  125. reload(sys.modules['mmgen.tx'])
  126. test_tx(MMGenTX(fn).hex,fn,n+1)
  127. init_coin('btc',False)
  128. rpc_init(reinit=True)
  129. reload(sys.modules['mmgen.tx'])
  130. Msg('OK')
  131. from mmgen.tx import DeserializedTX
  132. import json
  133. test_mmgen_txs()
  134. test_core_vectors()
  135. return True
  136. def exit_msg():
  137. t = int(time.time()) - start_time
  138. gmsg('All requested tests finished OK, elapsed time: {:02}:{:02}'.format(t//60,t%60))
  139. def run_unit_test(test):
  140. gmsg('Running unit test {}'.format(test))
  141. t = UnitTests()
  142. return getattr(t,test)(test)
  143. all_tests = filter(lambda s: s[0] != '_',dir(UnitTests))
  144. start_time = int(time.time())
  145. if opt.list:
  146. Die(0,' '.join(all_tests))
  147. try:
  148. for test in cmd_args:
  149. if test not in all_tests:
  150. die(1,"'{}': test not recognized".format(test))
  151. for test in (cmd_args or all_tests):
  152. if not run_unit_test(test):
  153. rdie(2,'Test failed')
  154. exit_msg()
  155. except KeyboardInterrupt:
  156. die(1,green('\nExiting at user request'))