Skip to content

Commit d0dc7a9

Browse files
committed
Add CScriptOp.(encode|decode)_op_n() unit tests
Fixed a few uncovered bugs
1 parent 4fd5300 commit d0dc7a9

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

bitcoin/script.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -52,13 +52,13 @@ def encode_op_n(n):
5252
if n == 0:
5353
return OP_0
5454
else:
55-
return OP_1 + n-1
55+
return CScriptOp(OP_1 + n-1)
5656

5757
def decode_op_n(self):
5858
if self == OP_0:
5959
return 0
6060

61-
if not (OP_0 <= self <= OP_16):
61+
if not (self == OP_0 or OP_1 <= self <= OP_16):
6262
raise ValueError('op %r is not an OP_N' % self)
6363

6464
return int(self - OP_1+1)

bitcoin/tests/test_script.py

+34
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,40 @@ def test_is_singleton(self):
3939
for i in range(0x0, 0x100):
4040
self.assertTrue(CScriptOp(i) is CScriptOp(i))
4141

42+
def test_encode_decode_op_n(self):
43+
def t(n, op):
44+
actual = CScriptOp.encode_op_n(n)
45+
self.assertEqual(actual, op)
46+
self.assertTrue(isinstance(actual, CScriptOp))
47+
48+
actual = op.decode_op_n()
49+
self.assertEqual(actual, n)
50+
self.assertTrue(isinstance(actual, int))
51+
52+
t(0, OP_0)
53+
t(1, OP_1)
54+
t(2, OP_2)
55+
t(3, OP_3)
56+
t(4, OP_4)
57+
t(5, OP_5)
58+
t(6, OP_6)
59+
t(7, OP_7)
60+
t(8, OP_8)
61+
t(9, OP_9)
62+
t(9, OP_9)
63+
t(10, OP_10)
64+
t(11, OP_11)
65+
t(12, OP_12)
66+
t(13, OP_13)
67+
t(14, OP_14)
68+
t(15, OP_15)
69+
t(16, OP_16)
70+
71+
with self.assertRaises(ValueError):
72+
OP_CHECKSIG.decode_op_n()
73+
74+
with self.assertRaises(ValueError):
75+
CScriptOp(1).decode_op_n()
4276

4377
class Test_CScript(unittest.TestCase):
4478
def test_tokenize_roundtrip(self):

0 commit comments

Comments
 (0)