-
Notifications
You must be signed in to change notification settings - Fork 3
/
Fairy.Engine.cs
416 lines (377 loc) · 17.8 KB
/
Fairy.Engine.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
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
using Neo.Json;
using Neo.Network.P2P.Payloads;
using Neo.Persistence;
using Neo.SmartContract;
using Neo.SmartContract.Native;
using Neo.VM;
using Neo.Wallets;
using System.Numerics;
using System.Reflection;
namespace Neo.Plugins
{
public partial class Fairy
{
public static FairySession NewFairySession(NeoSystem system, Fairy? fairy = null, DataCache? snapshot = null)
{
if (fairy == null)
fairy = new(system, settings: RpcServerSettings.Default);
return new FairySession(fairy, snapshot);
}
public static FairyEngine NewFairyEngine(NeoSystem system, Fairy? fairy = null, DataCache? snapshot = null)
{
if (fairy == null)
fairy = new(system, settings: RpcServerSettings.Default);
return Fairy.FairyEngine.Run(new byte[] { 0x40 }, snapshot == null ? fairy.system.StoreView : snapshot, fairy, settings: fairy.system.Settings, gas: fairy.settings.MaxGasInvoke);
}
public class FairyEngine : ApplicationEngine
{
readonly Fairy fairy;
protected FairyEngine(TriggerType trigger, IVerifiable container, DataCache snapshot, Block persistingBlock, ProtocolSettings settings, long gas, IDiagnostic diagnostic, Fairy fairy, FairyEngine? oldEngine = null, bool copyRuntimeArgs = false)
: base(trigger, container, snapshot, persistingBlock, settings, gas, diagnostic, jumpTable: ComposeFairyJumpTable())
{
this.fairy = fairy;
if (oldEngine != null)
{
if (copyRuntimeArgs)
{
this.services = oldEngine.services.ToDictionary(kvpair => kvpair.Key, kvpair => kvpair.Value); // clone
this.runtimeArgs = (RuntimeArgs)oldEngine.runtimeArgs.Clone();
}
else
{
this.services = oldEngine.services;
this.runtimeArgs = oldEngine.runtimeArgs;
}
}
else
{
this.services = ApplicationEngine.Services.ToDictionary(kvpair => kvpair.Key, kvpair => kvpair.Value);
this.runtimeArgs = new RuntimeArgs(fairy.defaultFairyWallet);
}
}
public static FairyEngine Create(TriggerType trigger, IVerifiable container, DataCache snapshot, Fairy fairy, Block persistingBlock = null, ProtocolSettings settings = null, long gas = TestModeGas, IDiagnostic diagnostic = null, FairyEngine? oldEngine = null, bool copyRuntimeArgs = false)
{
return new FairyEngine(trigger, container, snapshot, persistingBlock, settings, gas, diagnostic, fairy, oldEngine: oldEngine, copyRuntimeArgs: copyRuntimeArgs);
}
public new VMState State
{
get
{
return base.State;
}
set
{
base.State = value;
}
}
public new void ExecuteNext()
{
base.ExecuteNext();
}
public new VMState Execute()
{
if (State == VMState.BREAK)
State = VMState.NONE;
while (State != VMState.HALT && State != VMState.FAULT)
{
uint currentInstructionPointer = (uint)this.CurrentContext!.InstructionPointer;
UInt160 currentScripthash = this.CurrentScriptHash;
ExecuteNext();
if (currentScripthash != null && fairy.contractScriptHashToInstructionPointerToCoverage.ContainsKey(currentScripthash) && fairy.contractScriptHashToInstructionPointerToCoverage[currentScripthash].ContainsKey(currentInstructionPointer))
fairy.contractScriptHashToInstructionPointerToCoverage[currentScripthash][currentInstructionPointer] = true;
}
return State;
}
public static FairyEngine Run(ReadOnlyMemory<byte> script, DataCache snapshot, Fairy fairy, IVerifiable? container = null, Block? persistingBlock = null, ProtocolSettings? settings = null, int offset = 0, long gas = TestModeGas, IDiagnostic? diagnostic = null, FairyEngine? oldEngine = null, bool copyRuntimeArgs = false)
{
persistingBlock ??= CreateDummyBlockWithTimestamp(snapshot, settings ?? ProtocolSettings.Default, timestamp: null);
FairyEngine engine = Create(TriggerType.Application, container, snapshot, fairy, persistingBlock, settings, gas, diagnostic, oldEngine: oldEngine, copyRuntimeArgs: copyRuntimeArgs);
engine.LoadScript(script, initialPosition: offset);
engine.Execute();
return engine;
}
public Dictionary<uint, InteropDescriptor> services;
public class RuntimeArgs : ICloneable
{
public RuntimeArgs(Wallet fairyWallet)
{
this.fairyWallet = fairyWallet;
}
public Wallet fairyWallet;
public ulong? timestamp = null;
public BigInteger? designatedRandom = null;
public bool checkWitnessReturnTrue = false;
public object Clone() => MemberwiseClone();
//public uint? blockIndex = null;
}
public RuntimeArgs runtimeArgs;
protected static JumpTable ComposeFairyJumpTable()
{
var table = new JumpTable();
table[OpCode.SYSCALL] = OnSysCall;
table[OpCode.CALLT] = OnCallT;
return table;
}
protected static new void OnSysCall(ExecutionEngine engine, Instruction instruction)
{
if (engine is FairyEngine fairyEngine)
{
uint method = instruction.TokenU32;
fairyEngine.OnSysCall(fairyEngine.services[method]);
}
else
{
throw new InvalidOperationException();
}
}
public InteropDescriptor Register(string name, MethodInfo method, uint hash, long fixedPrice, CallFlags requiredCallFlags)
{
InteropDescriptor descriptor = new()
{
Name = name,
Handler = method,
FixedPrice = fixedPrice,
RequiredCallFlags = requiredCallFlags
};
this.services ??= new Dictionary<uint, InteropDescriptor>();
this.services[hash] = descriptor;
return descriptor;
}
public new bool CheckWitness(byte[] hashOrPubkey) => base.CheckWitness(hashOrPubkey);
public bool CheckFairyWitness(byte[] hashOrPubkey) => runtimeArgs.checkWitnessReturnTrue || CheckWitness(hashOrPubkey);
public new BigInteger GetRandom() => base.GetRandom();
public BigInteger GetFairyRandom() => runtimeArgs.designatedRandom != null ? (BigInteger)runtimeArgs.designatedRandom : base.GetRandom();
public new ulong GetTime()
{
ulong result = base.GetTime();
if (result != 0)
return result;
uint currentIndex = NativeContract.Ledger.CurrentIndex(Snapshot);
Block currentBlock = NativeContract.Ledger.GetBlock(Snapshot, currentIndex);
return currentBlock.Timestamp + ProtocolSettings.MillisecondsPerBlock;
}
public ulong GetFairyTime() => runtimeArgs.timestamp != null ? (ulong)runtimeArgs.timestamp : GetTime();
//public ulong GetFairyBlockIndex() => serviceArgs.blockIndex != null ? (uint)serviceArgs.blockIndex : NativeContract.Ledger.CurrentIndex(this.Snapshot);
}
[RpcMethod]
protected virtual JToken SetSnapshotTimestamp(JArray _params)
{
string session = _params[0]!.AsString();
ulong? timestamp;
if (_params[1] == null)
{
timestamp = null;
sessionStringToFairySession[session].timestamp = null;
}
else
{
timestamp = ulong.Parse(_params[1]!.AsString());
sessionStringToFairySession[session].timestamp = timestamp;
}
JObject json = new();
json[session] = timestamp;
return json;
}
[RpcMethod]
protected virtual JToken GetSnapshotTimeStamp(JArray _params)
{
JObject json = new();
foreach (var s in _params)
{
string session = s!.AsString();
json[session] = sessionStringToFairySession[session].timestamp;
}
return json;
}
[RpcMethod]
protected virtual JToken SetSnapshotRandom(JArray _params)
{
string session = _params[0]!.AsString();
string? designatedRandomString = _params[1]?.AsString();
FairySession fairySession = sessionStringToFairySession[session];
if (designatedRandomString == null)
fairySession.designatedRandom = null;
else
fairySession.designatedRandom = BigInteger.Parse(designatedRandomString);
JObject json = new();
json[session] = designatedRandomString;
return json;
}
[RpcMethod]
protected virtual JToken GetSnapshotRandom(JArray _params)
{
JObject json = new();
foreach (var s in _params)
{
string session = s!.AsString();
if (sessionStringToFairySession.ContainsKey(session))
json[session] = sessionStringToFairySession[session].designatedRandom.ToString();
else
json[session] = null;
}
return json;
}
[RpcMethod]
protected virtual JToken SetSnapshotCheckWitness(JArray _params)
{
string session = _params[0]!.AsString();
bool setValue = _params[1]!.AsBoolean();
FairySession fairySession = sessionStringToFairySession[session];
fairySession.checkWitnessReturnTrue = setValue;
JObject json = new();
json[session] = setValue;
return json;
}
[RpcMethod]
protected virtual JToken GetSnapshotCheckWitness(JArray _params)
{
JObject json = new();
foreach (var s in _params)
{
string session = s!.AsString();
if (sessionStringToFairySession.ContainsKey(session))
json[session] = sessionStringToFairySession[session].checkWitnessReturnTrue;
else
json[session] = null;
}
return json;
}
private static Block CreateDummyBlockWithTimestamp(DataCache snapshot, ProtocolSettings settings, ulong? timestamp = null, uint? index = null)
{
UInt256 hash = NativeContract.Ledger.CurrentHash(snapshot);
Block currentBlock = NativeContract.Ledger.GetBlock(snapshot, hash);
return new Block
{
Header = new Header
{
Version = 0,
PrevHash = hash,
MerkleRoot = new UInt256(),
Timestamp = timestamp == null ? currentBlock.Timestamp + settings.MillisecondsPerBlock : (ulong)timestamp,
Index = index == null ? currentBlock.Index + 1 : (uint)index,
NextConsensus = currentBlock.NextConsensus,
Witness = new Witness
{
InvocationScript = System.Array.Empty<byte>(),
VerificationScript = System.Array.Empty<byte>()
},
},
Transactions = System.Array.Empty<Transaction>()
};
}
public class FairySession
{
readonly Fairy fairy;
public DateTime StartTime;
public FairyEngine engine { get { ResetExpiration(); return _engine; } set { _engine = value; ResetExpiration(); } }
private FairyEngine _engine;
public FairyEngine? debugEngine { get { ResetExpiration(); return _debugEngine; } set { _debugEngine = value; ResetExpiration(); } }
private FairyEngine? _debugEngine = null;
public NeoSystem system;
public ProtocolSettings settings;
public ulong? timestamp
{
get => engine.runtimeArgs.timestamp;
set
{
if (value == null)
{
engine.Register("System.Runtime.GetTime", typeof(FairyEngine).GetMethod(nameof(FairyEngine.GetTime))!, ApplicationEngine.System_Runtime_GetTime.Hash, 1 << 3, CallFlags.None);
engine.runtimeArgs.timestamp = null;
}
else
{
engine.runtimeArgs.timestamp = value;
engine.Register("System.Runtime.GetTime", typeof(FairyEngine).GetMethod(nameof(FairyEngine.GetFairyTime))!, ApplicationEngine.System_Runtime_GetTime.Hash, 1 << 3, CallFlags.None);
}
}
}
public BigInteger? designatedRandom
{
get => engine.runtimeArgs.designatedRandom;
set
{
if (value == null)
{
engine.Register("System.Runtime.GetRandom", typeof(FairyEngine).GetMethod(nameof(FairyEngine.GetRandom))!, ApplicationEngine.System_Runtime_GetRandom.Hash, 0, CallFlags.None);
engine.runtimeArgs.designatedRandom = null;
}
else
{
engine.runtimeArgs.designatedRandom = value;
engine.Register("System.Runtime.GetRandom", typeof(FairyEngine).GetMethod(nameof(FairyEngine.GetFairyRandom))!, ApplicationEngine.System_Runtime_GetRandom.Hash, 0, CallFlags.None);
}
}
}
public bool checkWitnessReturnTrue
{
get => engine.runtimeArgs.checkWitnessReturnTrue;
set
{
if (value == false)
{
engine.Register("System.Runtime.CheckWitness", typeof(FairyEngine).GetMethod(nameof(FairyEngine.CheckWitness))!, ApplicationEngine.System_Runtime_CheckWitness.Hash, 1 << 10, CallFlags.None);
engine.runtimeArgs.checkWitnessReturnTrue = value;
}
else
{
engine.runtimeArgs.checkWitnessReturnTrue = value;
engine.Register("System.Runtime.CheckWitness", typeof(FairyEngine).GetMethod(nameof(FairyEngine.CheckFairyWitness))!, ApplicationEngine.System_Runtime_CheckWitness.Hash, 1 << 10, CallFlags.None);
}
}
}
public void ResetServices()
{
engine.runtimeArgs = new(fairy.defaultFairyWallet);
engine.services = ApplicationEngine.Services.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
ResetExpiration();
}
public FairySession(Fairy fairy, DataCache? snapshot = null)
{
this.fairy = fairy;
system = fairy.system;
settings = fairy.system.Settings;
_engine = Fairy.FairyEngine.Run(new byte[] { 0x40 }, snapshot is null ? fairy.system.StoreView : snapshot, fairy, settings: fairy.system.Settings, gas: fairy.settings.MaxGasInvoke);
}
public void ResetExpiration()
{
StartTime = DateTime.UtcNow;
}
public new string ToString()
{
return $"hasDebugEngine: {debugEngine != null}\ttimestamp: {timestamp}";//\tdesignatedRandom: {designatedRandom}";
}
}
internal Timer? timer;
internal void InitializeTimer()
{
if (settings.SessionEnabled)
timer = new(OnTimer, null, settings.SessionExpirationTime.Milliseconds, 60000);
}
internal void OnTimer(object? state)
{
List<(string Id, FairySession Session)> toBeDestroyed = new();
foreach (var (id, session) in sessionStringToFairySession)
if (DateTime.UtcNow >= session.StartTime + settings.SessionExpirationTime)
toBeDestroyed.Add((id, session));
//Console.WriteLine(toBeDestroyed.Count);
foreach (var (id, _) in toBeDestroyed)
sessionStringToFairySession.Remove(id, out _);
JArray debugInfoToBeDeleted = new();
foreach (UInt160 k in this.contractScriptHashToSourceLineFilenames.Keys)
{
string? contractName = null;
foreach (string s in this.sessionStringToFairySession.Keys)
{
contractName = NativeContract.ContractManagement.GetContract(this.sessionStringToFairySession[s].engine.Snapshot, k)?.Manifest.Name;
if (contractName != null)
break;
}
if (contractName == null)
debugInfoToBeDeleted.Add(k.ToString());
}
//Console.WriteLine(debugInfoToBeDeleted.Count);
DeleteDebugInfo(debugInfoToBeDeleted);
}
}
}