Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

getblocktemplate_proposals.py 6.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. #!/usr/bin/env python2
  2. # Copyright (c) 2014 The Bitcoin Core developers
  3. # Distributed under the MIT software license, see the accompanying
  4. # file COPYING or http://www.opensource.org/licenses/mit-license.php.
  5. from test_framework import BitcoinTestFramework
  6. from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
  7. from util import *
  8. from binascii import a2b_hex, b2a_hex
  9. from hashlib import sha256
  10. from struct import pack
  11. def check_array_result(object_array, to_match, expected):
  12. """
  13. Pass in array of JSON objects, a dictionary with key/value pairs
  14. to match against, and another dictionary with expected key/value
  15. pairs.
  16. """
  17. num_matched = 0
  18. for item in object_array:
  19. all_match = True
  20. for key,value in to_match.items():
  21. if item[key] != value:
  22. all_match = False
  23. if not all_match:
  24. continue
  25. for key,value in expected.items():
  26. if item[key] != value:
  27. raise AssertionError("%s : expected %s=%s"%(str(item), str(key), str(value)))
  28. num_matched = num_matched+1
  29. if num_matched == 0:
  30. raise AssertionError("No objects matched %s"%(str(to_match)))
  31. def b2x(b):
  32. return b2a_hex(b).decode('ascii')
  33. # NOTE: This does not work for signed numbers (set the high bit) or zero (use b'\0')
  34. def encodeUNum(n):
  35. s = bytearray(b'\1')
  36. while n > 127:
  37. s[0] += 1
  38. s.append(n % 256)
  39. n //= 256
  40. s.append(n)
  41. return bytes(s)
  42. def varlenEncode(n):
  43. if n < 0xfd:
  44. return pack('<B', n)
  45. if n <= 0xffff:
  46. return b'\xfd' + pack('<H', n)
  47. if n <= 0xffffffff:
  48. return b'\xfe' + pack('<L', n)
  49. return b'\xff' + pack('<Q', n)
  50. def dblsha(b):
  51. return sha256(sha256(b).digest()).digest()
  52. def genmrklroot(leaflist):
  53. cur = leaflist
  54. while len(cur) > 1:
  55. n = []
  56. if len(cur) & 1:
  57. cur.append(cur[-1])
  58. for i in range(0, len(cur), 2):
  59. n.append(dblsha(cur[i] + cur[i+1]))
  60. cur = n
  61. return cur[0]
  62. def template_to_bytes(tmpl, txlist):
  63. blkver = pack('<L', tmpl['version'])
  64. mrklroot = genmrklroot(list(dblsha(a) for a in txlist))
  65. timestamp = pack('<L', tmpl['curtime'])
  66. nonce = b'\0\0\0\0'
  67. blk = blkver + a2b_hex(tmpl['previousblockhash'])[::-1] + mrklroot + timestamp + a2b_hex(tmpl['bits'])[::-1] + nonce
  68. blk += varlenEncode(len(txlist))
  69. for tx in txlist:
  70. blk += tx
  71. return blk
  72. def template_to_hex(tmpl, txlist):
  73. return b2x(template_to_bytes(tmpl, txlist))
  74. def assert_template(node, tmpl, txlist, expect):
  75. rsp = node.getblocktemplate({'data':template_to_hex(tmpl, txlist),'mode':'proposal'})
  76. if rsp != expect:
  77. raise AssertionError('unexpected: %s' % (rsp,))
  78. class GetBlockTemplateProposalTest(BitcoinTestFramework):
  79. '''
  80. Test block proposals with getblocktemplate.
  81. '''
  82. def run_test(self):
  83. node = self.nodes[0]
  84. tmpl = node.getblocktemplate()
  85. if 'coinbasetxn' not in tmpl:
  86. rawcoinbase = encodeUNum(tmpl['height'])
  87. rawcoinbase += b'\x01-'
  88. hexcoinbase = b2x(rawcoinbase)
  89. hexoutval = b2x(pack('<Q', tmpl['coinbasevalue']))
  90. tmpl['coinbasetxn'] = {'data': '01000000' + '01' + '0000000000000000000000000000000000000000000000000000000000000000ffffffff' + ('%02x' % (len(rawcoinbase),)) + hexcoinbase + 'fffffffe' + '01' + hexoutval + '00' + '00000000'}
  91. txlist = list(bytearray(a2b_hex(a['data'])) for a in (tmpl['coinbasetxn'],) + tuple(tmpl['transactions']))
  92. # Test 0: Capability advertised
  93. assert('proposal' in tmpl['capabilities'])
  94. # NOTE: This test currently FAILS (regtest mode doesn't enforce block height in coinbase)
  95. ## Test 1: Bad height in coinbase
  96. #txlist[0][4+1+36+1+1] += 1
  97. #assert_template(node, tmpl, txlist, 'FIXME')
  98. #txlist[0][4+1+36+1+1] -= 1
  99. # Test 2: Bad input hash for gen tx
  100. txlist[0][4+1] += 1
  101. assert_template(node, tmpl, txlist, 'bad-cb-missing')
  102. txlist[0][4+1] -= 1
  103. # Test 3: Truncated final tx
  104. lastbyte = txlist[-1].pop()
  105. try:
  106. assert_template(node, tmpl, txlist, 'n/a')
  107. except JSONRPCException:
  108. pass # Expected
  109. txlist[-1].append(lastbyte)
  110. # Test 4: Add an invalid tx to the end (duplicate of gen tx)
  111. txlist.append(txlist[0])
  112. assert_template(node, tmpl, txlist, 'bad-txns-duplicate')
  113. txlist.pop()
  114. # Test 5: Add an invalid tx to the end (non-duplicate)
  115. txlist.append(bytearray(txlist[0]))
  116. txlist[-1][4+1] = b'\xff'
  117. assert_template(node, tmpl, txlist, 'bad-txns-inputs-missingorspent')
  118. txlist.pop()
  119. # Test 6: Future tx lock time
  120. txlist[0][-4:] = b'\xff\xff\xff\xff'
  121. assert_template(node, tmpl, txlist, 'bad-txns-nonfinal')
  122. txlist[0][-4:] = b'\0\0\0\0'
  123. # Test 7: Bad tx count
  124. txlist.append(b'')
  125. try:
  126. assert_template(node, tmpl, txlist, 'n/a')
  127. except JSONRPCException:
  128. pass # Expected
  129. txlist.pop()
  130. # Test 8: Bad bits
  131. realbits = tmpl['bits']
  132. tmpl['bits'] = '1c0000ff' # impossible in the real world
  133. assert_template(node, tmpl, txlist, 'bad-diffbits')
  134. tmpl['bits'] = realbits
  135. # Test 9: Bad merkle root
  136. rawtmpl = template_to_bytes(tmpl, txlist)
  137. rawtmpl[4+32] = (rawtmpl[4+32] + 1) % 0x100
  138. rsp = node.getblocktemplate({'data':b2x(rawtmpl),'mode':'proposal'})
  139. if rsp != 'bad-txnmrklroot':
  140. raise AssertionError('unexpected: %s' % (rsp,))
  141. # Test 10: Bad timestamps
  142. realtime = tmpl['curtime']
  143. tmpl['curtime'] = 0x7fffffff
  144. assert_template(node, tmpl, txlist, 'time-too-new')
  145. tmpl['curtime'] = 0
  146. assert_template(node, tmpl, txlist, 'time-too-old')
  147. tmpl['curtime'] = realtime
  148. # Test 11: Valid block
  149. assert_template(node, tmpl, txlist, None)
  150. # Test 12: Orphan block
  151. tmpl['previousblockhash'] = 'ff00' * 16
  152. assert_template(node, tmpl, txlist, 'inconclusive-not-best-prevblk')
  153. if __name__ == '__main__':
  154. GetBlockTemplateProposalTest().main()