-
Notifications
You must be signed in to change notification settings - Fork 2
/
script.py
185 lines (150 loc) · 5 KB
/
script.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
"""
Script implementation
"""
from io import BytesIO
from logging import Logger
from typing import List
from helper import (
encode_varint,
int_to_little_endian,
little_endian_to_int,
read_varint
)
from op import (
OP_CODE_FUNCTIONS,
OP_CODE_NAMES,
op_equal,
op_hash160,
op_verify
)
LOGGER = Logger
def p2pkh_script(h160):
"""
Takes a hash160 and returns the p2pkh ScriptPubKey
"""
return Script([0x76, 0xa9, h160, 0x88, 0xac])
class Script:
"""
Defines attributes and methods of Script
"""
def __init__(self, cmds=None) -> None:
"""
Initialize new Script
"""
if cmds is None:
self.cmds: List = []
else:
self.cmds = cmds
@classmethod
def parse(cls, s: BytesIO):
"""
Parse a stream
"""
length = read_varint(s)
cmds = []
count = 0
while count < length:
current = s.read(1)
count += 1
current_byte = current[0]
if current_byte >= 1 and current_byte <= 75:
n = current_byte
cmds.append(s.read(n))
count += n
elif current_byte == 76:
data_length = little_endian_to_int(s.read(1))
cmds.append(s.read(data_length))
count += data_length + 1
elif current_byte == 77:
data_length = little_endian_to_int(s.read(2))
cmds.append(s.read(data_length))
count += data_length + 2
else:
op_code = current_byte
cmds.append(op_code)
if count != length:
raise SyntaxError('parsing script failed')
return cls(cmds)
def raw_serialize(self):
"""
Serialize a raw script
"""
result = b''
for cmd in self.cmds:
if type(cmd) == int:
result += int_to_little_endian(cmd, 1)
else:
length = len(cmd)
if length < 75:
result += int_to_little_endian(length, 1)
elif length > 75 and length < 0x100:
result += int_to_little_endian(76, 1)
result += int_to_little_endian(length, 1)
elif length >= 0x100 and length <=520:
result += int_to_little_endian(77, 1)
result += int_to_little_endian(length, 2)
else:
raise ValueError('too long an cmd')
result += cmd
return result
def serialize(self):
"""
Serialize a script
"""
result = self.raw_serialize()
total = len(result)
return encode_varint(total) + result
def __add__(self, other):
"""
Combine two command sets to create a new Script object
"""
return Script(self.cmds + other.cmds)
def evaluate(self, z) -> bool:
"""
Evaluates Script
"""
cmds = self.cmds[:]
stack = []
altstack = []
while len(cmds) > 0:
cmd = cmds.pop(0)
if type(cmd) == int:
operation = OP_CODE_FUNCTIONS[cmd]
if cmd in (99, 100):
if not operation(stack, cmds):
LOGGER.info(f'bad op: {OP_CODE_NAMES[cmd]}')
return False
elif cmd in (107, 108):
if not operation(stack, altstack):
LOGGER.info(f'bad op: {OP_CODE_NAMES[cmd]}')
return False
elif cmd in (172, 173, 274, 175):
if not operation(stack, z):
LOGGER.info(f'bad op: {OP_CODE_NAMES[cmd]}')
return False
else:
if not operation(stack):
LOGGER.info(f'bad op: {OP_CODE_NAMES[cmd]}')
return False
else:
stack.append(cmd)
if len(cmds) == 3 and cmds[0] == 0xa9 and type(cmds[1]) == bytes and len(cmds[1]) == 20 and cmds[2] == 0x87:
cmds.pop()
h160 = cmds.pop()
cmds.pop()
if not op_hash160(stack):
return False
stack.append(h160)
if not op_equal(stack):
return False
if not op_verify(stack):
LOGGER.info("bad p2sh h160")
return False
redeem_script = encode_varint(len(cmd) + cmd)
stream = BytesIO(redeem_script)
cmds.extend(Script.parse(stream).cmds)
if len(stack) == 0:
return False
if stack.pop() == b'':
return False
return True