-
Notifications
You must be signed in to change notification settings - Fork 0
/
ScriptBuilder.cs
107 lines (95 loc) · 3.32 KB
/
ScriptBuilder.cs
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
using System;
using System.IO;
using System.Numerics;
using System.Text;
namespace Quras.VM
{
public class ScriptBuilder : IDisposable
{
private MemoryStream ms = new MemoryStream();
public int Offset => (int)ms.Position;
public void Dispose()
{
ms.Dispose();
}
public ScriptBuilder Emit(OpCode op, byte[] arg = null)
{
ms.WriteByte((byte)op);
if (arg != null)
ms.Write(arg, 0, arg.Length);
return this;
}
public ScriptBuilder EmitAppCall(byte[] scriptHash, bool useTailCall = false)
{
if (scriptHash.Length != 20)
throw new ArgumentException();
return Emit(useTailCall ? OpCode.TAILCALL : OpCode.APPCALL, scriptHash);
}
public ScriptBuilder EmitJump(OpCode op, short offset)
{
if (op != OpCode.JMP && op != OpCode.JMPIF && op != OpCode.JMPIFNOT && op != OpCode.CALL)
throw new ArgumentException();
return Emit(op, BitConverter.GetBytes(offset));
}
public ScriptBuilder EmitPush(BigInteger number)
{
if (number == -1) return Emit(OpCode.PUSHM1);
if (number == 0) return Emit(OpCode.PUSH0);
if (number > 0 && number <= 16) return Emit(OpCode.PUSH1 - 1 + (byte)number);
return EmitPush(number.ToByteArray());
}
public ScriptBuilder EmitPush(bool data)
{
return Emit(data ? OpCode.PUSHT : OpCode.PUSHF);
}
public ScriptBuilder EmitPush(byte[] data)
{
if (data == null)
throw new ArgumentNullException();
if (data.Length <= (int)OpCode.PUSHBYTES75)
{
ms.WriteByte((byte)data.Length);
ms.Write(data, 0, data.Length);
}
else if (data.Length < 0x100)
{
Emit(OpCode.PUSHDATA1);
ms.WriteByte((byte)data.Length);
ms.Write(data, 0, data.Length);
}
else if (data.Length < 0x10000)
{
Emit(OpCode.PUSHDATA2);
ms.Write(BitConverter.GetBytes((ushort)data.Length), 0, 2);
ms.Write(data, 0, data.Length);
}
else// if (data.Length < 0x100000000L)
{
Emit(OpCode.PUSHDATA4);
ms.Write(BitConverter.GetBytes((uint)data.Length), 0, 4);
ms.Write(data, 0, data.Length);
}
return this;
}
public ScriptBuilder EmitPush(string data)
{
return EmitPush(Encoding.UTF8.GetBytes(data));
}
public ScriptBuilder EmitSysCall(string api)
{
if (api == null)
throw new ArgumentNullException();
byte[] api_bytes = Encoding.ASCII.GetBytes(api);
if (api_bytes.Length == 0 || api_bytes.Length > 252)
throw new ArgumentException();
byte[] arg = new byte[api_bytes.Length + 1];
arg[0] = (byte)api_bytes.Length;
Buffer.BlockCopy(api_bytes, 0, arg, 1, api_bytes.Length);
return Emit(OpCode.SYSCALL, arg);
}
public byte[] ToArray()
{
return ms.ToArray();
}
}
}