-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathLogReader.cs
457 lines (392 loc) · 16.8 KB
/
LogReader.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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
// Copyright (C) 2015-2024 The Neo Project.
//
// LogReader.cs file belongs to the neo project and is free
// software distributed under the MIT software license, see the
// accompanying file LICENSE in the main directory of the
// repository or http://www.opensource.org/licenses/mit-license.php
// for more details.
//
// Redistribution and use in source and binary forms with or without
// modifications are permitted.
using ApplicationLogs.Store;
using ApplicationLogs.Store.Models;
using Neo.ConsoleService;
using Neo.IO;
using Neo.Json;
using Neo.Ledger;
using Neo.Network.P2P.Payloads;
using Neo.Persistence;
using Neo.SmartContract;
using Neo.SmartContract.Native;
using Neo.VM;
using System.Numerics;
using static System.IO.Path;
namespace Neo.Plugins
{
public class LogReader : Plugin
{
#region Globals
private NeoStore _neostore;
private NeoSystem _neosystem;
private readonly List<LogEventArgs> _logEvents;
#endregion
public override string Name => "ApplicationLogs";
public override string Description => "Synchronizes smart contract VM executions and notificatons (NotifyLog) on blockchain.";
#region Ctor
public LogReader()
{
_logEvents = new();
Blockchain.Committing += OnCommitting;
Blockchain.Committed += OnCommitted;
}
#endregion
#region Override Methods
public override void Dispose()
{
Blockchain.Committing -= OnCommitting;
Blockchain.Committed -= OnCommitted;
if (Settings.Default.Debug)
ApplicationEngine.Log -= OnApplicationEngineLog;
GC.SuppressFinalize(this);
}
protected override void Configure()
{
Settings.Load(GetConfiguration());
}
protected override void OnSystemLoaded(NeoSystem system)
{
if (system.Settings.Network != Settings.Default.Network)
return;
string path = string.Format(Settings.Default.Path, Settings.Default.Network.ToString("X8"));
var store = system.LoadStore(GetFullPath(path));
_neostore = new NeoStore(store);
_neosystem = system;
RpcServerPlugin.RegisterMethods(this, Settings.Default.Network);
if (Settings.Default.Debug)
ApplicationEngine.Log += OnApplicationEngineLog;
}
#endregion
#region JSON RPC Methods
[RpcMethod]
public JToken GetApplicationLog(JArray _params)
{
if (_params == null || _params.Count == 0)
throw new RpcException(RpcError.InvalidParams);
if (UInt256.TryParse(_params[0].AsString(), out var hash))
{
var raw = BlockToJObject(hash);
if (raw == null)
raw = TransactionToJObject(hash);
if (raw == null)
throw new RpcException(RpcError.InvalidParams.WithData("Unknown transaction/blockhash"));
if (_params.Count >= 2 && Enum.TryParse(_params[1].AsString(), true, out TriggerType triggerType))
{
var executions = raw["executions"] as JArray;
for (int i = 0; i < executions.Count;)
{
if (executions[i]["trigger"].AsString().Equals(triggerType.ToString(), StringComparison.OrdinalIgnoreCase) == false)
executions.RemoveAt(i);
else
i++;
}
}
return raw ?? JToken.Null;
}
else
throw new RpcException(RpcError.InvalidParams);
}
#endregion
#region Console Commands
[ConsoleCommand("log block", Category = "ApplicationLog Commands")]
private void OnGetBlockCommand(string blockHashOrIndex, string eventName = null)
{
UInt256 blockhash;
if (uint.TryParse(blockHashOrIndex, out var blockIndex))
{
blockhash = NativeContract.Ledger.GetBlockHash(_neosystem.StoreView, blockIndex);
}
else if (UInt256.TryParse(blockHashOrIndex, out blockhash) == false)
{
ConsoleHelper.Error("Invalid block hash or index.");
return;
}
var blockOnPersist = string.IsNullOrEmpty(eventName) ?
_neostore.GetBlockLog(blockhash, TriggerType.OnPersist) :
_neostore.GetBlockLog(blockhash, TriggerType.OnPersist, eventName);
var blockPostPersist = string.IsNullOrEmpty(eventName) ?
_neostore.GetBlockLog(blockhash, TriggerType.PostPersist) :
_neostore.GetBlockLog(blockhash, TriggerType.PostPersist, eventName);
if (blockOnPersist == null && blockOnPersist == null)
ConsoleHelper.Error($"No logs.");
if (blockOnPersist != null)
PrintExecutionToConsole(blockOnPersist);
if (blockPostPersist != null)
{
ConsoleHelper.Info("--------------------------------");
PrintExecutionToConsole(blockPostPersist);
}
}
[ConsoleCommand("log tx", Category = "ApplicationLog Commands")]
private void OnGetTransactionCommand(UInt256 txhash, string eventName = null)
{
var txApplication = string.IsNullOrEmpty(eventName) ?
_neostore.GetTransactionLog(txhash) :
_neostore.GetTransactionLog(txhash, eventName);
if (txApplication == null)
ConsoleHelper.Error($"No logs.");
else
PrintExecutionToConsole(txApplication);
}
[ConsoleCommand("log contract", Category = "ApplicationLog Commands")]
private void OnGetContractCommand(UInt160 scripthash, uint page = 1, uint pageSize = 1, string eventName = null)
{
if (page == 0)
{
ConsoleHelper.Error("Page is invalid. Pick a number 1 and above.");
return;
}
if (pageSize == 0)
{
ConsoleHelper.Error("PageSize is invalid. Pick a number between 1 and 10.");
return;
}
var txContract = string.IsNullOrEmpty(eventName) ?
_neostore.GetContractLog(scripthash, TriggerType.Application, page, pageSize) :
_neostore.GetContractLog(scripthash, TriggerType.Application, eventName, page, pageSize);
if (txContract.Count == 0)
ConsoleHelper.Error($"No logs.");
else
PrintEventModelToConsole(txContract);
}
#endregion
#region Blockchain Events
private void OnCommitting(NeoSystem system, Block block, DataCache snapshot, IReadOnlyList<Blockchain.ApplicationExecuted> applicationExecutedList)
{
if (system.Settings.Network != Settings.Default.Network)
return;
if (_neostore is null)
return;
_neostore.StartBlockLogBatch();
_neostore.PutBlockLog(block, applicationExecutedList);
if (Settings.Default.Debug)
{
foreach (var appEng in applicationExecutedList.Where(w => w.Transaction != null))
{
var logs = _logEvents.Where(w => w.ScriptContainer.Hash == appEng.Transaction.Hash).ToList();
if (logs.Any())
_neostore.PutTransactionEngineLogState(appEng.Transaction.Hash, logs);
}
_logEvents.Clear();
}
}
private void OnCommitted(NeoSystem system, Block block)
{
if (system.Settings.Network != Settings.Default.Network)
return;
if (_neostore is null)
return;
_neostore.CommitBlockLog();
}
private void OnApplicationEngineLog(object sender, LogEventArgs e)
{
if (Settings.Default.Debug == false)
return;
if (_neosystem.Settings.Network != Settings.Default.Network)
return;
if (e.ScriptContainer == null)
return;
_logEvents.Add(e);
}
#endregion
#region Private Methods
private void PrintExecutionToConsole(BlockchainExecutionModel model)
{
ConsoleHelper.Info("Trigger: ", $"{model.Trigger}");
ConsoleHelper.Info("VM State: ", $"{model.VmState}");
if (string.IsNullOrEmpty(model.Exception) == false)
ConsoleHelper.Error($"Exception: {model.Exception}");
else
ConsoleHelper.Info("Exception: ", "null");
ConsoleHelper.Info("Gas Consumed: ", $"{new BigDecimal((BigInteger)model.GasConsumed, NativeContract.GAS.Decimals)}");
if (model.Stack.Length == 0)
ConsoleHelper.Info("Stack: ", "[]");
else
{
ConsoleHelper.Info("Stack: ");
for (int i = 0; i < model.Stack.Length; i++)
ConsoleHelper.Info($" {i}: ", $"{model.Stack[i].ToJson()}");
}
if (model.Notifications.Length == 0)
ConsoleHelper.Info("Notifications: ", "[]");
else
{
ConsoleHelper.Info("Notifications:");
foreach (var notifyItem in model.Notifications)
{
ConsoleHelper.Info();
ConsoleHelper.Info(" ScriptHash: ", $"{notifyItem.ScriptHash}");
ConsoleHelper.Info(" Event Name: ", $"{notifyItem.EventName}");
ConsoleHelper.Info(" State Parameters:");
for (int i = 0; i < notifyItem.State.Length; i++)
ConsoleHelper.Info($" {GetMethodParameterName(notifyItem.ScriptHash, notifyItem.EventName, i)}: ", $"{notifyItem.State[i].ToJson()}");
}
}
if (Settings.Default.Debug)
{
if (model.Logs.Length == 0)
ConsoleHelper.Info("Logs: ", "[]");
else
{
ConsoleHelper.Info("Logs:");
foreach (var logItem in model.Logs)
{
ConsoleHelper.Info();
ConsoleHelper.Info(" ScriptHash: ", $"{logItem.ScriptHash}");
ConsoleHelper.Info(" Message: ", $"{logItem.Message}");
}
}
}
}
private void PrintEventModelToConsole(IReadOnlyCollection<(BlockchainEventModel NotifyLog, UInt256 TxHash)> models)
{
foreach (var (notifyItem, txhash) in models)
{
ConsoleHelper.Info("Transaction Hash: ", $"{txhash}");
ConsoleHelper.Info();
ConsoleHelper.Info(" Event Name: ", $"{notifyItem.EventName}");
ConsoleHelper.Info(" State Parameters:");
for (int i = 0; i < notifyItem.State.Length; i++)
ConsoleHelper.Info($" {GetMethodParameterName(notifyItem.ScriptHash, notifyItem.EventName, i)}: ", $"{notifyItem.State[i].ToJson()}");
ConsoleHelper.Info("--------------------------------");
}
}
private string GetMethodParameterName(UInt160 scriptHash, string methodName, int parameterIndex)
{
var contract = NativeContract.ContractManagement.GetContract(_neosystem.StoreView, scriptHash);
if (contract == null)
return $"{parameterIndex}";
var contractEvent = contract.Manifest.Abi.Events.SingleOrDefault(s => s.Name == methodName);
return contractEvent.Parameters[parameterIndex].Name;
}
private JObject EventModelToJObject(BlockchainEventModel model)
{
var root = new JObject();
root["contract"] = model.ScriptHash.ToString();
root["eventname"] = model.EventName;
root["state"] = model.State.Select(s => s.ToJson()).ToArray();
return root;
}
private JObject TransactionToJObject(UInt256 txHash)
{
var appLog = _neostore.GetTransactionLog(txHash);
if (appLog == null)
return null;
var raw = new JObject();
raw["txid"] = txHash.ToString();
var trigger = new JObject();
trigger["trigger"] = appLog.Trigger;
trigger["vmstate"] = appLog.VmState;
trigger["exception"] = string.IsNullOrEmpty(appLog.Exception) ? null : appLog.Exception;
trigger["gasconsumed"] = appLog.GasConsumed.ToString();
try
{
trigger["stack"] = appLog.Stack.Select(s => s.ToJson(Settings.Default.MaxStackSize)).ToArray();
}
catch (Exception ex)
{
trigger["exception"] = ex.Message;
}
trigger["notifications"] = appLog.Notifications.Select(s =>
{
var notification = new JObject();
notification["contract"] = s.ScriptHash.ToString();
notification["eventname"] = s.EventName;
try
{
var state = new JObject();
state["type"] = "Array";
state["value"] = s.State.Select(ss => ss.ToJson()).ToArray();
notification["state"] = state;
}
catch (InvalidOperationException)
{
notification["state"] = "error: recursive reference";
}
return notification;
}).ToArray();
if (Settings.Default.Debug)
{
trigger["logs"] = appLog.Logs.Select(s =>
{
var log = new JObject();
log["contract"] = s.ScriptHash.ToString();
log["message"] = s.Message;
return log;
}).ToArray();
}
raw["executions"] = new[] { trigger };
return raw;
}
private JObject BlockToJObject(UInt256 blockHash)
{
var blockOnPersist = _neostore.GetBlockLog(blockHash, TriggerType.OnPersist);
var blockPostPersist = _neostore.GetBlockLog(blockHash, TriggerType.PostPersist);
if (blockOnPersist == null && blockPostPersist == null)
return null;
var blockJson = new JObject();
blockJson["blockhash"] = blockHash.ToString();
var triggerList = new List<JObject>();
if (blockOnPersist != null)
triggerList.Add(BlockItemToJObject(blockOnPersist));
if (blockPostPersist != null)
triggerList.Add(BlockItemToJObject(blockPostPersist));
blockJson["executions"] = triggerList.ToArray();
return blockJson;
}
private JObject BlockItemToJObject(BlockchainExecutionModel blockExecutionModel)
{
JObject trigger = new();
trigger["trigger"] = blockExecutionModel.Trigger;
trigger["vmstate"] = blockExecutionModel.VmState;
trigger["gasconsumed"] = blockExecutionModel.GasConsumed.ToString();
try
{
trigger["stack"] = blockExecutionModel.Stack.Select(q => q.ToJson(Settings.Default.MaxStackSize)).ToArray();
}
catch (Exception ex)
{
trigger["exception"] = ex.Message;
}
trigger["notifications"] = blockExecutionModel.Notifications.Select(s =>
{
JObject notification = new();
notification["contract"] = s.ScriptHash.ToString();
notification["eventname"] = s.EventName;
try
{
var state = new JObject();
state["type"] = "Array";
state["value"] = s.State.Select(ss => ss.ToJson()).ToArray();
notification["state"] = state;
}
catch (InvalidOperationException)
{
notification["state"] = "error: recursive reference";
}
return notification;
}).ToArray();
if (Settings.Default.Debug)
{
trigger["logs"] = blockExecutionModel.Logs.Select(s =>
{
var log = new JObject();
log["contract"] = s.ScriptHash.ToString();
log["message"] = s.Message;
return log;
}).ToArray();
}
return trigger;
}
#endregion
}
}