This repository was archived by the owner on Dec 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 224
/
Copy pathMainService.cs
480 lines (425 loc) · 17.8 KB
/
MainService.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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
using Akka.Actor;
using Microsoft.Extensions.Configuration;
using Neo.ConsoleService;
using Neo.Cryptography.ECC;
using Neo.IO;
using Neo.IO.Json;
using Neo.Ledger;
using Neo.Network.P2P;
using Neo.Network.P2P.Payloads;
using Neo.Plugins;
using Neo.SmartContract;
using Neo.SmartContract.Manifest;
using Neo.VM;
using Neo.Wallets;
using Neo.Wallets.NEP6;
using Neo.Wallets.SQLite;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
namespace Neo.CLI
{
public partial class MainService : ConsoleServiceBase
{
public event EventHandler WalletChanged;
private Wallet currentWallet;
public Wallet CurrentWallet
{
get
{
return currentWallet;
}
private set
{
currentWallet = value;
WalletChanged?.Invoke(this, EventArgs.Empty);
}
}
private NeoSystem neoSystem;
public NeoSystem NeoSystem
{
get
{
return neoSystem;
}
private set
{
neoSystem = value;
}
}
protected override string Prompt => "neo";
public override string ServiceName => "NEO-CLI";
/// <summary>
/// Constructor
/// </summary>
public MainService() : base()
{
RegisterCommandHander<string, UInt160>(false, (str) =>
{
switch (str.ToLowerInvariant())
{
case "neo": return SmartContract.Native.NativeContract.NEO.Hash;
case "gas": return SmartContract.Native.NativeContract.GAS.Hash;
}
// Try to parse as UInt160
if (UInt160.TryParse(str, out var addr))
{
return addr;
}
// Accept wallet format
return str.ToScriptHash();
});
RegisterCommandHander<string, UInt256>(false, (str) => UInt256.Parse(str));
RegisterCommandHander<string[], UInt256[]>((str) => str.Select(u => UInt256.Parse(u.Trim())).ToArray());
RegisterCommandHander<string[], UInt160[]>((arr) =>
{
return arr.Select(str =>
{
switch (str.ToLowerInvariant())
{
case "neo": return SmartContract.Native.NativeContract.NEO.Hash;
case "gas": return SmartContract.Native.NativeContract.GAS.Hash;
}
// Try to parse as UInt160
if (UInt160.TryParse(str, out var addr))
{
return addr;
}
// Accept wallet format
return str.ToScriptHash();
})
.ToArray();
});
RegisterCommandHander<string[], ECPoint[]>((str) => str.Select(u => ECPoint.Parse(u.Trim(), ECCurve.Secp256r1)).ToArray());
RegisterCommandHander<string, JObject>((str) => JObject.Parse(str));
RegisterCommandHander<JObject, JArray>((obj) => (JArray)obj);
RegisterCommandHander<string[], AttachAsset[]>((str) => str.Select(u => AttachAsset.Parse(u)).ToArray());
RegisterCommand(this);
foreach (var plugin in Plugin.Plugins)
{
// Register plugins commands
RegisterCommand(plugin, plugin.Name);
}
}
public override void RunConsole()
{
Console.ForegroundColor = ConsoleColor.DarkGreen;
var cliV = Assembly.GetAssembly(typeof(Program)).GetVersion();
var neoV = Assembly.GetAssembly(typeof(NeoSystem)).GetVersion();
var vmV = Assembly.GetAssembly(typeof(ExecutionEngine)).GetVersion();
Console.WriteLine($"{ServiceName} v{cliV} - NEO v{neoV} - NEO-VM v{vmV}");
Console.WriteLine();
base.RunConsole();
}
public void CreateWallet(string path, string password)
{
switch (Path.GetExtension(path))
{
case ".db3":
{
UserWallet wallet = UserWallet.Create(path, password);
WalletAccount account = wallet.CreateAccount();
Console.WriteLine($"address: {account.Address}");
Console.WriteLine($" pubkey: {account.GetKey().PublicKey.EncodePoint(true).ToHexString()}");
CurrentWallet = wallet;
}
break;
case ".json":
{
NEP6Wallet wallet = new NEP6Wallet(path);
wallet.Unlock(password);
WalletAccount account = wallet.CreateAccount();
wallet.Save();
Console.WriteLine($"address: {account.Address}");
Console.WriteLine($" pubkey: {account.GetKey().PublicKey.EncodePoint(true).ToHexString()}");
CurrentWallet = wallet;
}
break;
default:
Console.WriteLine("Wallet files in that format are not supported, please use a .json or .db3 file extension.");
break;
}
}
private static IEnumerable<Block> GetBlocks(Stream stream, bool read_start = false)
{
using BinaryReader r = new BinaryReader(stream);
uint start = read_start ? r.ReadUInt32() : 0;
uint count = r.ReadUInt32();
uint end = start + count - 1;
if (end <= Blockchain.Singleton.Height) yield break;
for (uint height = start; height <= end; height++)
{
var size = r.ReadInt32();
if (size > Message.PayloadMaxSize)
throw new ArgumentException($"Block {height} exceeds the maximum allowed size");
byte[] array = r.ReadBytes(size);
if (height > Blockchain.Singleton.Height)
{
Block block = array.AsSerializable<Block>();
yield return block;
}
}
}
private IEnumerable<Block> GetBlocksFromFile()
{
const string pathAcc = "chain.acc";
if (File.Exists(pathAcc))
using (FileStream fs = new FileStream(pathAcc, FileMode.Open, FileAccess.Read, FileShare.Read))
foreach (var block in GetBlocks(fs))
yield return block;
const string pathAccZip = pathAcc + ".zip";
if (File.Exists(pathAccZip))
using (FileStream fs = new FileStream(pathAccZip, FileMode.Open, FileAccess.Read, FileShare.Read))
using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Read))
using (Stream zs = zip.GetEntry(pathAcc).Open())
foreach (var block in GetBlocks(zs))
yield return block;
var paths = Directory.EnumerateFiles(".", "chain.*.acc", SearchOption.TopDirectoryOnly).Concat(Directory.EnumerateFiles(".", "chain.*.acc.zip", SearchOption.TopDirectoryOnly)).Select(p => new
{
FileName = Path.GetFileName(p),
Start = uint.Parse(Regex.Match(p, @"\d+").Value),
IsCompressed = p.EndsWith(".zip")
}).OrderBy(p => p.Start);
foreach (var path in paths)
{
if (path.Start > Blockchain.Singleton.Height + 1) break;
if (path.IsCompressed)
using (FileStream fs = new FileStream(path.FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Read))
using (Stream zs = zip.GetEntry(Path.GetFileNameWithoutExtension(path.FileName)).Open())
foreach (var block in GetBlocks(zs, true))
yield return block;
else
using (FileStream fs = new FileStream(path.FileName, FileMode.Open, FileAccess.Read, FileShare.Read))
foreach (var block in GetBlocks(fs, true))
yield return block;
}
}
private bool NoWallet()
{
if (CurrentWallet != null) return false;
Console.WriteLine("You have to open the wallet first.");
return true;
}
private byte[] LoadDeploymentScript(string nefFilePath, string manifestFilePath, out UInt160 scriptHash)
{
if (string.IsNullOrEmpty(manifestFilePath))
{
manifestFilePath = Path.ChangeExtension(nefFilePath, ".manifest.json");
}
// Read manifest
var info = new FileInfo(manifestFilePath);
if (!info.Exists || info.Length >= Transaction.MaxTransactionSize)
{
throw new ArgumentException(nameof(manifestFilePath));
}
var manifest = ContractManifest.Parse(File.ReadAllText(manifestFilePath));
// Read nef
info = new FileInfo(nefFilePath);
if (!info.Exists || info.Length >= Transaction.MaxTransactionSize)
{
throw new ArgumentException(nameof(nefFilePath));
}
NefFile file;
using (var stream = new BinaryReader(File.OpenRead(nefFilePath), Encoding.UTF8, false))
{
file = stream.ReadSerializable<NefFile>();
}
// Basic script checks
using (var engine = new ApplicationEngine(TriggerType.Application, null, null, 0, true))
{
var context = engine.LoadScript(file.Script);
while (context.InstructionPointer <= context.Script.Length)
{
// Check bad opcodes
var ci = context.CurrentInstruction;
if (ci == null || !Enum.IsDefined(typeof(OpCode), ci.OpCode))
{
throw new FormatException($"OpCode not found at {context.InstructionPointer}-{((byte)ci.OpCode).ToString("x2")}");
}
switch (ci.OpCode)
{
case OpCode.SYSCALL:
{
// Check bad syscalls (NEO2)
if (!InteropService.SupportedMethods().Any(u => u.Hash == ci.TokenU32))
{
throw new FormatException($"Syscall not found {ci.TokenU32.ToString("x2")}. Are you using a NEO2 smartContract?");
}
break;
}
}
context.InstructionPointer += ci.Size;
}
}
// Build script
scriptHash = file.ScriptHash;
using (ScriptBuilder sb = new ScriptBuilder())
{
sb.EmitSysCall(InteropService.Contract.Create, file.Script, manifest.ToJson().ToString());
return sb.ToArray();
}
}
public override void OnStart(string[] args)
{
base.OnStart(args);
Start(args);
}
public override void OnStop()
{
base.OnStop();
Stop();
}
public void OpenWallet(string path, string password)
{
if (!File.Exists(path))
{
throw new FileNotFoundException();
}
if (Path.GetExtension(path) == ".db3")
{
CurrentWallet = UserWallet.Open(path, password);
}
else
{
NEP6Wallet nep6wallet = new NEP6Wallet(path);
nep6wallet.Unlock(password);
CurrentWallet = nep6wallet;
}
}
public async void Start(string[] args)
{
if (NeoSystem != null) return;
bool verifyImport = true;
for (int i = 0; i < args.Length; i++)
switch (args[i])
{
case "/noverify":
case "--noverify":
verifyImport = false;
break;
case "/testnet":
case "--testnet":
case "-t":
ProtocolSettings.Initialize(new ConfigurationBuilder().AddJsonFile("protocol.testnet.json").Build());
Settings.Initialize(new ConfigurationBuilder().AddJsonFile("config.testnet.json").Build());
break;
case "/mainnet":
case "--mainnet":
case "-m":
ProtocolSettings.Initialize(new ConfigurationBuilder().AddJsonFile("protocol.mainnet.json").Build());
Settings.Initialize(new ConfigurationBuilder().AddJsonFile("config.mainnet.json").Build());
break;
}
NeoSystem = new NeoSystem(Settings.Default.Storage.Engine);
using (IEnumerator<Block> blocksBeingImported = GetBlocksFromFile().GetEnumerator())
{
while (true)
{
List<Block> blocksToImport = new List<Block>();
for (int i = 0; i < 10; i++)
{
if (!blocksBeingImported.MoveNext()) break;
blocksToImport.Add(blocksBeingImported.Current);
}
if (blocksToImport.Count == 0) break;
await NeoSystem.Blockchain.Ask<Blockchain.ImportCompleted>(new Blockchain.Import
{
Blocks = blocksToImport,
Verify = verifyImport
});
if (NeoSystem is null) return;
}
}
NeoSystem.StartNode(new ChannelsConfig
{
Tcp = new IPEndPoint(IPAddress.Any, Settings.Default.P2P.Port),
WebSocket = new IPEndPoint(IPAddress.Any, Settings.Default.P2P.WsPort),
MinDesiredConnections = Settings.Default.P2P.MinDesiredConnections,
MaxConnections = Settings.Default.P2P.MaxConnections,
MaxConnectionsPerAddress = Settings.Default.P2P.MaxConnectionsPerAddress
});
if (Settings.Default.UnlockWallet.IsActive)
{
try
{
OpenWallet(Settings.Default.UnlockWallet.Path, Settings.Default.UnlockWallet.Password);
}
catch (FileNotFoundException)
{
Console.WriteLine($"Warning: wallet file \"{Settings.Default.UnlockWallet.Path}\" not found.");
}
catch (System.Security.Cryptography.CryptographicException)
{
Console.WriteLine($"failed to open file \"{Settings.Default.UnlockWallet.Path}\"");
}
if (Settings.Default.UnlockWallet.StartConsensus && CurrentWallet != null)
{
OnStartConsensusCommand();
}
}
}
public void Stop()
{
Interlocked.Exchange(ref neoSystem, null)?.Dispose();
}
private void WriteBlocks(uint start, uint count, string path, bool writeStart)
{
uint end = start + count - 1;
using FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, 4096, FileOptions.WriteThrough);
if (fs.Length > 0)
{
byte[] buffer = new byte[sizeof(uint)];
if (writeStart)
{
fs.Seek(sizeof(uint), SeekOrigin.Begin);
fs.Read(buffer, 0, buffer.Length);
start += BitConverter.ToUInt32(buffer, 0);
fs.Seek(sizeof(uint), SeekOrigin.Begin);
}
else
{
fs.Read(buffer, 0, buffer.Length);
start = BitConverter.ToUInt32(buffer, 0);
fs.Seek(0, SeekOrigin.Begin);
}
}
else
{
if (writeStart)
{
fs.Write(BitConverter.GetBytes(start), 0, sizeof(uint));
}
}
if (start <= end)
fs.Write(BitConverter.GetBytes(count), 0, sizeof(uint));
fs.Seek(0, SeekOrigin.End);
Console.WriteLine("Export block from " + start + " to " + end);
using (var percent = new ConsolePercent(start, end))
{
for (uint i = start; i <= end; i++)
{
Block block = Blockchain.Singleton.GetBlock(i);
byte[] array = block.ToArray();
fs.Write(BitConverter.GetBytes(array.Length), 0, sizeof(int));
fs.Write(array, 0, array.Length);
percent.Value = i;
}
}
}
private static void WriteLineWithoutFlicker(string message = "", int maxWidth = 80)
{
if (message.Length > 0) Console.Write(message);
var spacesToErase = maxWidth - message.Length;
if (spacesToErase < 0) spacesToErase = 0;
Console.WriteLine(new string(' ', spacesToErase));
}
}
}