Skip to content

Commit 2012d4d

Browse files
committed
Add CScriptNum decode python implementation in functional suite
1 parent a4eaaa6 commit 2012d4d

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

test/functional/mining_basic.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
assert_raises_rpc_error,
2626
bytes_to_hex_str as b2x,
2727
)
28-
28+
from test_framework.script import CScriptNum
2929

3030
def assert_template(node, block, expect, rehash=True):
3131
if rehash:
@@ -65,11 +65,19 @@ def assert_submitblock(block, result_str_1, result_str_2=None):
6565
assert 'proposal' in tmpl['capabilities']
6666
assert 'coinbasetxn' not in tmpl
6767

68-
coinbase_tx = create_coinbase(height=int(tmpl["height"]) + 1)
68+
next_height = int(tmpl["height"])
69+
coinbase_tx = create_coinbase(height=next_height)
6970
# sequence numbers must not be max for nLockTime to have effect
7071
coinbase_tx.vin[0].nSequence = 2 ** 32 - 2
7172
coinbase_tx.rehash()
7273

74+
# round-trip the encoded bip34 block height commitment
75+
assert_equal(CScriptNum.decode(coinbase_tx.vin[0].scriptSig), next_height)
76+
# round-trip negative and multi-byte CScriptNums to catch python regression
77+
assert_equal(CScriptNum.decode(CScriptNum.encode(CScriptNum(1500))), 1500)
78+
assert_equal(CScriptNum.decode(CScriptNum.encode(CScriptNum(-1500))), -1500)
79+
assert_equal(CScriptNum.decode(CScriptNum.encode(CScriptNum(-1))), -1)
80+
7381
block = CBlock()
7482
block.nVersion = tmpl["version"]
7583
block.hashPrevBlock = int(tmpl["previousblockhash"], 16)

test/functional/test_framework/script.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,22 @@ def encode(obj):
385385
r[-1] |= 0x80
386386
return bytes([len(r)]) + r
387387

388+
@staticmethod
389+
def decode(vch):
390+
result = 0
391+
# We assume valid push_size and minimal encoding
392+
value = vch[1:]
393+
if len(value) == 0:
394+
return result
395+
for i, byte in enumerate(value):
396+
result |= int(byte) << 8*i
397+
if value[-1] >= 0x80:
398+
# Mask for all but the highest result bit
399+
num_mask = (2**(len(value)*8) - 1) >> 1
400+
result &= num_mask
401+
result *= -1
402+
return result
403+
388404

389405
class CScript(bytes):
390406
"""Serialized script

0 commit comments

Comments
 (0)