forked from gandrewstone/bchscript
-
Notifications
You must be signed in to change notification settings - Fork 1
/
bchc
executable file
·373 lines (310 loc) · 10.5 KB
/
bchc
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
#!/usr/bin/python3
import pdb
import re
import sys
import argparse
import io
from bchscript.bchutil import *
from bchscript.bchprimitives import *
from bchscript.bchimmediates import immediates, BchAddress
class ParserError(Exception):
pass
multiTokens = ["->", "...", "bchtest:", "bitcoincash:", "bchreg:"]
unitaryTokens = """,./?~`#$%^&*()-+=\|}{[]'";:"""
bchStatements = primitives
bchStatements.update(immediates)
def statementConsumer(tokens, n, localSymbols):
stmts = []
while 1:
if n >= len(tokens):
break
try:
i = int(tokens[n]) # Push a number onto the stack
stmts.append(i)
n += 1
except:
if tokens[n][0] == '"': # Push data onto the stack
stmts.append(tokens[n])
n += 1
elif tokens[n] in localSymbols:
syms = copy.copy(bchStatements)
syms.update(localSymbols)
(n, obj) = localSymbols[tokens[n]].parse(tokens, n + 1, syms)
stmts.append(obj)
elif tokens[n] in bchStatements:
syms = copy.copy(bchStatements)
syms.update(localSymbols)
(n, obj) = bchStatements[tokens[n]].parse(tokens, n + 1, syms)
if obj.outputs:
localSymbols.update(obj.outputs)
stmts.append(obj)
else:
break
return (n, stmts)
SetStatementConsumerCallout(statementConsumer)
class Scriptify:
def __init__(self):
self.name = "scriptify!"
self.statements = None
self.args = []
def parse(self, tokens, n, symbols=None):
"""
default doesn't accept any other tokens
"""
global bchStatements
syms = copy.copy(bchStatements)
if symbols:
syms.update(symbols)
assert tokens[n] == "("
(n, self.args) = argsConsumer(tokens, n, syms)
dup = copy.copy(self)
dup.name = self.args[0].strip("'").strip('"')
dup.statements = listify(self.args[1])
return (n, dup)
def compile(self, symbols):
output = compileStatementList(self.statements, symbols)
spend = self.solve(output)
return (self.name, {"script": output, "spend": spend})
def solve(self, pgm, n=0, end=None):
if end is None:
end = len(pgm)
ret = []
while n < end:
item = pgm[n]
if type(item) is str and item[0] == "@":
ret.append(item)
n += 1
continue
elif type(item) is str and item == "OP_IF":
(els, endif) = condSection(n, pgm)
ret.append([self.solve(pgm, n + 1, els - 1), self.solve(pgm, els + 1, endif - 1)])
n = endif + 1
else:
n += 1
return ret
class P2shify(Scriptify):
def __init__(self):
Scriptify.__init__(self)
self.name = "p2shify!"
self.statements = None
def compile(self, symbols):
pred = compileStatementList(self.statements, symbols)
spend = self.solve(pred)
scriptHash = hash160(script2bin(pred))
p2sh = [primitives["OP_HASH160"], scriptHash, primitives["OP_EQUAL"], script2bin(pred)]
return (self.name, {"script": p2sh, "spend": spend, "predicate": pred})
class Define:
def __init__(self):
self.name = "def"
self.statements = None
self.args = None
def matchArgs(self, bindings):
"""Match passed arguments with their definitions to produce a dictionary of { symbol: binding } pairs
"""
ret = {}
count = 0
for b in bindings:
a = self.args[count]
if type(b) == list:
pdb.set_trace()
ret[a] = b
count += 1
return ret
def compile(self, invocation):
if invocation is None: # a raw define produces no output, it must be applied
return [] # note that a 0-arg invocation will be an empty dict
return compileStatementList(self.statements, invocation)
def parse(self, tokens, n, symbols=None):
"""
default doesn't accept any other tokens
"""
global bchStatements
self.define = tokens[n]
n += 1
if tokens[n] == "(":
(n, self.args) = paramsConsumer(tokens, n)
if tokens[n] == "->":
(n, self.results) = paramsConsumer(tokens, n + 1)
assert tokens[n] == "{"
n += 1
(n, self.statements) = statementConsumer(tokens, n, self.args)
assert tokens[n] == "}"
tmp = Binding(self.define)
cpy = copy.copy(self)
tmp.instanceOf = cpy
bchStatements[self.define] = tmp
return (n + 1, cpy)
class Include:
"""Implement the include primitive"""
def __init__(self):
self.name = "def"
self.statements = None
def parse(self, tokens, n, symbols=None):
filename = tokens[n].strip("'").strip('"')
inp = open(filename, "r")
newtokens = lex(inp)
# insert the tokens of the included file at this point
tokens[n + 1:n + 1] = newtokens
return (n + 1, copy.copy(self))
def compile(self, symbols):
return []
topScope = {"def": Define(), "scriptify!": Scriptify(), "p2shify!": P2shify(), "include": Include()}
def topParser(tokens, n):
stmts = []
while tokens[n] in topScope:
# print(tokens[n])
(n, obj) = topScope[tokens[n]].parse(tokens, n + 1)
stmts.append(obj)
if n >= len(tokens): # all done
break
if n < len(tokens):
raise ParserError("""Parsing stopped at token %d: '%s'\ncontext:\n %s)""" %
(n, tokens[n], " ".join(tokens[n - 20:min(len(tokens), n + 20)])))
return (n, stmts)
def separate(t):
ret = []
cur = []
for tok in multiTokens:
idx = t.find(tok)
if idx != -1:
pfx = separate(t[0:idx])
sfx = separate(t[idx + len(tok):])
return pfx + [tok] + sfx
for c in t:
if c in unitaryTokens:
if cur:
ret.append("".join(cur))
cur = []
ret.append(c)
else:
cur.append(c)
if cur:
ret.append("".join(cur))
return ret
def lex(fin):
ret = []
for line in fin:
tcomment = line.split("//")
splitquotes = [x for x in re.split("( |\\\".*?\\\"|'.*?')", tcomment[0]) if x.strip()]
# print(splitquotes)
# pdb.set_trace()
for sq in splitquotes:
if sq[0] == '"' or sq[0] == "'":
ret.append(sq)
else:
tspc = sq.split()
for t in tspc:
tokens = separate(t)
# print(tokens)
ret += tokens
return ret
def bchCompile(program):
commands = []
for p in program:
temp = p.compile(None)
commands.append(temp)
ret = {}
for c in commands:
if type(c) is tuple:
ret[c[0]] = c[1]
return ret
def condSection(start, pgm):
"""find else and endif clauses"""
nif = 0
nelse = 0
elsepos = None
pos = start
while pos < len(pgm):
if pgm[pos] == "OP_IF":
nif += 1
elif pgm[pos] == "OP_ELSE":
if nif == 1:
elsepos = pos
elif pgm[pos] == "OP_ENDIF":
nif -= 1
if nif == 0:
return(elsepos, pos)
pos += 1
assert 0 # not closed
def prettyPrint(opcodes):
"""Convert a program to a human-readable string"""
ret = []
indent = 0
for opcode in opcodes:
if type(opcode) is str and opcode[0] == "@":
continue
if type(opcode) is Primitive:
opcode = opcode.name
if type(opcode) is BchAddress:
opcode = opcode.name
if opcode in ["OP_ELSE", "OP_ENDIF"]:
indent -= 4
if type(opcode) is bytes:
ret.append(" " * indent + ToHex(opcode))
else:
ret.append(" " * indent + str(opcode).strip('"').strip("'"))
if opcode in ["OP_IF", "OP_ELSE"]:
indent += 4
return "\n".join(ret)
def compile(s):
"""Accepts either a string or an iterable of lines"""
if type(s) is str:
s = s.split("\n")
tokens = lex(s)
(n, program) = topParser(tokens, 0)
result = bchCompile(program)
return result
def main(argv):
parser = argparse.ArgumentParser(prog="bchc", description='Compile BchScript')
parser.add_argument('input', nargs="?", help='input file or string program', default=None)
parser.add_argument('--hex', action='store_true', default=False, dest='hex', help='compile into hex')
parser.add_argument('--opc', action='store_true', default=False, dest='opcode', help='compile into opcodes')
parser.add_argument('--display', action='store', default='main', dest='display', help='what to output')
parser.add_argument('-o', action='store', dest='output', help='write output to specified file')
params = parser.parse_args(argv[1:])
if params.hex == False and params.opcode == False:
params.hex = True
inp = None
if params.input:
try:
inp = open(params.input, "r")
except FileNotFoundError as e:
if "OP" in params.input: # try it as a text script
inp = params.input
else:
inp = sys.stdin
out = []
if inp:
result = compile(inp)
if params.display == 'all':
ret = {}
for (key, value) in result.items():
d = {}
out = []
t = value["script"]
if params.hex:
out.append(ToHex(script2bin(t)))
if params.opcode:
out.append(prettyPrint(t))
d["script"] = out
d["spend"] = value["spend"]
ret[key] = d
out = [str(ret)]
else:
try:
t = result[params.display]["script"]
except KeyError:
sys.stderr.write("Include a 'main' scriptify! command\n")
return
if params.hex:
out.append(ToHex(script2bin(t)))
if params.opcode:
out.append(prettyPrint(t))
if params.output:
outf = open(params.output, "w")
else:
outf = sys.stdout
outf.write("\n".join(out))
outf.write("\n")
if __name__ == "__main__":
main(sys.argv)