This repository has been archived by the owner on Nov 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 192
/
ApplicationEngine.py
332 lines (221 loc) · 9.35 KB
/
ApplicationEngine.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
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
from neo.VM.ExecutionEngine import ExecutionEngine
from neo.VM.OpCode import *
from neo.VM import VMState
from neo.Cryptography.Crypto import Crypto
from neo.Fixed8 import Fixed8
import sys
import os
from autologging import logged
# used for ApplicationEngine.Run
from neo.Implementations.Blockchains.LevelDB.DBPrefix import DBPrefix
from neo.Implementations.Blockchains.LevelDB.DBCollection import DBCollection
from neo.Implementations.Blockchains.LevelDB.CachedScriptTable import CachedScriptTable
from neo.Core.State import ContractState, AssetState, AccountState, ValidatorState, StorageItem
from neo.SmartContract import TriggerType
@logged
class ApplicationEngine(ExecutionEngine):
ratio = 100000
gas_free = 10 * 100000000
gas_amount = 0
gas_consumed = 0
testMode = False
Trigger = None
def GasConsumed(self):
return Fixed8(self.gas_consumed)
def __init__(self, trigger_type, container, table, service, gas, testMode=False):
super(ApplicationEngine, self).__init__(container=container, crypto=Crypto.Default(), table=table, service=service)
self.Trigger = trigger_type
self.gas_amount = self.gas_free + gas.value
self.testMode = testMode
def CheckArraySize(self):
maxArraySize = 1024
if self.CurrentContext.InstructionPointer >= len(self.CurrentContext.Script):
return True
opcode = self.CurrentContext.NextInstruction
if opcode == PACK or opcode == NEWARRAY:
size = self.EvaluationStack.Peek().GetBigInteger()
if size > maxArraySize:
return False
return True
return True
def CheckInvocationStack(self):
maxStackSize = 1024
if self.CurrentContext.InstructionPointer >= len(self.CurrentContext.Script):
return True
opcode = self.CurrentContext.NextInstruction
if opcode == CALL or opcode == APPCALL:
if self.InvocationStack.Count >= maxStackSize:
return False
return True
return True
def CheckItemSize(self):
maxItemSize = 1024 * 1024
if self.CurrentContext.InstructionPointer >= len(self.CurrentContext.Script):
return True
opcode = self.CurrentContext.NextInstruction
if opcode == PUSHDATA4:
if self.CurrentContext.InstructionPointer + 4 >= len(self.CurrentContext.Script):
return False
# TODO this should be double checked. it has been
# double checked and seems to work, but could possibly not work
position = self.CurrentContext.InstructionPointer + 1
lengthpointer = self.CurrentContext.Script[position:position + 4]
length = int.from_bytes(lengthpointer, 'little')
if length > maxItemSize:
return False
return True
elif opcode == CAT:
if self.EvaluationStack.Count < 2:
return False
length = 0
try:
length = len(self.EvaluationStack.Peek(0).GetByteArray()) + len(self.EvaluationStack.Peek(1).GetByteArray())
except Exception as e:
self.__log.debug("colud not get length %s " % e)
if length > maxItemSize:
return False
return True
return True
def CheckStackSize(self):
maxStackSize = 2 * 1024
if self.CurrentContext.InstructionPointer >= len(self.CurrentContext.Script):
return True
size = 0
opcode = self.CurrentContext.NextInstruction
if opcode < PUSH16:
size = 1
else:
if opcode in [DEPTH, DUP, OVER, TUCK]:
size = 1
elif opcode == UNPACK:
item = self.EvaluationStack.Peek()
if not item.IsArray:
return False
size = len(item.GetArray())
if size == 0:
return True
size += self.EvaluationStack.Count + self.AltStack.Count
if size > maxStackSize:
print("SIZE IS OVER MAX STACK SIZE!!!!")
return False
return True
def Execute(self):
while self._VMState & VMState.HALT == 0 and self._VMState & VMState.FAULT == 0:
try:
self.gas_consumed = self.gas_consumed + self.GetPrice() * self.ratio
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
self.__log.debug(exc_type, fname, exc_tb.tb_lineno)
self.__log.debug("exception calculating gas consumed %s " % e)
print("Exception calculating gas consumed %s " % e)
return False
if not self.testMode and self.gas_consumed > self.gas_amount:
return False
if not self.CheckItemSize():
return False
if not self.CheckStackSize():
return False
if not self.CheckArraySize():
return False
if not self.CheckInvocationStack():
return False
self.StepInto()
return not self._VMState & VMState.FAULT > 0
def GetPrice(self):
if self.CurrentContext.InstructionPointer >= len(self.CurrentContext.Script):
return 0
opcode = self.CurrentContext.NextInstruction
if opcode <= PUSH16:
return 0
if opcode == NOP:
return 0
elif opcode == APPCALL or opcode == TAILCALL:
return 10
elif opcode == SYSCALL:
return self.GetPriceForSysCall()
elif opcode == SHA1 or opcode == SHA256:
return 10
elif opcode == HASH160 or opcode == HASH256:
return 20
elif opcode == CHECKSIG:
return 100
elif opcode == CHECKMULTISIG:
if self.EvaluationStack.Count == 0:
return 1
n = self.EvaluationStack.Peek().GetBigInteger()
if n < 1:
return 1
return 100 * n
return 1
def GetPriceForSysCall(self):
if self.CurrentContext.InstructionPointer >= len(self.CurrentContext.Script) - 3:
return 1
length = self.CurrentContext.Script[self.CurrentContext.InstructionPointer + 1]
if self.CurrentContext.InstructionPointer > len(self.CurrentContext.Script) - length - 2:
return 1
strbytes = self.CurrentContext.Script[self.CurrentContext.InstructionPointer + 2:length + self.CurrentContext.InstructionPointer + 2]
api_name = strbytes.decode('utf-8')
api = api_name.replace('Antshares.', 'Neo.')
if api == "Neo.Runtime.CheckWitness":
return 200
elif api == "Neo.Blockchain.GetHeader":
return 100
elif api == "Neo.Blockchain.GetBlock":
return 200
elif api == "Neo.Blockchain.GetTransaction":
return 100
elif api == "Neo.Blockchain.GetAccount":
return 100
elif api == "Neo.Blockchain..GetValidators":
return 200
elif api == "Neo.Blockchain.GetAsset":
return 100
elif api == "Neo.Blockchain.GetContract":
return 100
elif api == "Neo.Blockchain.GetReferences":
return 200
elif api == "Neo.Account.SetVotes":
return 1000
elif api == "Neo.Validator.Register":
return int(1000 * 100000000 / self.ratio)
elif api == "Neo.Asset.Create":
return int(5000 * 100000000 / self.ratio)
elif api == "Neo.Asset.Renew":
return int(self.EvaluationStack.Peek(1).GetBigInteger() * 5000 * 100000000 / self.ratio)
elif api == "Neo.Contract.Create" or api == "Neo.Contract.Migrate":
amount = int(500 * 100000000 / self.ratio)
return amount
elif api == "Neo.Storage.Get":
return 100
elif api == "Neo.Storage.Put":
l1 = len(self.EvaluationStack.Peek(1).GetByteArray())
l2 = len(self.EvaluationStack.Peek(2).GetByteArray())
return int(((l1 + l2 - 1) / 1024 + 1) * 1000)
elif api == "Neo.Storage.Delete":
return 100
return 1
@staticmethod
def Run(script, container=None):
from neo.Core.Blockchain import Blockchain
from neo.SmartContract.StateMachine import StateMachine
bc = Blockchain.Default()
sn = bc._db.snapshot()
accounts = DBCollection(bc._db, sn, DBPrefix.ST_Account, AccountState)
assets = DBCollection(bc._db, sn, DBPrefix.ST_Asset, AssetState)
validators = DBCollection(bc._db, sn, DBPrefix.ST_Validator, ValidatorState)
contracts = DBCollection(bc._db, sn, DBPrefix.ST_Contract, ContractState)
storages = DBCollection(bc._db, sn, DBPrefix.ST_Storage, StorageItem)
script_table = CachedScriptTable(contracts)
service = StateMachine(accounts, validators, assets, contracts, storages, None)
engine = ApplicationEngine(
trigger_type=TriggerType.Application,
container=container,
table=script_table,
service=service,
gas=Fixed8.Zero(),
testMode=True
)
engine.LoadScript(script, False)
engine.Execute()
return engine