From d1bc7d1ca9f5100dba7c08af19e02a2b7012ebb9 Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Thu, 10 Feb 2022 12:51:01 +0300 Subject: [PATCH 01/65] neo-cli: tune MaxTransactionsPerBlock for testnet (#850) Allow to flush the mempool in just 10 blocks. --- neo-cli/config.testnet.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/neo-cli/config.testnet.json b/neo-cli/config.testnet.json index f151c2625..94ad1d7b0 100644 --- a/neo-cli/config.testnet.json +++ b/neo-cli/config.testnet.json @@ -26,7 +26,7 @@ "Network": 877933390, "AddressVersion": 53, "MillisecondsPerBlock": 15000, - "MaxTransactionsPerBlock": 512, + "MaxTransactionsPerBlock": 5000, "MemoryPoolMaxTransactions": 50000, "MaxTraceableBlocks": 2102400, "InitialGasDistribution": 5200000000000000, From 35269f63f56cc17a2fabc06060ea5c847db72b3e Mon Sep 17 00:00:00 2001 From: superboyiii <573504781@qq.com> Date: Mon, 28 Mar 2022 14:54:03 +0800 Subject: [PATCH 02/65] set new network id for testnet --- neo-cli/config.testnet.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/neo-cli/config.testnet.json b/neo-cli/config.testnet.json index 94ad1d7b0..2eb691fe8 100644 --- a/neo-cli/config.testnet.json +++ b/neo-cli/config.testnet.json @@ -23,7 +23,7 @@ } }, "ProtocolConfiguration": { - "Network": 877933390, + "Network": 894710606, "AddressVersion": 53, "MillisecondsPerBlock": 15000, "MaxTransactionsPerBlock": 5000, From 51b5514535ab3bcac8400eec94bd48f413012355 Mon Sep 17 00:00:00 2001 From: superboyiii <573504781@qq.com> Date: Mon, 28 Mar 2022 14:55:31 +0800 Subject: [PATCH 03/65] revert --- neo-cli/config.testnet.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/neo-cli/config.testnet.json b/neo-cli/config.testnet.json index 2eb691fe8..94ad1d7b0 100644 --- a/neo-cli/config.testnet.json +++ b/neo-cli/config.testnet.json @@ -23,7 +23,7 @@ } }, "ProtocolConfiguration": { - "Network": 894710606, + "Network": 877933390, "AddressVersion": 53, "MillisecondsPerBlock": 15000, "MaxTransactionsPerBlock": 5000, From 2ad44ef46f82582ffb93685bc3867f5d7640e44c Mon Sep 17 00:00:00 2001 From: Owen Zhang <38493437+superboyiii@users.noreply.github.com> Date: Tue, 29 Mar 2022 21:49:05 +0800 Subject: [PATCH 04/65] Add new testnet network id (#852) --- neo-cli/config.testnet.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/neo-cli/config.testnet.json b/neo-cli/config.testnet.json index 94ad1d7b0..2eb691fe8 100644 --- a/neo-cli/config.testnet.json +++ b/neo-cli/config.testnet.json @@ -23,7 +23,7 @@ } }, "ProtocolConfiguration": { - "Network": 877933390, + "Network": 894710606, "AddressVersion": 53, "MillisecondsPerBlock": 15000, "MaxTransactionsPerBlock": 5000, From ab5447d3444e2a8ceb88623fd925a274ef924223 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 31 Mar 2022 02:16:54 -0700 Subject: [PATCH 05/65] typo, comment (#847) * typo, comment, code optimization. * optimise code * Update ConsoleColorSet.cs * Update ConsoleColorSet.cs * revert all visiblities * revert change to visibility * remove null check and optimise code * remove null check * Revert some changes * Revert some changes * revert recursion * revert unnessary optimise * revert unnecessary optimise * revert almost all changes that has nothing to do witht typo * revert if statement changes * revert more unnesary optimise code * revert change to using packages order * revert change in wallet * Update neo-cli/CLI/MainService.Contracts.cs Co-authored-by: Shargon * Update neo-cli/CLI/MainService.Contracts.cs Co-authored-by: Shargon * Update Neo.ConsoleService/ConsoleServiceBase.cs * Update MainService.Node.cs * Update MainService.Node.cs * Update Logger.cs * remove default * remove static * remove static * remove token.cancel * Update MainService.Node.cs * Update MainService.Tools.cs Co-authored-by: Erik Zhang Co-authored-by: Shargon --- Neo.ConsoleService/CommandToken.cs | 4 +- Neo.ConsoleService/ConsoleCommandMethod.cs | 2 +- Neo.ConsoleService/ConsoleServiceBase.cs | 74 +++++++++------------- Neo.ConsoleService/ServiceProxy.cs | 8 +-- neo-cli/CLI/ConsolePercent.cs | 9 +-- neo-cli/CLI/MainService.Contracts.cs | 17 +++-- neo-cli/CLI/MainService.NEP17.cs | 18 ++++-- neo-cli/CLI/MainService.Plugins.cs | 10 +-- neo-cli/CLI/MainService.Tools.cs | 18 +----- neo-cli/CLI/MainService.Vote.cs | 14 ++-- neo-cli/CLI/MainService.Wallet.cs | 16 ++--- neo-cli/CLI/MainService.cs | 57 +++++++---------- 12 files changed, 109 insertions(+), 138 deletions(-) diff --git a/Neo.ConsoleService/CommandToken.cs b/Neo.ConsoleService/CommandToken.cs index fedb601b2..f3bf1fa64 100644 --- a/Neo.ConsoleService/CommandToken.cs +++ b/Neo.ConsoleService/CommandToken.cs @@ -29,7 +29,7 @@ internal abstract class CommandToken /// /// Value /// - public string Value { get; protected set; } + public string Value { get; protected init; } /// /// Constructor @@ -152,7 +152,7 @@ public static void Trim(List args) // Trim end - while (args.Count > 0 && args[args.Count - 1].Type == CommandTokenType.Space) + while (args.Count > 0 && args[^1].Type == CommandTokenType.Space) { args.RemoveAt(args.Count - 1); } diff --git a/Neo.ConsoleService/ConsoleCommandMethod.cs b/Neo.ConsoleService/ConsoleCommandMethod.cs index d0949a68f..df241ce5f 100644 --- a/Neo.ConsoleService/ConsoleCommandMethod.cs +++ b/Neo.ConsoleService/ConsoleCommandMethod.cs @@ -52,7 +52,7 @@ internal class ConsoleCommandMethod /// /// Instance /// Method - /// Verbs + /// Attribute public ConsoleCommandMethod(object instance, MethodInfo method, ConsoleCommandAttribute attribute) { Method = method; diff --git a/Neo.ConsoleService/ConsoleServiceBase.cs b/Neo.ConsoleService/ConsoleServiceBase.cs index bffa0ef7d..cb62382ba 100644 --- a/Neo.ConsoleService/ConsoleServiceBase.cs +++ b/Neo.ConsoleService/ConsoleServiceBase.cs @@ -35,11 +35,11 @@ public abstract class ConsoleServiceBase public bool ReadingPassword { get; set; } = false; private bool _running; - private readonly CancellationTokenSource _shutdownTokenSource = new CancellationTokenSource(); - private readonly CountdownEvent _shutdownAcknowledged = new CountdownEvent(1); - private readonly Dictionary> _verbs = new Dictionary>(); - private readonly Dictionary _instances = new Dictionary(); - private readonly Dictionary, bool, object>> _handlers = new Dictionary, bool, object>>(); + private readonly CancellationTokenSource _shutdownTokenSource = new(); + private readonly CountdownEvent _shutdownAcknowledged = new(1); + private readonly Dictionary> _verbs = new(); + private readonly Dictionary _instances = new(); + private readonly Dictionary, bool, object>> _handlers = new(); private bool OnCommand(string commandLine) { @@ -188,10 +188,10 @@ protected void OnHelpCommand(string key) withHelp.Sort((a, b) => { - var cate = a.HelpCategory.CompareTo(b.HelpCategory); + var cate = string.Compare(a.HelpCategory, b.HelpCategory, StringComparison.Ordinal); if (cate == 0) { - cate = a.Key.CompareTo(b.Key); + cate = string.Compare(a.Key, b.Key, StringComparison.Ordinal); } return cate; }); @@ -234,7 +234,7 @@ protected void OnHelpCommand(string key) if (lastKey != command.Key) { - Console.WriteLine($"You can call this command like this:"); + Console.WriteLine("You can call this command like this:"); lastKey = command.Key; } @@ -247,7 +247,7 @@ protected void OnHelpCommand(string key) if (!found) { - throw new ArgumentException($"Command not found."); + throw new ArgumentException("Command not found."); } } } @@ -297,8 +297,7 @@ public virtual void OnStop() public string ReadUserInput(string prompt, bool password = false) { const string t = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; - StringBuilder sb = new StringBuilder(); - ConsoleKeyInfo key; + var sb = new StringBuilder(); if (!string.IsNullOrEmpty(prompt)) { @@ -316,6 +315,7 @@ public string ReadUserInput(string prompt, bool password = false) } else { + ConsoleKeyInfo key; do { key = Console.ReadKey(true); @@ -323,14 +323,7 @@ public string ReadUserInput(string prompt, bool password = false) if (t.IndexOf(key.KeyChar) != -1) { sb.Append(key.KeyChar); - if (password) - { - Console.Write('*'); - } - else - { - Console.Write(key.KeyChar); - } + Console.Write(password ? '*' : key.KeyChar); } else if (key.Key == ConsoleKey.Backspace && sb.Length > 0) { @@ -411,30 +404,25 @@ protected ConsoleServiceBase() { // Register self commands - RegisterCommandHander((args, canConsumeAll) => - { - return CommandToken.ReadString(args, canConsumeAll); - }); + RegisterCommandHandler(CommandToken.ReadString); - RegisterCommandHander((args, canConsumeAll) => + RegisterCommandHandler((args, canConsumeAll) => { if (canConsumeAll) { var ret = CommandToken.ToString(args); args.Clear(); - return ret.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); - } - else - { - return CommandToken.ReadString(args, false).Split(',', ' '); + return ret.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); } + + return CommandToken.ReadString(args, false).Split(',', ' '); }); - RegisterCommandHander(false, (str) => byte.Parse(str)); - RegisterCommandHander(false, (str) => str == "1" || str == "yes" || str == "y" || bool.Parse(str)); - RegisterCommandHander(false, (str) => ushort.Parse(str)); - RegisterCommandHander(false, (str) => uint.Parse(str)); - RegisterCommandHander(false, (str) => IPAddress.Parse(str)); + RegisterCommandHandler(false, str => byte.Parse(str)); + RegisterCommandHandler(false, str => str == "1" || str == "yes" || str == "y" || bool.Parse(str)); + RegisterCommandHandler(false, str => ushort.Parse(str)); + RegisterCommandHandler(false, str => uint.Parse(str)); + RegisterCommandHandler(false, IPAddress.Parse); } /// @@ -442,7 +430,7 @@ protected ConsoleServiceBase() /// /// Return type /// Handler - private void RegisterCommandHander(Func, bool, object> handler) + private void RegisterCommandHandler(Func, bool, object> handler) { _handlers[typeof(TRet)] = handler; } @@ -454,9 +442,9 @@ private void RegisterCommandHander(Func, bool, object> /// Return type /// Can consume all /// Handler - public void RegisterCommandHander(bool canConsumeAll, Func handler) + public void RegisterCommandHandler(bool canConsumeAll, Func handler) { - _handlers[typeof(TRet)] = (args, cosumeAll) => + _handlers[typeof(TRet)] = (args, _) => { var value = (T)_handlers[typeof(T)](args, canConsumeAll); return handler(value); @@ -469,11 +457,11 @@ public void RegisterCommandHander(bool canConsumeAll, Func h /// Base type /// Return type /// Handler - public void RegisterCommandHander(Func handler) + public void RegisterCommandHandler(Func handler) { - _handlers[typeof(TRet)] = (args, cosumeAll) => + _handlers[typeof(TRet)] = (args, consumeAll) => { - var value = (T)_handlers[typeof(T)](args, cosumeAll); + var value = (T)_handlers[typeof(T)](args, consumeAll); return handler(value); }; } @@ -498,7 +486,7 @@ public void RegisterCommand(object instance, string name = null) if (!method.GetParameters().All(u => u.ParameterType.IsEnum || _handlers.ContainsKey(u.ParameterType))) { - throw new ArgumentException("Handler not found for the command: " + method.ToString()); + throw new ArgumentException("Handler not found for the command: " + method); } // Add command @@ -576,7 +564,7 @@ public void Run(string[] args) protected string ReadLine() { - Task readLineTask = Task.Run(() => Console.ReadLine()); + Task readLineTask = Task.Run(Console.ReadLine); try { @@ -623,7 +611,7 @@ public virtual void RunConsole() ConsoleHelper.Error("Command not found"); } } - catch (TargetInvocationException ex) + catch (TargetInvocationException ex) when (ex.InnerException is not null) { ConsoleHelper.Error(ex.InnerException.Message); } diff --git a/Neo.ConsoleService/ServiceProxy.cs b/Neo.ConsoleService/ServiceProxy.cs index a6fac7ebd..e3a8a982f 100644 --- a/Neo.ConsoleService/ServiceProxy.cs +++ b/Neo.ConsoleService/ServiceProxy.cs @@ -14,21 +14,21 @@ namespace Neo.ConsoleService { internal class ServiceProxy : ServiceBase { - private readonly ConsoleServiceBase service; + private readonly ConsoleServiceBase _service; public ServiceProxy(ConsoleServiceBase service) { - this.service = service; + this._service = service; } protected override void OnStart(string[] args) { - service.OnStart(args); + _service.OnStart(args); } protected override void OnStop() { - service.OnStop(); + _service.OnStop(); } } } diff --git a/neo-cli/CLI/ConsolePercent.cs b/neo-cli/CLI/ConsolePercent.cs index cd9f36f15..364e67221 100644 --- a/neo-cli/CLI/ConsolePercent.cs +++ b/neo-cli/CLI/ConsolePercent.cs @@ -16,7 +16,8 @@ public class ConsolePercent : IDisposable { #region Variables - private long _maxValue, _value; + private readonly long _maxValue; + private long _value; private decimal _lastFactor; private string _lastPercent; @@ -33,7 +34,7 @@ public class ConsolePercent : IDisposable /// public long Value { - get { return _value; } + get => _value; set { if (value == _value) return; @@ -48,8 +49,8 @@ public long Value /// public long MaxValue { - get { return _maxValue; } - set + get => _maxValue; + init { if (value == _maxValue) return; diff --git a/neo-cli/CLI/MainService.Contracts.cs b/neo-cli/CLI/MainService.Contracts.cs index 1a32e3f5c..74ac577e6 100644 --- a/neo-cli/CLI/MainService.Contracts.cs +++ b/neo-cli/CLI/MainService.Contracts.cs @@ -26,6 +26,7 @@ partial class MainService /// /// File path /// Manifest path + /// Extra data for deploy [ConsoleCommand("deploy", Category = "Contract Commands")] private void OnDeployCommand(string filePath, string manifestPath = null, JObject data = null) { @@ -57,8 +58,12 @@ private void OnDeployCommand(string filePath, string manifestPath = null, JObjec /// /// Process "update" command /// + /// Script hash /// File path /// Manifest path + /// Sender + /// Signer Accounts + /// Extra data for update [ConsoleCommand("update", Category = "Contract Commands")] private void OnUpdateCommand(UInt160 scriptHash, string filePath, string manifestPath, UInt160 sender, UInt160[] signerAccounts = null, JObject data = null) { @@ -68,7 +73,7 @@ private void OnUpdateCommand(UInt160 scriptHash, string filePath, string manifes if (sender != null) { if (signerAccounts == null) - signerAccounts = new UInt160[1] { sender }; + signerAccounts = new[] { sender }; else if (signerAccounts.Contains(sender) && signerAccounts[0] != sender) { var signersList = signerAccounts.ToList(); @@ -82,13 +87,7 @@ private void OnUpdateCommand(UInt160 scriptHash, string filePath, string manifes signers = signerAccounts.Select(p => new Signer() { Account = p, Scopes = WitnessScope.CalledByEntry }).ToArray(); } - Transaction tx = new Transaction - { - Signers = signers, - Attributes = Array.Empty(), - Witnesses = Array.Empty() - }; - + Transaction tx; try { byte[] script = LoadUpdateScript(scriptHash, filePath, manifestPath, data, out var nef, out var manifest); @@ -127,7 +126,7 @@ private void OnUpdateCommand(UInt160 scriptHash, string filePath, string manifes /// Contract parameters /// Transaction's sender /// Signer's accounts - /// Max fee for running the script + /// Max fee for running the script [ConsoleCommand("invoke", Category = "Contract Commands")] private void OnInvokeCommand(UInt160 scriptHash, string operation, JArray contractParameters = null, UInt160 sender = null, UInt160[] signerAccounts = null, decimal maxGas = 20) { diff --git a/neo-cli/CLI/MainService.NEP17.cs b/neo-cli/CLI/MainService.NEP17.cs index 8cce43dbf..ff06974bf 100644 --- a/neo-cli/CLI/MainService.NEP17.cs +++ b/neo-cli/CLI/MainService.NEP17.cs @@ -16,7 +16,9 @@ using Neo.VM.Types; using Neo.Wallets; using System; +using System.Collections.Generic; using System.Linq; +using Array = System.Array; namespace Neo.CLI { @@ -27,7 +29,7 @@ partial class MainService /// /// Script hash /// To - /// Ammount + /// Amount /// From /// Data /// Signer's accounts @@ -58,7 +60,7 @@ private void OnTransferCommand(UInt160 tokenHash, UInt160 to, decimal amount, UI Scopes = WitnessScope.CalledByEntry, Account = p }) - .ToArray() ?? new Signer[0]); + .ToArray() ?? Array.Empty()); } catch (InvalidOperationException e) { @@ -80,9 +82,11 @@ private void OnTransferCommand(UInt160 tokenHash, UInt160 to, decimal amount, UI [ConsoleCommand("balanceOf", Category = "NEP17 Commands")] private void OnBalanceOfCommand(UInt160 tokenHash, UInt160 address) { - var arg = new JObject(); - arg["type"] = "Hash160"; - arg["value"] = address.ToString(); + var arg = new JObject + { + ["type"] = "Hash160", + ["value"] = address.ToString() + }; var asset = new AssetDescriptor(NeoSystem.StoreView, NeoSystem.Settings, tokenHash); @@ -113,7 +117,7 @@ private void OnNameCommand(UInt160 tokenHash) [ConsoleCommand("decimals", Category = "NEP17 Commands")] private void OnDecimalsCommand(UInt160 tokenHash) { - if (!OnInvokeWithResult(tokenHash, "decimals", out StackItem result, null)) return; + if (!OnInvokeWithResult(tokenHash, "decimals", out StackItem result)) return; ConsoleHelper.Info("Result: ", $"{((PrimitiveType)result).GetInteger()}"); } @@ -125,7 +129,7 @@ private void OnDecimalsCommand(UInt160 tokenHash) [ConsoleCommand("totalSupply", Category = "NEP17 Commands")] private void OnTotalSupplyCommand(UInt160 tokenHash) { - if (!OnInvokeWithResult(tokenHash, "totalSupply", out StackItem result, null)) return; + if (!OnInvokeWithResult(tokenHash, "totalSupply", out StackItem result)) return; var asset = new AssetDescriptor(NeoSystem.StoreView, NeoSystem.Settings, tokenHash); var totalSupply = new BigDecimal(((PrimitiveType)result).GetInteger(), asset.Decimals); diff --git a/neo-cli/CLI/MainService.Plugins.cs b/neo-cli/CLI/MainService.Plugins.cs index f61117682..682213327 100644 --- a/neo-cli/CLI/MainService.Plugins.cs +++ b/neo-cli/CLI/MainService.Plugins.cs @@ -35,11 +35,11 @@ private async Task OnInstallCommandAsync(string pluginName) if (response.StatusCode == HttpStatusCode.NotFound) { response.Dispose(); - Version version_core = typeof(Plugin).Assembly.GetName().Version; + Version versionCore = typeof(Plugin).Assembly.GetName().Version; HttpRequestMessage request = new(HttpMethod.Get, "https://api.github.com/repos/neo-project/neo-modules/releases"); request.Headers.UserAgent.ParseAdd($"{GetType().Assembly.GetName().Name}/{GetType().Assembly.GetVersion()}"); - using HttpResponseMessage response_api = await http.SendAsync(request); - byte[] buffer = await response_api.Content.ReadAsByteArrayAsync(); + using HttpResponseMessage responseApi = await http.SendAsync(request); + byte[] buffer = await responseApi.Content.ReadAsByteArrayAsync(); JObject releases = JObject.Parse(buffer); JObject asset = releases.GetArray() .Where(p => !p["tag_name"].GetString().Contains('-')) @@ -49,14 +49,14 @@ private async Task OnInstallCommandAsync(string pluginName) Assets = p["assets"].GetArray() }) .OrderByDescending(p => p.Version) - .First(p => p.Version <= version_core).Assets + .First(p => p.Version <= versionCore).Assets .FirstOrDefault(p => p["name"].GetString() == $"{pluginName}.zip"); if (asset is null) throw new Exception("Plugin doesn't exist."); response = await http.GetAsync(asset["browser_download_url"].GetString()); } using (response) { - using Stream stream = await response.Content.ReadAsStreamAsync(); + await using Stream stream = await response.Content.ReadAsStreamAsync(); using ZipArchive zip = new(stream, ZipArchiveMode.Read); try { diff --git a/neo-cli/CLI/MainService.Tools.cs b/neo-cli/CLI/MainService.Tools.cs index 05d6df487..f5be9a648 100644 --- a/neo-cli/CLI/MainService.Tools.cs +++ b/neo-cli/CLI/MainService.Tools.cs @@ -80,13 +80,7 @@ private string HexToString(string hexString) var clearHexString = ClearHexString(hexString); var bytes = clearHexString.HexToBytes(); var utf8String = Utility.StrictUTF8.GetString(bytes); - - if (!IsPrintable(utf8String)) - { - return null; - } - - return utf8String; + return IsPrintable(utf8String) ? utf8String : null; } catch { @@ -416,14 +410,8 @@ private string Base64ToString(string bytearray) try { byte[] result = Convert.FromBase64String(bytearray); - string utf8string = Utility.StrictUTF8.GetString(result); - - if (!IsPrintable(utf8string)) - { - return null; - } - - return utf8string; + string utf8String = Utility.StrictUTF8.GetString(result); + return IsPrintable(utf8String) ? utf8String : null; } catch { diff --git a/neo-cli/CLI/MainService.Vote.cs b/neo-cli/CLI/MainService.Vote.cs index b8ffdb988..da9be9953 100644 --- a/neo-cli/CLI/MainService.Vote.cs +++ b/neo-cli/CLI/MainService.Vote.cs @@ -17,6 +17,7 @@ using Neo.VM.Types; using Neo.Wallets; using System; +using System.Linq; using System.Numerics; namespace Neo.CLI @@ -27,7 +28,6 @@ partial class MainService /// Process "register candidate" command /// /// register account scriptHash - /// Max fee for running the script [ConsoleCommand("register candidate", Category = "Vote Commands")] private void OnRegisterCandidateCommand(UInt160 account) { @@ -49,7 +49,7 @@ private void OnRegisterCandidateCommand(UInt160 account) } } - ECPoint publicKey = currentAccount?.GetKey()?.PublicKey; + ECPoint publicKey = currentAccount.GetKey()?.PublicKey; byte[] script; using (ScriptBuilder scriptBuilder = new ScriptBuilder()) { @@ -63,7 +63,7 @@ private void OnRegisterCandidateCommand(UInt160 account) /// /// Process "unregister candidate" command /// - /// unregister account scriptHash + /// unregister account scriptHash [ConsoleCommand("unregister candidate", Category = "Vote Commands")] private void OnUnregisterCandidateCommand(UInt160 account) { @@ -208,9 +208,11 @@ private void OnGetNextBlockValidatorsCommand() private void OnGetAccountState(UInt160 address) { string notice = "No vote record!"; - var arg = new JObject(); - arg["type"] = "Hash160"; - arg["value"] = address.ToString(); + var arg = new JObject + { + ["type"] = "Hash160", + ["value"] = address.ToString() + }; if (!OnInvokeWithResult(NativeContract.NEO.Hash, "getAccountState", out StackItem result, null, new JArray(arg))) return; Console.WriteLine(); diff --git a/neo-cli/CLI/MainService.Wallet.cs b/neo-cli/CLI/MainService.Wallet.cs index 0db3eb313..f56a759ff 100644 --- a/neo-cli/CLI/MainService.Wallet.cs +++ b/neo-cli/CLI/MainService.Wallet.cs @@ -90,14 +90,14 @@ private void OnUpgradeWalletCommand(string path) ConsoleHelper.Info("Cancelled"); return; } - string path_new = Path.ChangeExtension(path, ".json"); - if (File.Exists(path_new)) + string pathNew = Path.ChangeExtension(path, ".json"); + if (File.Exists(pathNew)) { - ConsoleHelper.Warning($"File '{path_new}' already exists"); + ConsoleHelper.Warning($"File '{pathNew}' already exists"); return; } - NEP6Wallet.Migrate(path_new, path, password, NeoSystem.Settings).Save(); - Console.WriteLine($"Wallet file upgrade complete. New wallet file has been auto-saved at: {path_new}"); + NEP6Wallet.Migrate(pathNew, path, password, NeoSystem.Settings).Save(); + Console.WriteLine($"Wallet file upgrade complete. New wallet file has been auto-saved at: {pathNew}"); } /// @@ -252,7 +252,7 @@ private void OnImportMultisigAddress(ushort m, ECPoint[] publicKeys) Contract multiSignContract = Contract.CreateMultiSigContract(m, publicKeys); KeyPair keyPair = CurrentWallet.GetAccounts().FirstOrDefault(p => p.HasKey && publicKeys.Contains(p.GetKey().PublicKey))?.GetKey(); - WalletAccount account = CurrentWallet.CreateAccount(multiSignContract, keyPair); + CurrentWallet.CreateAccount(multiSignContract, keyPair); if (CurrentWallet is NEP6Wallet wallet) wallet.Save(); @@ -466,7 +466,7 @@ private void OnSignCommand(JObject jsonObjectToSign) { var snapshot = NeoSystem.StoreView; ContractParametersContext context = ContractParametersContext.Parse(jsonObjectToSign.ToString(), snapshot); - if (context.Network != neoSystem.Settings.Network) + if (context.Network != _neoSystem.Settings.Network) { ConsoleHelper.Warning("Network mismatch."); return; @@ -636,7 +636,7 @@ private void SignAndSendTx(DataCache snapshot, Transaction tx) ContractParametersContext context; try { - context = new ContractParametersContext(snapshot, tx, neoSystem.Settings.Network); + context = new ContractParametersContext(snapshot, tx, _neoSystem.Settings.Network); } catch (InvalidOperationException e) { diff --git a/neo-cli/CLI/MainService.cs b/neo-cli/CLI/MainService.cs index 6fa7853e8..89493e03d 100644 --- a/neo-cli/CLI/MainService.cs +++ b/neo-cli/CLI/MainService.cs @@ -36,6 +36,7 @@ using System.Reflection; using System.Text.RegularExpressions; using System.Threading; +using Array = System.Array; namespace Neo.CLI { @@ -45,33 +46,24 @@ public partial class MainService : ConsoleServiceBase, IWalletProvider public const long TestModeGas = 20_00000000; - private Wallet currentWallet; + private Wallet _currentWallet; public LocalNode LocalNode; public Wallet CurrentWallet { - get - { - return currentWallet; - } + get => _currentWallet; private set { - currentWallet = value; + _currentWallet = value; WalletChanged?.Invoke(this, value); } } - private NeoSystem neoSystem; + private NeoSystem _neoSystem; public NeoSystem NeoSystem { - get - { - return neoSystem; - } - private set - { - neoSystem = value; - } + get => _neoSystem; + private set => _neoSystem = value; } protected override string Prompt => "neo"; @@ -82,15 +74,15 @@ private set /// public MainService() : base() { - RegisterCommandHander(false, (str) => StringToAddress(str, NeoSystem.Settings.AddressVersion)); - RegisterCommandHander(false, (str) => UInt256.Parse(str)); - RegisterCommandHander((str) => str.Select(u => UInt256.Parse(u.Trim())).ToArray()); - RegisterCommandHander((arr) => arr.Select(str => StringToAddress(str, NeoSystem.Settings.AddressVersion)).ToArray()); - RegisterCommandHander((str) => ECPoint.Parse(str.Trim(), ECCurve.Secp256r1)); - RegisterCommandHander((str) => str.Select(u => ECPoint.Parse(u.Trim(), ECCurve.Secp256r1)).ToArray()); - RegisterCommandHander((str) => JObject.Parse(str)); - RegisterCommandHander((str) => decimal.Parse(str, CultureInfo.InvariantCulture)); - RegisterCommandHander((obj) => (JArray)obj); + RegisterCommandHandler(false, str => StringToAddress(str, NeoSystem.Settings.AddressVersion)); + RegisterCommandHandler(false, UInt256.Parse); + RegisterCommandHandler(str => str.Select(u => UInt256.Parse(u.Trim())).ToArray()); + RegisterCommandHandler(arr => arr.Select(str => StringToAddress(str, NeoSystem.Settings.AddressVersion)).ToArray()); + RegisterCommandHandler(str => ECPoint.Parse(str.Trim(), ECCurve.Secp256r1)); + RegisterCommandHandler(str => str.Select(u => ECPoint.Parse(u.Trim(), ECCurve.Secp256r1)).ToArray()); + RegisterCommandHandler(str => JObject.Parse(str)); + RegisterCommandHandler(str => decimal.Parse(str, CultureInfo.InvariantCulture)); + RegisterCommandHandler(obj => (JArray)obj); RegisterCommand(this); } @@ -483,7 +475,7 @@ public async void Start(string[] args) public void Stop() { - Interlocked.Exchange(ref neoSystem, null)?.Dispose(); + Interlocked.Exchange(ref _neoSystem, null)?.Dispose(); } private void WriteBlocks(uint start, uint count, string path, bool writeStart) @@ -548,14 +540,14 @@ private static void WriteLineWithoutFlicker(string message = "", int maxWidth = /// Max fee for running the script private void SendTransaction(byte[] script, UInt160 account = null, long gas = TestModeGas) { - Signer[] signers = System.Array.Empty(); + Signer[] signers = Array.Empty(); var snapshot = NeoSystem.StoreView; if (account != null) { signers = CurrentWallet.GetAccounts() .Where(p => !p.Lock && !p.WatchOnly && p.ScriptHash == account && NativeContract.GAS.BalanceOf(snapshot, p.ScriptHash).Sign > 0) - .Select(p => new Signer() { Account = p.ScriptHash, Scopes = WitnessScope.CalledByEntry }) + .Select(p => new Signer { Account = p.ScriptHash, Scopes = WitnessScope.CalledByEntry }) .ToArray(); } @@ -580,10 +572,7 @@ private void SendTransaction(byte[] script, UInt160 account = null, long gas = T catch (InvalidOperationException e) { ConsoleHelper.Error(GetExceptionMessage(e)); - return; } - - return; } /// @@ -592,12 +581,12 @@ private void SendTransaction(byte[] script, UInt160 account = null, long gas = T /// Script hash /// Operation /// Result - /// Transaction + /// Transaction /// Contract parameters /// Show result stack if it is true /// Max fee for running the script /// Return true if it was successful - private bool OnInvokeWithResult(UInt160 scriptHash, string operation, out StackItem result, IVerifiable verificable = null, JArray contractParameters = null, bool showStack = true, long gas = TestModeGas) + private bool OnInvokeWithResult(UInt160 scriptHash, string operation, out StackItem result, IVerifiable verifiable = null, JArray contractParameters = null, bool showStack = true, long gas = TestModeGas) { List parameters = new List(); @@ -635,12 +624,12 @@ private bool OnInvokeWithResult(UInt160 scriptHash, string operation, out StackI ConsoleHelper.Info("Invoking script with: ", $"'{script.ToBase64String()}'"); } - if (verificable is Transaction tx) + if (verifiable is Transaction tx) { tx.Script = script; } - using ApplicationEngine engine = ApplicationEngine.Run(script, NeoSystem.StoreView, container: verificable, settings: NeoSystem.Settings, gas: gas); + using ApplicationEngine engine = ApplicationEngine.Run(script, NeoSystem.StoreView, container: verifiable, settings: NeoSystem.Settings, gas: gas); PrintExecutionOutput(engine, showStack); result = engine.State == VMState.FAULT ? null : engine.ResultStack.Peek(); return engine.State != VMState.FAULT; From 8cac90f325e8588eed0660e953390f04b7cded1f Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Sat, 2 Apr 2022 21:17:35 -0400 Subject: [PATCH 06/65] create mode folders --- .../mainnet/config.fs.json} | 0 .../mainnet/config.json} | 0 neo-cli/Modes/privatenet/config.fs.json | 53 +++++++++++++++++++ neo-cli/{ => Modes/privatenet}/config.json | 0 .../testnet/config.fs.json} | 0 .../testnet/config.json} | 0 neo-cli/neo-cli.csproj | 20 +++++++ 7 files changed, 73 insertions(+) rename neo-cli/{config.fs.mainnet.json => Modes/mainnet/config.fs.json} (100%) rename neo-cli/{config.mainnet.json => Modes/mainnet/config.json} (100%) create mode 100644 neo-cli/Modes/privatenet/config.fs.json rename neo-cli/{ => Modes/privatenet}/config.json (100%) rename neo-cli/{config.fs.testnet.json => Modes/testnet/config.fs.json} (100%) rename neo-cli/{config.testnet.json => Modes/testnet/config.json} (100%) diff --git a/neo-cli/config.fs.mainnet.json b/neo-cli/Modes/mainnet/config.fs.json similarity index 100% rename from neo-cli/config.fs.mainnet.json rename to neo-cli/Modes/mainnet/config.fs.json diff --git a/neo-cli/config.mainnet.json b/neo-cli/Modes/mainnet/config.json similarity index 100% rename from neo-cli/config.mainnet.json rename to neo-cli/Modes/mainnet/config.json diff --git a/neo-cli/Modes/privatenet/config.fs.json b/neo-cli/Modes/privatenet/config.fs.json new file mode 100644 index 000000000..dadf6f5bf --- /dev/null +++ b/neo-cli/Modes/privatenet/config.fs.json @@ -0,0 +1,53 @@ +{ + "ApplicationConfiguration": { + "Logger": { + "Path": "Logs", + "ConsoleOutput": false, + "Active": false + }, + "Storage": { + "Engine": "LevelDBStore", + "Path": "Data_LevelDB_{0}" + }, + "P2P": { + "Port": 40333, + "WsPort": 40334, + "MinDesiredConnections": 10, + "MaxConnections": 40, + "MaxConnectionsPerAddress": 3 + }, + "UnlockWallet": { + "Path": "", + "Password": "", + "IsActive": false + } + }, + "ProtocolConfiguration": { + "Network": 91414437, + "AddressVersion": 53, + "MillisecondsPerBlock": 15000, + "MaxTransactionsPerBlock": 512, + "MemoryPoolMaxTransactions": 50000, + "MaxTraceableBlocks": 2102400, + "InitialGasDistribution": 5200000000000000, + "ValidatorsCount": 7, + "StandbyCommittee": [ + "026fa34ec057d74c2fdf1a18e336d0bd597ea401a0b2ad57340d5c220d09f44086", + "039a9db2a30942b1843db673aeb0d4fd6433f74cec1d879de6343cb9fcf7628fa4", + "0366d255e7ce23ea6f7f1e4bedf5cbafe598705b47e6ec213ef13b2f0819e8ab33", + "023f9cb7bbe154d529d5c719fdc39feaa831a43ae03d2a4280575b60f52fa7bc52", + "039ba959e0ab6dc616df8b803692f1c30ba9071b76b05535eb994bf5bbc402ad5f", + "035a2a18cddafa25ad353dea5e6730a1b9fcb4b918c4a0303c4387bb9c3b816adf", + "031f4d9c66f2ec348832c48fd3a16dfaeb59e85f557ae1e07f6696d0375c64f97b" + ], + "SeedList": [ + "morph1.fs.neo.org:40333", + "morph2.fs.neo.org:40333", + "morph3.fs.neo.org:40333", + "morph4.fs.neo.org:40333", + "morph5.fs.neo.org:40333", + "morph6.fs.neo.org:40333", + "morph7.fs.neo.org:40333" + ] + } +} diff --git a/neo-cli/config.json b/neo-cli/Modes/privatenet/config.json similarity index 100% rename from neo-cli/config.json rename to neo-cli/Modes/privatenet/config.json diff --git a/neo-cli/config.fs.testnet.json b/neo-cli/Modes/testnet/config.fs.json similarity index 100% rename from neo-cli/config.fs.testnet.json rename to neo-cli/Modes/testnet/config.fs.json diff --git a/neo-cli/config.testnet.json b/neo-cli/Modes/testnet/config.json similarity index 100% rename from neo-cli/config.testnet.json rename to neo-cli/Modes/testnet/config.json diff --git a/neo-cli/neo-cli.csproj b/neo-cli/neo-cli.csproj index 208fd90e4..cbb5cc07c 100644 --- a/neo-cli/neo-cli.csproj +++ b/neo-cli/neo-cli.csproj @@ -20,6 +20,26 @@ PreserveNewest PreserveNewest + + PreserveNewest + PreserveNewest + + + PreserveNewest + PreserveNewest + + + PreserveNewest + PreserveNewest + + + PreserveNewest + PreserveNewest + + + PreserveNewest + PreserveNewest + From c9c33928e63253af7d8e201a2fe8fa9c0b588013 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Sat, 2 Apr 2022 21:36:50 -0400 Subject: [PATCH 07/65] privatenet config and commands --- neo-cli/CLI/MainService.Mode.cs | 121 ++++++++++++++++++++++++++ neo-cli/Modes/privatenet/config.json | 42 ++------- neo-cli/Modes/privatenet/private.json | 1 + 3 files changed, 130 insertions(+), 34 deletions(-) create mode 100644 neo-cli/CLI/MainService.Mode.cs create mode 100644 neo-cli/Modes/privatenet/private.json diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs new file mode 100644 index 000000000..0be3761f5 --- /dev/null +++ b/neo-cli/CLI/MainService.Mode.cs @@ -0,0 +1,121 @@ +// Copyright (C) 2016-2021 The Neo Project. +// +// The neo-cli is free software distributed under the MIT software +// license, see the accompanying file LICENSE in the main directory of +// the project 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 Neo.ConsoleService; +using Neo.IO.Json; +using Neo.Plugins; +using System; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Net; +using System.Threading.Tasks; +namespace Neo.CLI; + + partial class MainService + { + /// + /// Process "install" command + /// + /// Mode name + [ConsoleCommand("mode load", Category = "Mode Commands")] + private async Task OnLoadMode(string modeName) + { + + + // using (response) + // { + // await using Stream stream = await response.Content.ReadAsStreamAsync(); + // using ZipArchive zip = new(stream, ZipArchiveMode.Read); + // try + // { + // zip.ExtractToDirectory("."); + // } + // catch (IOException) + // { + // } + // } + } + + /// + /// Process "mode list" command + /// Mode name + /// + [ConsoleCommand("mode list", Category = "Mode Commands")] + private void OnListModes() + { + // var plugin = Plugin.Plugins.FirstOrDefault(p => p.Name == pluginName); + // if (plugin is null) + // { + // ConsoleHelper.Warning("Plugin not found"); + // return; + // } + // if (plugin is Logger) + // { + // ConsoleHelper.Warning("You cannot uninstall a built-in plugin."); + // return; + // } + + // File.Delete(plugin.Path); + // File.Delete(plugin.ConfigFile); + // try + // { + // Directory.Delete(Path.GetDirectoryName(plugin.ConfigFile), false); + // } + // catch (IOException) + // { + // } + // ConsoleHelper.Info("Uninstall successful, please restart neo-cli."); + } + + /// + /// Process "mode save" command + /// Mode name + /// + [ConsoleCommand("mode save", Category = "Mode Commands")] + private void OnSaveMode(string modeName) + { + // if (Plugin.Plugins.Count > 0) + // { + // Console.WriteLine("Loaded plugins:"); + // foreach (Plugin plugin in Plugin.Plugins) + // { + // if (plugin is Logger) continue; + // ConsoleHelper.Info($"\t{plugin.Name,-20}", plugin.Description); + // } + // } + // else + // { + // ConsoleHelper.Warning("No loaded plugins"); + // } + } + + /// + /// Process "plugins" command + /// Mode name + /// + [ConsoleCommand("mode delete", Category = "Mode Commands")] + private void OnDeleteMode(string modeName) + { + // if (Plugin.Plugins.Count > 0) + // { + // Console.WriteLine("Loaded plugins:"); + // foreach (Plugin plugin in Plugin.Plugins) + // { + // if (plugin is Logger) continue; + // ConsoleHelper.Info($"\t{plugin.Name,-20}", plugin.Description); + // } + // } + // else + // { + // ConsoleHelper.Warning("No loaded plugins"); + // } + } + } diff --git a/neo-cli/Modes/privatenet/config.json b/neo-cli/Modes/privatenet/config.json index 7d037a19d..1b340e952 100644 --- a/neo-cli/Modes/privatenet/config.json +++ b/neo-cli/Modes/privatenet/config.json @@ -2,8 +2,8 @@ "ApplicationConfiguration": { "Logger": { "Path": "Logs", - "ConsoleOutput": false, - "Active": false + "ConsoleOutput": true, + "Active": true }, "Storage": { "Engine": "LevelDBStore", @@ -18,49 +18,23 @@ }, "UnlockWallet": { - "Path": "", + "Path": "private.json", "Password": "", - "IsActive": false + "IsActive": true } }, "ProtocolConfiguration": { - "Network": 860833102, + "Network": 582277343, "AddressVersion": 53, "MillisecondsPerBlock": 15000, "MaxTransactionsPerBlock": 512, "MemoryPoolMaxTransactions": 50000, "MaxTraceableBlocks": 2102400, "InitialGasDistribution": 5200000000000000, - "ValidatorsCount": 7, + "ValidatorsCount": 1, "StandbyCommittee": [ - "03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c", - "02df48f60e8f3e01c48ff40b9b7f1310d7a8b2a193188befe1c2e3df740e895093", - "03b8d9d5771d8f513aa0869b9cc8d50986403b78c6da36890638c3d46a5adce04a", - "02ca0e27697b9c248f6f16e085fd0061e26f44da85b58ee835c110caa5ec3ba554", - "024c7b7fb6c310fccf1ba33b082519d82964ea93868d676662d4a59ad548df0e7d", - "02aaec38470f6aad0042c6e877cfd8087d2676b0f516fddd362801b9bd3936399e", - "02486fd15702c4490a26703112a5cc1d0923fd697a33406bd5a1c00e0013b09a70", - "023a36c72844610b4d34d1968662424011bf783ca9d984efa19a20babf5582f3fe", - "03708b860c1de5d87f5b151a12c2a99feebd2e8b315ee8e7cf8aa19692a9e18379", - "03c6aa6e12638b36e88adc1ccdceac4db9929575c3e03576c617c49cce7114a050", - "03204223f8c86b8cd5c89ef12e4f0dbb314172e9241e30c9ef2293790793537cf0", - "02a62c915cf19c7f19a50ec217e79fac2439bbaad658493de0c7d8ffa92ab0aa62", - "03409f31f0d66bdc2f70a9730b66fe186658f84a8018204db01c106edc36553cd0", - "0288342b141c30dc8ffcde0204929bb46aed5756b41ef4a56778d15ada8f0c6654", - "020f2887f41474cfeb11fd262e982051c1541418137c02a0f4961af911045de639", - "0222038884bbd1d8ff109ed3bdef3542e768eef76c1247aea8bc8171f532928c30", - "03d281b42002647f0113f36c7b8efb30db66078dfaaa9ab3ff76d043a98d512fde", - "02504acbc1f4b3bdad1d86d6e1a08603771db135a73e61c9d565ae06a1938cd2ad", - "0226933336f1b75baa42d42b71d9091508b638046d19abd67f4e119bf64a7cfb4d", - "03cdcea66032b82f5c30450e381e5295cae85c5e6943af716cc6b646352a6067dc", - "02cd5a5547119e24feaa7c2a0f37b8c9366216bab7054de0065c9be42084003c8a" + "02155400060a3612eba11267fe8acc545f843fe73ebbd3d3781b7ee270f8b882c7" ], - "SeedList": [ - "seed1.neo.org:10333", - "seed2.neo.org:10333", - "seed3.neo.org:10333", - "seed4.neo.org:10333", - "seed5.neo.org:10333" - ] + "SeedList": [] } } diff --git a/neo-cli/Modes/privatenet/private.json b/neo-cli/Modes/privatenet/private.json new file mode 100644 index 000000000..0b51fc2f5 --- /dev/null +++ b/neo-cli/Modes/privatenet/private.json @@ -0,0 +1 @@ +{"name":null,"version":"1.0","scrypt":{"n":16384,"r":8,"p":8},"accounts":[{"address":"NbNRXrkfMyrEyEv2euE63Xxxqkno7xvuk2","label":null,"isDefault":false,"lock":false,"key":"","contract":{"script":"","parameters":[{"name":"signature","type":"Signature"}],"deployed":false},"extra":null}],"extra":null} From 029ac425bc738eb821d1619fd85a2255701e231c Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Wed, 6 Apr 2022 20:46:19 -0400 Subject: [PATCH 08/65] load mode --- neo-cli/CLI/MainService.cs | 47 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/neo-cli/CLI/MainService.cs b/neo-cli/CLI/MainService.cs index 89493e03d..b3bb8019e 100644 --- a/neo-cli/CLI/MainService.cs +++ b/neo-cli/CLI/MainService.cs @@ -406,6 +406,25 @@ public async void Start(string[] args) case "--noverify": verifyImport = false; break; + case "--mode": + case "/mode": + { + if (i < args.Length) + { + i++; + // Get all the modes + var modes = Directory.GetDirectories("./Modes/"); + if (modes.Any(p => string.Equals(p, args[i], StringComparison.CurrentCultureIgnoreCase))) + { + LoadConfig($"Modes/{args[i]}"); + } + else + { + throw new Exception($"Invalid Mode {args[i]}."); + } + } + } + break; } _ = new Logger(); @@ -658,5 +677,33 @@ static string GetExceptionMessage(Exception exception) return exception.Message; } + + + private void LoadConfig(string mode) + { + var dir = new DirectoryInfo(mode); + if (!dir.Exists) + throw new DirectoryNotFoundException($"Mode not found: {dir.FullName}"); + + // Cache directories before we start copying + var dirs = dir.GetDirectories(); + + // Get the config files of the node + foreach (var file in dir.GetFiles()) + { + var targetFilePath = Path.Combine("./", file.Name); + file.CopyTo(targetFilePath, true); + } + + // Copy the Plugin files + foreach (var plugin in dirs) + { + foreach (var file in plugin.GetFiles()) + { + var targetFilePath = Path.Combine($"Plugins/{plugin.Name}", file.Name); + file.CopyTo(targetFilePath, true); + } + } + } } } From d4bb9e43ef7e0f31240a814862d5d55c368bf8b1 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Wed, 6 Apr 2022 21:01:02 -0400 Subject: [PATCH 09/65] list mode --- neo-cli/CLI/MainService.Mode.cs | 124 +++++++++++++++++--------------- neo-cli/CLI/MainService.cs | 31 +------- neo-cli/Modes/Mode | 1 + 3 files changed, 69 insertions(+), 87 deletions(-) create mode 100644 neo-cli/Modes/Mode diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 0be3761f5..af9da7c87 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -16,34 +16,13 @@ using System.IO.Compression; using System.Linq; using System.Net; +using System.Text; using System.Threading.Tasks; +using Akka.Util.Internal; namespace Neo.CLI; partial class MainService { - /// - /// Process "install" command - /// - /// Mode name - [ConsoleCommand("mode load", Category = "Mode Commands")] - private async Task OnLoadMode(string modeName) - { - - - // using (response) - // { - // await using Stream stream = await response.Content.ReadAsStreamAsync(); - // using ZipArchive zip = new(stream, ZipArchiveMode.Read); - // try - // { - // zip.ExtractToDirectory("."); - // } - // catch (IOException) - // { - // } - // } - } - /// /// Process "mode list" command /// Mode name @@ -51,28 +30,13 @@ private async Task OnLoadMode(string modeName) [ConsoleCommand("mode list", Category = "Mode Commands")] private void OnListModes() { - // var plugin = Plugin.Plugins.FirstOrDefault(p => p.Name == pluginName); - // if (plugin is null) - // { - // ConsoleHelper.Warning("Plugin not found"); - // return; - // } - // if (plugin is Logger) - // { - // ConsoleHelper.Warning("You cannot uninstall a built-in plugin."); - // return; - // } - - // File.Delete(plugin.Path); - // File.Delete(plugin.ConfigFile); - // try - // { - // Directory.Delete(Path.GetDirectoryName(plugin.ConfigFile), false); - // } - // catch (IOException) - // { - // } - // ConsoleHelper.Info("Uninstall successful, please restart neo-cli."); + try + { + Directory.GetDirectories("./Modes/").ForEach(p => ConsoleHelper.Info(p)); + } + catch (IOException) + { + } } /// @@ -82,19 +46,7 @@ private void OnListModes() [ConsoleCommand("mode save", Category = "Mode Commands")] private void OnSaveMode(string modeName) { - // if (Plugin.Plugins.Count > 0) - // { - // Console.WriteLine("Loaded plugins:"); - // foreach (Plugin plugin in Plugin.Plugins) - // { - // if (plugin is Logger) continue; - // ConsoleHelper.Info($"\t{plugin.Name,-20}", plugin.Description); - // } - // } - // else - // { - // ConsoleHelper.Warning("No loaded plugins"); - // } + } /// @@ -118,4 +70,60 @@ private void OnDeleteMode(string modeName) // ConsoleHelper.Warning("No loaded plugins"); // } } + + + + private void LoadConfig(string mode) + { + var dir = new DirectoryInfo(mode); + if (!dir.Exists) + throw new DirectoryNotFoundException($"Mode not found: {dir.FullName}"); + + // Cache directories before we start copying + var dirs = dir.GetDirectories(); + + // Get the config files of the node + foreach (var file in dir.GetFiles()) + { + var targetFilePath = Path.Combine("./", file.Name); + file.CopyTo(targetFilePath, true); + } + + // Copy the Plugin files + foreach (var plugin in dirs) + { + foreach (var file in plugin.GetFiles()) + { + var targetFilePath = Path.Combine($"Plugins/{plugin.Name}", file.Name); + file.CopyTo(targetFilePath, true); + } + } + } + + private void SaveMode(string mode) + { + string path = @"./Modes/Mode"; + + try + { + // if(File.Exists(path)) File.Delete(path); + using (var fs = File.Create(path)) + { + byte[] info = new UTF8Encoding(true).GetBytes(mode); + fs.Write(info, 0, info.Length); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + // using (StreamReader sr = File.OpenText(path)) + // { + // string s = ""; + // while ((s = sr.ReadLine()) != null) + // { + // Console.WriteLine(s); + // } + // } + } } diff --git a/neo-cli/CLI/MainService.cs b/neo-cli/CLI/MainService.cs index b3bb8019e..922760348 100644 --- a/neo-cli/CLI/MainService.cs +++ b/neo-cli/CLI/MainService.cs @@ -409,7 +409,7 @@ public async void Start(string[] args) case "--mode": case "/mode": { - if (i < args.Length) + if (i < args.Length-1) { i++; // Get all the modes @@ -417,6 +417,7 @@ public async void Start(string[] args) if (modes.Any(p => string.Equals(p, args[i], StringComparison.CurrentCultureIgnoreCase))) { LoadConfig($"Modes/{args[i]}"); + SaveMode(args[i]); } else { @@ -677,33 +678,5 @@ static string GetExceptionMessage(Exception exception) return exception.Message; } - - - private void LoadConfig(string mode) - { - var dir = new DirectoryInfo(mode); - if (!dir.Exists) - throw new DirectoryNotFoundException($"Mode not found: {dir.FullName}"); - - // Cache directories before we start copying - var dirs = dir.GetDirectories(); - - // Get the config files of the node - foreach (var file in dir.GetFiles()) - { - var targetFilePath = Path.Combine("./", file.Name); - file.CopyTo(targetFilePath, true); - } - - // Copy the Plugin files - foreach (var plugin in dirs) - { - foreach (var file in plugin.GetFiles()) - { - var targetFilePath = Path.Combine($"Plugins/{plugin.Name}", file.Name); - file.CopyTo(targetFilePath, true); - } - } - } } } diff --git a/neo-cli/Modes/Mode b/neo-cli/Modes/Mode new file mode 100644 index 000000000..15471a593 --- /dev/null +++ b/neo-cli/Modes/Mode @@ -0,0 +1 @@ +mainnet From 11dabc810c7849eda1a3fb37d903a0e318f6565f Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Wed, 6 Apr 2022 21:14:13 -0400 Subject: [PATCH 10/65] delete mode --- neo-cli/CLI/MainService.Mode.cs | 99 +++++++++++++++++---------------- neo-cli/CLI/MainService.cs | 3 +- 2 files changed, 52 insertions(+), 50 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index af9da7c87..727095c55 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -56,74 +56,77 @@ private void OnSaveMode(string modeName) [ConsoleCommand("mode delete", Category = "Mode Commands")] private void OnDeleteMode(string modeName) { - // if (Plugin.Plugins.Count > 0) - // { - // Console.WriteLine("Loaded plugins:"); - // foreach (Plugin plugin in Plugin.Plugins) - // { - // if (plugin is Logger) continue; - // ConsoleHelper.Info($"\t{plugin.Name,-20}", plugin.Description); - // } - // } - // else - // { - // ConsoleHelper.Warning("No loaded plugins"); - // } + try + { + var dir = new DirectoryInfo($"Modes/{modeName}"); + if (!dir.Exists) + return; + Directory.Delete(dir.FullName); + ConsoleHelper.Info("Mode ", modeName, " was deleted."); + } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } } - - - private void LoadConfig(string mode) + private static void LoadMode() { - var dir = new DirectoryInfo(mode); - if (!dir.Exists) - throw new DirectoryNotFoundException($"Mode not found: {dir.FullName}"); + const string path = @"./Modes/Mode"; + try + { + var mode = "mainnet"; + using (var sr = File.OpenText(path)) + { + // If there is no valid mode, load mainnet as default. + mode = sr.ReadLine()??mode; + } - // Cache directories before we start copying - var dirs = dir.GetDirectories(); + var dir = new DirectoryInfo(mode); + if (!dir.Exists) + throw new DirectoryNotFoundException($"Mode not found: {dir.FullName}"); - // Get the config files of the node - foreach (var file in dir.GetFiles()) - { - var targetFilePath = Path.Combine("./", file.Name); - file.CopyTo(targetFilePath, true); - } + // Cache directories before we start copying + var dirs = dir.GetDirectories(); - // Copy the Plugin files - foreach (var plugin in dirs) - { - foreach (var file in plugin.GetFiles()) + // Get the config files of the node + foreach (var file in dir.GetFiles()) { - var targetFilePath = Path.Combine($"Plugins/{plugin.Name}", file.Name); + var targetFilePath = Path.Combine("./", file.Name); file.CopyTo(targetFilePath, true); } + + // Copy the Plugin files + foreach (var plugin in dirs) + { + foreach (var file in plugin.GetFiles()) + { + var targetFilePath = Path.Combine($"Plugins/{plugin.Name}", file.Name); + file.CopyTo(targetFilePath, true); + } + } + } + catch (Exception e) + { + Console.WriteLine(e); + throw; } } - private void SaveMode(string mode) + private static void SaveMode(string mode) { - string path = @"./Modes/Mode"; - + const string path = @"./Modes/Mode"; try { // if(File.Exists(path)) File.Delete(path); - using (var fs = File.Create(path)) - { - byte[] info = new UTF8Encoding(true).GetBytes(mode); - fs.Write(info, 0, info.Length); - } + using var fs = File.Create(path); + var info = new UTF8Encoding(true).GetBytes(mode); + fs.Write(info, 0, info.Length); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } - // using (StreamReader sr = File.OpenText(path)) - // { - // string s = ""; - // while ((s = sr.ReadLine()) != null) - // { - // Console.WriteLine(s); - // } - // } } } diff --git a/neo-cli/CLI/MainService.cs b/neo-cli/CLI/MainService.cs index 922760348..d1c6cb49c 100644 --- a/neo-cli/CLI/MainService.cs +++ b/neo-cli/CLI/MainService.cs @@ -416,7 +416,6 @@ public async void Start(string[] args) var modes = Directory.GetDirectories("./Modes/"); if (modes.Any(p => string.Equals(p, args[i], StringComparison.CurrentCultureIgnoreCase))) { - LoadConfig($"Modes/{args[i]}"); SaveMode(args[i]); } else @@ -427,7 +426,7 @@ public async void Start(string[] args) } break; } - + LoadMode(); _ = new Logger(); ProtocolSettings protocol = ProtocolSettings.Load("config.json"); From e86ab46cadf054c47d1e458cf3165621601b8c32 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Wed, 6 Apr 2022 21:31:50 -0400 Subject: [PATCH 11/65] save mode --- neo-cli/CLI/MainService.Mode.cs | 213 ++++++++++++++++++++------------ 1 file changed, 132 insertions(+), 81 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 727095c55..5a5fd2d97 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -21,112 +21,163 @@ using Akka.Util.Internal; namespace Neo.CLI; - partial class MainService +partial class MainService +{ + /// + /// Process "mode list" command + /// Mode name + /// + [ConsoleCommand("mode list", Category = "Mode Commands")] + private void OnListModes() { - /// - /// Process "mode list" command - /// Mode name - /// - [ConsoleCommand("mode list", Category = "Mode Commands")] - private void OnListModes() + try { - try - { - Directory.GetDirectories("./Modes/").ForEach(p => ConsoleHelper.Info(p)); - } - catch (IOException) - { - } + Directory.GetDirectories("./Modes/").ForEach(p => ConsoleHelper.Info(p)); } - - /// - /// Process "mode save" command - /// Mode name - /// - [ConsoleCommand("mode save", Category = "Mode Commands")] - private void OnSaveMode(string modeName) + catch (IOException) { - } + } - /// - /// Process "plugins" command - /// Mode name - /// - [ConsoleCommand("mode delete", Category = "Mode Commands")] - private void OnDeleteMode(string modeName) + /// + /// Process "mode save" command + /// Mode name + /// + [ConsoleCommand("mode save", Category = "Mode Commands")] + private void OnSaveMode(string modeName) + { + // if no mode name assigned, save on current mode + modeName ??= LoadCurrentMode(); + try { - try + var dir = new DirectoryInfo($"./"); + + // Get the config files of the node + foreach (var file in dir.GetFiles().Where(p=> p.Extension == ".json")) { - var dir = new DirectoryInfo($"Modes/{modeName}"); - if (!dir.Exists) - return; - Directory.Delete(dir.FullName); - ConsoleHelper.Info("Mode ", modeName, " was deleted."); + var targetMode = new DirectoryInfo($"Modes/{modeName}"); + if (!targetMode.Exists) Directory.CreateDirectory(targetMode.FullName); + + var targetFilePath = Path.Combine(targetMode.FullName, file.Name); + file.CopyTo(targetFilePath, true); } - catch (Exception e) + + var plugins = new DirectoryInfo($"./Plugins"); + // Cache directories before we start copying + var dirs = plugins.GetDirectories(); + + // Save the Plugin files + foreach (var plugin in dirs) { - Console.WriteLine(e); - throw; + foreach (var file in plugin.GetFiles()) + { + var targetPlugin = new DirectoryInfo($"Modes/{modeName}/{plugin}"); + if (!targetPlugin.Exists) Directory.CreateDirectory(targetPlugin.FullName); + var targetFilePath = Path.Combine(targetPlugin.FullName, file.Name); + file.CopyTo(targetFilePath, true); + } } + // Update the most recent mode + SaveMode(modeName); + } + catch (Exception e) + { + Console.WriteLine(e); + throw; } - private static void LoadMode() + } + + /// + /// Process "plugins" command + /// Mode name + /// + [ConsoleCommand("mode delete", Category = "Mode Commands")] + private void OnDeleteMode(string modeName) + { + try { - const string path = @"./Modes/Mode"; - try - { - var mode = "mainnet"; - using (var sr = File.OpenText(path)) - { - // If there is no valid mode, load mainnet as default. - mode = sr.ReadLine()??mode; - } + var dir = new DirectoryInfo($"Modes/{modeName}"); + if (!dir.Exists) + return; + Directory.Delete(dir.FullName); + ConsoleHelper.Info("Mode ", modeName, " was deleted."); + } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } + } - var dir = new DirectoryInfo(mode); - if (!dir.Exists) - throw new DirectoryNotFoundException($"Mode not found: {dir.FullName}"); + private static void LoadMode() + { + try + { + var mode = LoadCurrentMode(); + var dir = new DirectoryInfo(mode); + if (!dir.Exists) + throw new DirectoryNotFoundException($"Mode not found: {dir.FullName}"); - // Cache directories before we start copying - var dirs = dir.GetDirectories(); + // Cache directories before we start copying + var dirs = dir.GetDirectories(); - // Get the config files of the node - foreach (var file in dir.GetFiles()) - { - var targetFilePath = Path.Combine("./", file.Name); - file.CopyTo(targetFilePath, true); - } + // Get the config files of the node + foreach (var file in dir.GetFiles()) + { + var targetFilePath = Path.Combine("./", file.Name); + file.CopyTo(targetFilePath, true); + } - // Copy the Plugin files - foreach (var plugin in dirs) + // Copy the Plugin files + foreach (var plugin in dirs) + { + foreach (var file in plugin.GetFiles()) { - foreach (var file in plugin.GetFiles()) - { - var targetFilePath = Path.Combine($"Plugins/{plugin.Name}", file.Name); - file.CopyTo(targetFilePath, true); - } + var targetFilePath = Path.Combine($"Plugins/{plugin.Name}", file.Name); + file.CopyTo(targetFilePath, true); } } - catch (Exception e) - { - Console.WriteLine(e); - throw; - } } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } + } - private static void SaveMode(string mode) + private static void SaveMode(string mode) + { + const string path = @"./Modes/Mode"; + try { - const string path = @"./Modes/Mode"; - try - { - // if(File.Exists(path)) File.Delete(path); - using var fs = File.Create(path); - var info = new UTF8Encoding(true).GetBytes(mode); - fs.Write(info, 0, info.Length); - } - catch (Exception ex) + // if(File.Exists(path)) File.Delete(path); + using var fs = File.Create(path); + var info = new UTF8Encoding(true).GetBytes(mode); + fs.Write(info, 0, info.Length); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + } + } + + private static string LoadCurrentMode() + { + const string path = @"./Modes/Mode"; + var mode = "mainnet"; + try + { + using (var sr = File.OpenText(path)) { - Console.WriteLine(ex.ToString()); + // If there is no valid mode, load mainnet as default. + mode = sr.ReadLine() ?? mode; } } + catch (Exception e) + { + // ignored + } + return mode; } +} From c73623b9d7f4facad480af6290cd94c778e84b23 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Wed, 6 Apr 2022 23:03:18 -0400 Subject: [PATCH 12/65] optimise code --- neo-cli/CLI/MainService.Mode.cs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 5a5fd2d97..b90e0e2d3 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -168,11 +168,9 @@ private static string LoadCurrentMode() var mode = "mainnet"; try { - using (var sr = File.OpenText(path)) - { - // If there is no valid mode, load mainnet as default. - mode = sr.ReadLine() ?? mode; - } + using var sr = File.OpenText(path); + // If there is no valid mode, load mainnet as default. + mode = sr.ReadLine() ?? mode; } catch (Exception e) { From 2564839faea0c0e5e55099d24c16234d0f203dc3 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 7 Apr 2022 10:25:51 -0400 Subject: [PATCH 13/65] done with the mode system and added an icon for neo-cli --- neo-cli/CLI/MainService.Mode.cs | 20 ++++++++++---------- neo-cli/CLI/MainService.cs | 6 +++++- neo-cli/neo-cli.csproj | 29 ++++++++--------------------- neo-cli/neo.ico | Bin 0 -> 21317 bytes 4 files changed, 23 insertions(+), 32 deletions(-) create mode 100644 neo-cli/neo.ico diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index b90e0e2d3..52c540071 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -9,15 +9,10 @@ // modifications are permitted. using Neo.ConsoleService; -using Neo.IO.Json; -using Neo.Plugins; using System; using System.IO; -using System.IO.Compression; using System.Linq; -using System.Net; using System.Text; -using System.Threading.Tasks; using Akka.Util.Internal; namespace Neo.CLI; @@ -48,6 +43,7 @@ private void OnSaveMode(string modeName) { // if no mode name assigned, save on current mode modeName ??= LoadCurrentMode(); + modeName = modeName.ToLower(); try { var dir = new DirectoryInfo($"./"); @@ -56,8 +52,8 @@ private void OnSaveMode(string modeName) foreach (var file in dir.GetFiles().Where(p=> p.Extension == ".json")) { var targetMode = new DirectoryInfo($"Modes/{modeName}"); + // Create the mode if it does not exist if (!targetMode.Exists) Directory.CreateDirectory(targetMode.FullName); - var targetFilePath = Path.Combine(targetMode.FullName, file.Name); file.CopyTo(targetFilePath, true); } @@ -69,9 +65,9 @@ private void OnSaveMode(string modeName) // Save the Plugin files foreach (var plugin in dirs) { - foreach (var file in plugin.GetFiles()) + foreach (var file in plugin.GetFiles().Where(p=> p.Extension == ".json")) { - var targetPlugin = new DirectoryInfo($"Modes/{modeName}/{plugin}"); + var targetPlugin = new DirectoryInfo($"Modes/{modeName}/{plugin.Name}"); if (!targetPlugin.Exists) Directory.CreateDirectory(targetPlugin.FullName); var targetFilePath = Path.Combine(targetPlugin.FullName, file.Name); file.CopyTo(targetFilePath, true); @@ -115,7 +111,7 @@ private static void LoadMode() try { var mode = LoadCurrentMode(); - var dir = new DirectoryInfo(mode); + var dir = new DirectoryInfo($"./Modes/{mode}"); if (!dir.Exists) throw new DirectoryNotFoundException($"Mode not found: {dir.FullName}"); @@ -149,6 +145,8 @@ private static void LoadMode() private static void SaveMode(string mode) { const string path = @"./Modes/Mode"; + mode ??= "mainnet"; + mode = mode.ToLower(); try { // if(File.Exists(path)) File.Delete(path); @@ -175,7 +173,9 @@ private static string LoadCurrentMode() catch (Exception e) { // ignored + ConsoleHelper.Error("Mode system is crashed, please reinstall the node"); + /// TODO: Maybe allow users to fix it automatically } - return mode; + return mode.ToLower(); } } diff --git a/neo-cli/CLI/MainService.cs b/neo-cli/CLI/MainService.cs index d1c6cb49c..025f47245 100644 --- a/neo-cli/CLI/MainService.cs +++ b/neo-cli/CLI/MainService.cs @@ -36,6 +36,7 @@ using System.Reflection; using System.Text.RegularExpressions; using System.Threading; +using Akka.Util.Internal; using Array = System.Array; namespace Neo.CLI @@ -414,8 +415,10 @@ public async void Start(string[] args) i++; // Get all the modes var modes = Directory.GetDirectories("./Modes/"); - if (modes.Any(p => string.Equals(p, args[i], StringComparison.CurrentCultureIgnoreCase))) + // Find the expected mode + if (modes.Any(p => string.Equals(new DirectoryInfo(p).Name, args[i], StringComparison.CurrentCultureIgnoreCase))) { + // Update the mode file SaveMode(args[i]); } else @@ -426,6 +429,7 @@ public async void Start(string[] args) } break; } + // Load the mode (network) LoadMode(); _ = new Logger(); diff --git a/neo-cli/neo-cli.csproj b/neo-cli/neo-cli.csproj index cbb5cc07c..59038fca7 100644 --- a/neo-cli/neo-cli.csproj +++ b/neo-cli/neo-cli.csproj @@ -13,34 +13,21 @@ The Neo Project Neo.CLI Neo.CLI + neo.ico - + + + PreserveNewest - PreserveNewest - - + Modes\%(RecursiveDir)\%(Filename)%(Extension) + + diff --git a/neo-cli/neo.ico b/neo-cli/neo.ico new file mode 100644 index 0000000000000000000000000000000000000000..60786c424d8ec4c41a72a023d1aead2a8995a515 GIT binary patch literal 21317 zcmeI44Lnp!|G;N0i(0l9@=~EfC6!WAE4GUyg^S+gwIr2FkyVP7`{ZAGVU@QMm99i6 z6``zL#U<6I7et#RDy&KrcK^S@-bdZ;L%H|4J@;cief{Q~o%#KKGiT16nK^Sph=4@U zkRb@95^@nnXemNSR<`T-|HKix2IrKNx{l94y7`g_X=rpGt02^%02v_Q{K@cJr~yI~ z;24s^nXdC75CT2J26xeU{1^U-c#cp{`eLd_dJ4o102g2oKL4Kr{v8koG=ZH!9?$|5 z0azDeCU-&rDFu-6u^`~zf$=~E!0$n4{@?^80qOOCeLz8XT##K*&MA=Zb&tGQ&#jQl zXfve$1$YDSffm33_$@#>tmF6jtI?g1RCK*NAI|%~mj51sJraq0_3!+G7^D&C5`p+cU^5T_tOP~_LO`Da zPS*|gt25rGj9;0E&qoN;>WdI-H9+j0Rtn^S^f({xXP~P>&>eO5Kb_{G&-!omGoAMS z;eQ0zA0!FD{lvoVc)v;xI&ixp0!n}bkO;g4t^vLFyI(R6`8wMwNGZS^hyrlG+71Zr z%WQ~$q95*QK_5LB;$r||eD3oA`2_k8K>YXjdY6sg^mpqO0XYG11u}t)z$ecDft_ys z_?|lf2>ktAW`~zS{v#KRLM|dV(D4{(0|b4)K=xZd^8$+b zg5ClBUDy2D|9Ji6hFn7a&^~M78VlN_;M!u@-}dt^;u*RUb`LQ_GEgMwy9u_MdbFqh z>hHSW@N>Hcm4$QA+0a511ZDaeY?OknY>;?N_Pfx1|KdJk3-Ao+06xEee}7zq-a)!M z;pOP$kzbG#GXas{9{gQ^G=lyIk2jTpwZJ9d^ReIOHr_y*JSflh$d_nL=p%%pKKxGo zCnq4iz?L|~X8^l^n?N&w_2V(_ZD22;3rGT;c|K9phXX-AkV63@0NXMJq=C*cNFUS; zB>96H;KN|)Hv;&mU6hZwqBjwjB#JnwZ*U+EJQNNs=t z6aa$07WcOofIrnf=)-pLvt$zB24n&az~|48UhU)OAwUH1_*oGj_ZGkowvX3MDgnWK z_e-|FXdl}E@Vbf&U?I$tMBcDFl#(w-2 z<;V7S4cPx;d+T}a2kQTy+5RrU9LNUdKP7MveCXvq`19|-=cp;78l4M!gy@H}5FPBt zgD+Jezck1EE9?uN3m;$}RRVL+h|s%e3#{kv20yZZh8}hDHTL`Z{1Mpyx2!>Lz?Wa( znY8yvKH38Pb1?XE2mIIwve(f4{K0G2@jxBW+cWszwm%&s@W2nec9#ZgQ#;@}H6gU9 zSM&JUFF+LHcx}-W$N}(t^^a_Q={%liR|99kk7ckvPL8PS-G0v$kXPUfp2y;AvL9dr zAAm2}#C7!wxCE>R#si(>Gm!lXI6r{ry|REMfY$?`0=S&GZgPPg03JJu1D(G2%jg#} z3-p4-V?-6e2ABtQzSjad5C&?X&ouyR5TAxtUp}7$AYXnf@>Og_UVsCDzKM3o$7g^t z4w27qSNzl#9N~2e{I19W_-&m+d0?Fas$(Dw)WARu{6lL1Kc~CF?{NQTp55I(3#v0v^CMfD3%?bI;?y)qn5}`;FJJ#{o`23Q!C5b?)_5{=-~QuwE$& z@u|REKnS1zmH>WY|Mh^!Ks(U0Zu=7NlmFO1K(L`zTJsaew{CbHYE`f707E_{4wkMbJKmLR=p>0I-3c>)Acm_x^tW zs}VYUwbSoG;HMU_3&8LF|7bn@d-DGX^Blr;y#YuE`m&z>{rF#ln6S2_+sC@@>9-*M z_qLxd|7qZVGa&HkYvh3cU29U`*8dFD|3Ld0Xg>q}PyfcB-#-2s=zj+KpZ@hfN8!7e zF)#*-fbqi#PFe^2b%e4cfP4X9|M5QR{?30b`Z50%_}ZJq`@io4hv5DCVwi8v zgK}&K+~HfW{`xNu{_h0ve(HBXZ@%>R_hu-^O~5O>5{)~~N9ai2x2*njHGVZq7%ew-wD<}&Y;#2^yN8bXlf1j5H z&qK?ANC1B`Fap5q@83nhesudI4RSGX6u@hz&j9>B!xm5k@S5;<9k74hevSc&_q*V> z)_JYIYsUwi8>oSS8W^a7KGs0j#v%NTISzf1?cM1(-Lms@E5vW_mYi-0s_?h&SS71V z@=%wA?N6QOS=|zSx3bfDs7Nfi2obU5;f+@y`QU!12^+0)jz8(S-5n|S?0pLf^*sory4P#@M#XNVuW#0 zWuE(8$)wd|tfTTyrB!ZHj}IuXXt~z-!RM^a2)ppKZH?PMW@W#nzF;UDGr#sbfKeujt&&ADwpaX6GdiN+|RDRO?rSb z8JUbpeuhpY?oh4}SByJ>tHAZnjhRbku$?&3k~R{qqL&G?gaT*tS{#L2MY!r*jTB0& zJ;x+Brj*PW=5!}o*ha{e;E6^u-2FaSw)?gTwaSV61^CJM*$Www{cEP7GBtl6-4t@V z#3SRMTV;YZ!o{PBn+b;q-hK}mPaK+3rjZ$1@lRfbG1qmNauhi7oRSsovknPGqhz9< z@=X6(er6K8bDYt|c_dyu>tO-4!;|C8SyaQ*)D_yfz)s@5kXg{OJ^FicIMYz%S-Xr( zu}8vWLK?B~5UP zC#NXz1_cJ}T7zbQomCubi<~EtHb$XuBb}vMiQM6wEyGB9s&hqUN$!P6)=KVO9Gc{J z&WV#e?f})&He;mKDb`I^LhRkz0G2N?T29zK7s)C&dv|QTVCt*5?pB9?$YEoLJoB-omvrPsMbQwXWQOqt~@!__&j$VXCCLuDZb7s*&=mfjQz{d z#|ioD3N4PR>0?Nt&&qU~pAsNNp{#0ho8M}9)I{#xU}KX8XZD#?g7%^JSr2dje47!? z+>v9)_IfwXp~)?h%qZ2mrqZ%>dhM)`A>r|%kJ(mvxnagbbVykTsM2voD15S9s|n*( zLClkdp-rZ*T25Um8p<}~s;@Bg8sw!I7!a}w6~*qTYZ%0_yI_|c%DY${TC2e&OjOV{ zu+_O}=Qhe`qW4U&AjxKWk9Q;Z-|O^~A9PiW5^U%1pKiHj6wzT06vRD$bL;wtw!^Kr znrJTE7ohiZ<>mI_>Iy<6RtdDWd6mxt^1VAGoMzw7F3g#=(E6ags>wdHpsJ@YPLurX z%l1NRTV%a8Ey&Mz(uev+wypaCa~VoPaW0YdlzE+nv_rv1p$n$jA+A>@pHN9N2q^e< z-nOFBw@xG7Uj+t`Xlr(wG_0Rq+o&3_Hna?U)C-a@HVcZ#DZJPku1QoP@@KG_E9)~> z`cJ-cI$>Wx@{clFh1>LG#*o zxm>;e=L5{kRblxXSgT`IxrW(_u4f}V%H5z~@=&m`*&od6TAsyk(;c_*7w>}N+=uI0 z&(buB4m(XYZHp|HsJ69_G`0_FX@4pFO!4l?#fFQ0M7&U|Wa;`>>?mjU(5+AF-m)kz zUZ?p6k)u#p@VE=7Bi>9~*StVLx6xv*#RCakh&!g-ve^fPZ^ZT|J;TKg!88e1U z29Nf;KihvQQ%So?N{{F}rd08QczX1)+1v^rKF!h*oiP|!GG4TUy6)wN*~2&T3Sy#- zB)8ZSclt|3CAcf;*0xZzmXH_=w+`|87y09O2K`KEgX;0BXw!YgRO7oJc0_KUS*}fD zlr?CwV^RY?PH5U2)-at5IUB~>#-;@at~h#ShbI{l)M{K=`g)?p9q;1>>J|4b+t-vV zOWmk^^oI59rPd$x;}@KAs%x0d4&zJBu3qgl%wNG_Vx3B!BcX_0q_l`N8%(md~x7OGyckuW8%vE`@s!4`VW86IijqZ+jgGTttI`r~HH zRp^YOE`b+VH@PBe(T>JO)eY}oi>V!L|*y5m~Arf$^LD$RT=A<4IFWodwBh)ewN+-@>Nbf-JZMxp z(mq!5fr}cEc4YO`ip3s7=T}70MV@88Eq>iXiQOxQ)+B^Byk}12S%o!BQIQM2 zj9GLl_7VMcPPAV(!>WE(@RRpxgu*R#NlVDcu%n!(!x?em)u!RxZSBV|hAJlBh@`a3 zapTfGmI+U~EWbfv_QJv(dodzSEu5evU4()LIim$4nkaU+9J0tEqj(1r!%E{H{ImT` zcBAN>$15JeUz!|&H>!2WBV;p3y|zVv-FsQIuPr-*-{7f0I4-;t#u-$g3%)vlw7 zv}Y<}lK1MfB(fyhiEcAfq|;@V6OV}(!2{+joy0hJE^;XAg$FfRC|Sstm?*S|k?Hq} zaj&i8Or$Q6HasDhljcF?i|Y(-S8>x6_s?V$`dNO2ALWTO%McA&5g)^}R8cSC<%C30 zPXZmuI5wpWC8Ndm*ByklX=(1LRw#^cG{1~!zw}ZHYxM{Ht+6GI9CyAKWx19PF?wGT=oN*aZanNfw zxlOK{`p95k!1(62A5GREmrW&kx%TXO9kJJA@~)Q`6mdK`8H3LjdAW_jRZl%FXj$UR*^NdUClP7>CnWvN>OAd) z?1Xso>A`czNjX(d_fJPNyk2UwN>mhwuzZm(A@S4{1-m_YxyR*@ysNnXIM&o!PamWs zY_sU9<(9c_V@6Qo@{qYZc-F#bVfYFqAuTBG9L^|p1=C1EOpTnq&Q78iv6X5u?$P|n z151f(9b}Ke&Fu_TPWPZrMN{FCyZ*xLb($-dEH7y^8f^d_>nTZp`+M~|rlwlfrlvFG zg|wKfi`5kr)}S*{FRPy3uJhzcdj)wYY!dbiD$ZRaWv4R(mH0H9=F$D=1=H3p3$EPl zZQR6FACxE~i_~tmRy}>idgT;X)g0^PMR6leR2Y#1|CiDY8A`OsaUyTuMTJJ?o5yU8 z3j+fdOEP2%-rRnEv0b07oj`#HcuK9Ou2NpEiLn?txN+r%h6OIpDA5bO86%;Y)z-$!4*scfky_Tdk3l8l zw>70?jC-nR{K9dY(RFKiAEO`OnVI-gjw5IE9(uOETGle=)#udwyZ6_!ITYhvTDzua^)Q2oY^;6-aG3KHgvjnas6`Y(ca#-tsuE+R^3YY804kprQ>ypv%c+p%Va$}_tsF|-7NDkKZKf)^L@UdE_s!a^vUql|k z44kB8VehnsaO<(@OEQh2$tWmL`Y`O#ZEiycOD`mXH5V?`U^lH1l=~XRXa|gql2yQ8 zPj(*p{gZQ=h~VF$vhiR>X{{@JN7ex;O7bcVx|%!^A~PbwG?vqfPmU~!+DBp_qJyUj z*>o&bI-%+*iL>+LN@yv9oiFx5EquIpBxhRF)j=-e}*rs;vhV zxy49Wo9J@wS))~AaS}c5mv9`~LwNi-Fbv literal 0 HcmV?d00001 From cbd62b398400fcae6c4f7753244396a9aa9689d2 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 7 Apr 2022 10:38:02 -0400 Subject: [PATCH 14/65] fix format --- neo-cli/CLI/MainService.Mode.cs | 8 ++++---- neo-cli/CLI/MainService.cs | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 52c540071..f7830637f 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -49,7 +49,7 @@ private void OnSaveMode(string modeName) var dir = new DirectoryInfo($"./"); // Get the config files of the node - foreach (var file in dir.GetFiles().Where(p=> p.Extension == ".json")) + foreach (var file in dir.GetFiles().Where(p => p.Extension == ".json")) { var targetMode = new DirectoryInfo($"Modes/{modeName}"); // Create the mode if it does not exist @@ -65,7 +65,7 @@ private void OnSaveMode(string modeName) // Save the Plugin files foreach (var plugin in dirs) { - foreach (var file in plugin.GetFiles().Where(p=> p.Extension == ".json")) + foreach (var file in plugin.GetFiles().Where(p => p.Extension == ".json")) { var targetPlugin = new DirectoryInfo($"Modes/{modeName}/{plugin.Name}"); if (!targetPlugin.Exists) Directory.CreateDirectory(targetPlugin.FullName); @@ -85,7 +85,7 @@ private void OnSaveMode(string modeName) } /// - /// Process "plugins" command + /// Process "mode delete" command /// Mode name /// [ConsoleCommand("mode delete", Category = "Mode Commands")] @@ -170,7 +170,7 @@ private static string LoadCurrentMode() // If there is no valid mode, load mainnet as default. mode = sr.ReadLine() ?? mode; } - catch (Exception e) + catch (Exception) { // ignored ConsoleHelper.Error("Mode system is crashed, please reinstall the node"); diff --git a/neo-cli/CLI/MainService.cs b/neo-cli/CLI/MainService.cs index 025f47245..ba6d3fa73 100644 --- a/neo-cli/CLI/MainService.cs +++ b/neo-cli/CLI/MainService.cs @@ -410,7 +410,7 @@ public async void Start(string[] args) case "--mode": case "/mode": { - if (i < args.Length-1) + if (i < args.Length - 1) { i++; // Get all the modes From fd1ec20b42acfaf612d09a7e8b1382d7fc14a8bc Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 7 Apr 2022 10:45:19 -0400 Subject: [PATCH 15/65] fix format....well, no idea where the format issue is --- neo-cli/CLI/MainService.Mode.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index f7830637f..a39b41a08 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2016-2021 The Neo Project. +// Copyright (C) 2016-2021 The Neo Project. // // The neo-cli is free software distributed under the MIT software // license, see the accompanying file LICENSE in the main directory of From 7d5ed7f7b43195b50c78811fe1b614b45b647cc0 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 7 Apr 2022 22:36:06 -0400 Subject: [PATCH 16/65] remove mode file --- neo-cli/CLI/MainService.Mode.cs | 50 +++++---------------------------- neo-cli/CLI/MainService.cs | 7 +++-- neo-cli/Modes/Mode | 1 - 3 files changed, 11 insertions(+), 47 deletions(-) delete mode 100644 neo-cli/Modes/Mode diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index a39b41a08..d3fe58269 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -41,8 +41,12 @@ private void OnListModes() [ConsoleCommand("mode save", Category = "Mode Commands")] private void OnSaveMode(string modeName) { - // if no mode name assigned, save on current mode - modeName ??= LoadCurrentMode(); + // if no mode name assigned + if (modeName is null) + { + ConsoleHelper.Error("No mode name assigned."); + return; + } modeName = modeName.ToLower(); try { @@ -73,8 +77,6 @@ private void OnSaveMode(string modeName) file.CopyTo(targetFilePath, true); } } - // Update the most recent mode - SaveMode(modeName); } catch (Exception e) { @@ -106,11 +108,10 @@ private void OnDeleteMode(string modeName) } } - private static void LoadMode() + private static void LoadMode(string mode) { try { - var mode = LoadCurrentMode(); var dir = new DirectoryInfo($"./Modes/{mode}"); if (!dir.Exists) throw new DirectoryNotFoundException($"Mode not found: {dir.FullName}"); @@ -141,41 +142,4 @@ private static void LoadMode() throw; } } - - private static void SaveMode(string mode) - { - const string path = @"./Modes/Mode"; - mode ??= "mainnet"; - mode = mode.ToLower(); - try - { - // if(File.Exists(path)) File.Delete(path); - using var fs = File.Create(path); - var info = new UTF8Encoding(true).GetBytes(mode); - fs.Write(info, 0, info.Length); - } - catch (Exception ex) - { - Console.WriteLine(ex.ToString()); - } - } - - private static string LoadCurrentMode() - { - const string path = @"./Modes/Mode"; - var mode = "mainnet"; - try - { - using var sr = File.OpenText(path); - // If there is no valid mode, load mainnet as default. - mode = sr.ReadLine() ?? mode; - } - catch (Exception) - { - // ignored - ConsoleHelper.Error("Mode system is crashed, please reinstall the node"); - /// TODO: Maybe allow users to fix it automatically - } - return mode.ToLower(); - } } diff --git a/neo-cli/CLI/MainService.cs b/neo-cli/CLI/MainService.cs index ba6d3fa73..9bf9b3be6 100644 --- a/neo-cli/CLI/MainService.cs +++ b/neo-cli/CLI/MainService.cs @@ -400,6 +400,8 @@ public async void Start(string[] args) { if (NeoSystem != null) return; bool verifyImport = true; + // set mainnet as default mode + string mode = "mainnet"; for (int i = 0; i < args.Length; i++) switch (args[i]) { @@ -418,8 +420,7 @@ public async void Start(string[] args) // Find the expected mode if (modes.Any(p => string.Equals(new DirectoryInfo(p).Name, args[i], StringComparison.CurrentCultureIgnoreCase))) { - // Update the mode file - SaveMode(args[i]); + mode = args[i].ToLower(); } else { @@ -430,7 +431,7 @@ public async void Start(string[] args) break; } // Load the mode (network) - LoadMode(); + LoadMode(mode); _ = new Logger(); ProtocolSettings protocol = ProtocolSettings.Load("config.json"); diff --git a/neo-cli/Modes/Mode b/neo-cli/Modes/Mode deleted file mode 100644 index 15471a593..000000000 --- a/neo-cli/Modes/Mode +++ /dev/null @@ -1 +0,0 @@ -mainnet From 6427f5410ddd19682545a84809baff7c008cd9a6 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 7 Apr 2022 23:08:59 -0400 Subject: [PATCH 17/65] update wallet file --- .../privatenet/NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP.json | 1 + neo-cli/Modes/privatenet/config.json | 6 +++--- neo-cli/Modes/privatenet/private.json | 1 - 3 files changed, 4 insertions(+), 4 deletions(-) create mode 100644 neo-cli/Modes/privatenet/NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP.json delete mode 100644 neo-cli/Modes/privatenet/private.json diff --git a/neo-cli/Modes/privatenet/NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP.json b/neo-cli/Modes/privatenet/NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP.json new file mode 100644 index 000000000..e151b0b0b --- /dev/null +++ b/neo-cli/Modes/privatenet/NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP.json @@ -0,0 +1 @@ +{"extra":{},"scrypt":{"r":8,"p":8,"n":16384,"size":64},"name":"NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP","accounts":[{"address":"NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP","extra":{},"lock":false,"contract":{"script":"DCED7s02MiDW5N55Or\/rrgl3l2hGjFmjtuATKp6jsiAQ99hBVuezJw==","deployed":false,"parameters":[{"name":"signature","type":"signature"}]},"label":"NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP","key":"6PYTrLoLMT1Ms1H2msFTGUDRhHKXsZWA2Lj5rcF2GdPJju1Nuqy4npbef4","isDefault":true}],"version":"1.0"} \ No newline at end of file diff --git a/neo-cli/Modes/privatenet/config.json b/neo-cli/Modes/privatenet/config.json index 1b340e952..2add715bc 100644 --- a/neo-cli/Modes/privatenet/config.json +++ b/neo-cli/Modes/privatenet/config.json @@ -18,8 +18,8 @@ }, "UnlockWallet": { - "Path": "private.json", - "Password": "", + "Path": "NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP.json", + "Password": "12345678", "IsActive": true } }, @@ -33,7 +33,7 @@ "InitialGasDistribution": 5200000000000000, "ValidatorsCount": 1, "StandbyCommittee": [ - "02155400060a3612eba11267fe8acc545f843fe73ebbd3d3781b7ee270f8b882c7" + "03eecd363220d6e4de793abfebae09779768468c59a3b6e0132a9ea3b22010f7d8" ], "SeedList": [] } diff --git a/neo-cli/Modes/privatenet/private.json b/neo-cli/Modes/privatenet/private.json deleted file mode 100644 index 0b51fc2f5..000000000 --- a/neo-cli/Modes/privatenet/private.json +++ /dev/null @@ -1 +0,0 @@ -{"name":null,"version":"1.0","scrypt":{"n":16384,"r":8,"p":8},"accounts":[{"address":"NbNRXrkfMyrEyEv2euE63Xxxqkno7xvuk2","label":null,"isDefault":false,"lock":false,"key":"","contract":{"script":"","parameters":[{"name":"signature","type":"Signature"}],"deployed":false},"extra":null}],"extra":null} From 01daf7788431995b9be804df34c7e0e0cceeb3a1 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Fri, 8 Apr 2022 00:07:22 -0400 Subject: [PATCH 18/65] save config files in a same folder --- neo-cli/CLI/MainService.Mode.cs | 21 ++++++++------------- 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index d3fe58269..506281a62 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -71,10 +71,7 @@ private void OnSaveMode(string modeName) { foreach (var file in plugin.GetFiles().Where(p => p.Extension == ".json")) { - var targetPlugin = new DirectoryInfo($"Modes/{modeName}/{plugin.Name}"); - if (!targetPlugin.Exists) Directory.CreateDirectory(targetPlugin.FullName); - var targetFilePath = Path.Combine(targetPlugin.FullName, file.Name); - file.CopyTo(targetFilePath, true); + file.CopyTo($"Modes/{modeName}/{plugin.Name}.json", true); } } } @@ -122,18 +119,16 @@ private static void LoadMode(string mode) // Get the config files of the node foreach (var file in dir.GetFiles()) { - var targetFilePath = Path.Combine("./", file.Name); - file.CopyTo(targetFilePath, true); - } - - // Copy the Plugin files - foreach (var plugin in dirs) - { - foreach (var file in plugin.GetFiles()) + if (file.Name == "config.json" || file.Name == "config.fs.json") { - var targetFilePath = Path.Combine($"Plugins/{plugin.Name}", file.Name); + var targetFilePath = Path.Combine("./", file.Name); file.CopyTo(targetFilePath, true); } + else + { + var plugin = file.Name.Split('.')[0]; + file.CopyTo($"Plugins/{plugin}/config.json", true); + } } } catch (Exception e) From 8536ff975bcea4336d19e2b55b40762acc3f421f Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Fri, 8 Apr 2022 00:11:37 -0400 Subject: [PATCH 19/65] code optimise --- neo-cli/CLI/MainService.Mode.cs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 506281a62..73b8dd637 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -113,13 +113,10 @@ private static void LoadMode(string mode) if (!dir.Exists) throw new DirectoryNotFoundException($"Mode not found: {dir.FullName}"); - // Cache directories before we start copying - var dirs = dir.GetDirectories(); - // Get the config files of the node foreach (var file in dir.GetFiles()) { - if (file.Name == "config.json" || file.Name == "config.fs.json") + if (file.Name is "config.json" or "config.fs.json") { var targetFilePath = Path.Combine("./", file.Name); file.CopyTo(targetFilePath, true); @@ -127,6 +124,8 @@ private static void LoadMode(string mode) else { var plugin = file.Name.Split('.')[0]; + // if the plugin no longer exists, just ignore it. + if(Directory.Exists($"Plugins/{plugin}/")) continue; file.CopyTo($"Plugins/{plugin}/config.json", true); } } From 4f62c331317d3d514e30df663d17f6da14c17283 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Fri, 8 Apr 2022 00:12:19 -0400 Subject: [PATCH 20/65] fix logic --- neo-cli/CLI/MainService.Mode.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 73b8dd637..8dcea9691 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -125,7 +125,7 @@ private static void LoadMode(string mode) { var plugin = file.Name.Split('.')[0]; // if the plugin no longer exists, just ignore it. - if(Directory.Exists($"Plugins/{plugin}/")) continue; + if(!Directory.Exists($"Plugins/{plugin}/")) continue; file.CopyTo($"Plugins/{plugin}/config.json", true); } } From f41de1ad32b1f5eca09b98ae3f29288e3fbe109a Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Fri, 8 Apr 2022 00:20:28 -0400 Subject: [PATCH 21/65] fix format --- neo-cli/CLI/MainService.Mode.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 8dcea9691..10b0e4746 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -62,7 +62,7 @@ private void OnSaveMode(string modeName) file.CopyTo(targetFilePath, true); } - var plugins = new DirectoryInfo($"./Plugins"); + var plugins = new DirectoryInfo("./Plugins"); // Cache directories before we start copying var dirs = plugins.GetDirectories(); From de3ccd83eb0e11c989487209cd62c471fc2b6bcb Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Fri, 8 Apr 2022 07:40:35 -0400 Subject: [PATCH 22/65] optimise code and solve delete issue --- neo-cli/CLI/MainService.Mode.cs | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 10b0e4746..51e4084c6 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -52,20 +52,19 @@ private void OnSaveMode(string modeName) { var dir = new DirectoryInfo($"./"); + var targetMode = new DirectoryInfo($"Modes/{modeName}"); + // Create the mode if it does not exist + if (!targetMode.Exists) Directory.CreateDirectory(targetMode.FullName); + // Get the config files of the node foreach (var file in dir.GetFiles().Where(p => p.Extension == ".json")) { - var targetMode = new DirectoryInfo($"Modes/{modeName}"); - // Create the mode if it does not exist - if (!targetMode.Exists) Directory.CreateDirectory(targetMode.FullName); var targetFilePath = Path.Combine(targetMode.FullName, file.Name); file.CopyTo(targetFilePath, true); } - var plugins = new DirectoryInfo("./Plugins"); // Cache directories before we start copying var dirs = plugins.GetDirectories(); - // Save the Plugin files foreach (var plugin in dirs) { @@ -80,7 +79,6 @@ private void OnSaveMode(string modeName) Console.WriteLine(e); throw; } - } /// @@ -95,7 +93,7 @@ private void OnDeleteMode(string modeName) var dir = new DirectoryInfo($"Modes/{modeName}"); if (!dir.Exists) return; - Directory.Delete(dir.FullName); + Directory.Delete(dir.FullName,true); ConsoleHelper.Info("Mode ", modeName, " was deleted."); } catch (Exception e) From 6dd88ef7c2512d7f512476a491d4770ce3682ddd Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Fri, 8 Apr 2022 16:08:07 -0400 Subject: [PATCH 23/65] when user install plugin, save the config to the current mode --- neo-cli/CLI/MainService.Mode.cs | 4 ++-- neo-cli/CLI/MainService.Plugins.cs | 3 +++ neo-cli/CLI/MainService.cs | 2 ++ 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 51e4084c6..99795e931 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -93,7 +93,7 @@ private void OnDeleteMode(string modeName) var dir = new DirectoryInfo($"Modes/{modeName}"); if (!dir.Exists) return; - Directory.Delete(dir.FullName,true); + Directory.Delete(dir.FullName, true); ConsoleHelper.Info("Mode ", modeName, " was deleted."); } catch (Exception e) @@ -123,7 +123,7 @@ private static void LoadMode(string mode) { var plugin = file.Name.Split('.')[0]; // if the plugin no longer exists, just ignore it. - if(!Directory.Exists($"Plugins/{plugin}/")) continue; + if (!Directory.Exists($"Plugins/{plugin}/")) continue; file.CopyTo($"Plugins/{plugin}/config.json", true); } } diff --git a/neo-cli/CLI/MainService.Plugins.cs b/neo-cli/CLI/MainService.Plugins.cs index 682213327..709fd9ea2 100644 --- a/neo-cli/CLI/MainService.Plugins.cs +++ b/neo-cli/CLI/MainService.Plugins.cs @@ -61,6 +61,9 @@ private async Task OnInstallCommandAsync(string pluginName) try { zip.ExtractToDirectory("."); + + // _currentMode + File.Copy($"Plugins/{pluginName}/config.json", $"Modes/{_currentMode}/{pluginName}.json", true); ConsoleHelper.Info("Install successful, please restart neo-cli."); } catch (IOException) diff --git a/neo-cli/CLI/MainService.cs b/neo-cli/CLI/MainService.cs index 9bf9b3be6..08c90ede1 100644 --- a/neo-cli/CLI/MainService.cs +++ b/neo-cli/CLI/MainService.cs @@ -49,6 +49,7 @@ public partial class MainService : ConsoleServiceBase, IWalletProvider private Wallet _currentWallet; public LocalNode LocalNode; + private string _currentMode = "mainnet"; public Wallet CurrentWallet { @@ -421,6 +422,7 @@ public async void Start(string[] args) if (modes.Any(p => string.Equals(new DirectoryInfo(p).Name, args[i], StringComparison.CurrentCultureIgnoreCase))) { mode = args[i].ToLower(); + _currentMode = mode; } else { From dd130bbeabd5d0f18655a6c9d4c0a5729e6bf84c Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Fri, 8 Apr 2022 21:33:55 -0400 Subject: [PATCH 24/65] copy plugin config.json to all modes --- neo-cli/CLI/MainService.Plugins.cs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/neo-cli/CLI/MainService.Plugins.cs b/neo-cli/CLI/MainService.Plugins.cs index 709fd9ea2..eb8a168d5 100644 --- a/neo-cli/CLI/MainService.Plugins.cs +++ b/neo-cli/CLI/MainService.Plugins.cs @@ -18,6 +18,7 @@ using System.Net; using System.Net.Http; using System.Threading.Tasks; +using Akka.Util.Internal; namespace Neo.CLI { @@ -63,7 +64,10 @@ private async Task OnInstallCommandAsync(string pluginName) zip.ExtractToDirectory("."); // _currentMode - File.Copy($"Plugins/{pluginName}/config.json", $"Modes/{_currentMode}/{pluginName}.json", true); + Directory.GetDirectories("./Modes/"). + ForEach(p => + File.Copy($"Plugins/{pluginName}/config.json", $"Modes/{new DirectoryInfo(p).Name}/{pluginName}.json", true)); + ConsoleHelper.Info("Install successful, please restart neo-cli."); } catch (IOException) From 27ea359ab4c8e095018498002f73273cdfe971da Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Sat, 9 Apr 2022 13:38:25 -0400 Subject: [PATCH 25/65] Update neo-cli/CLI/MainService.Mode.cs --- neo-cli/CLI/MainService.Mode.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 99795e931..90e7c9ea7 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -1,4 +1,4 @@ -// Copyright (C) 2016-2021 The Neo Project. +// Copyright (C) 2016-2022 The Neo Project. // // The neo-cli is free software distributed under the MIT software // license, see the accompanying file LICENSE in the main directory of From d0c0f302e85ee54b19d70c37d77bbb46686304c8 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Wed, 18 May 2022 09:50:44 -0400 Subject: [PATCH 26/65] update mode system --- neo-cli/CLI/MainService.Mode.cs | 46 ++++++++++++++++++++++-------- neo-cli/CLI/MainService.Plugins.cs | 43 ++++++++++++---------------- 2 files changed, 52 insertions(+), 37 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 90e7c9ea7..4a1f35961 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -13,6 +13,7 @@ using System.IO; using System.Linq; using System.Text; +using System.Threading.Tasks; using Akka.Util.Internal; namespace Neo.CLI; @@ -90,7 +91,7 @@ private void OnDeleteMode(string modeName) { try { - var dir = new DirectoryInfo($"Modes/{modeName}"); + var dir = new DirectoryInfo($"Modes/{modeName.ToLower()}"); if (!dir.Exists) return; Directory.Delete(dir.FullName, true); @@ -103,29 +104,50 @@ private void OnDeleteMode(string modeName) } } - private static void LoadMode(string mode) + /// + /// Load the target mode, plugin should be according to the mode, + /// if the mode contains the plugin, install the plugin, otherwise delete the plugin + /// + /// name of the mode + /// if the mode is not found + private async Task LoadMode(string mode) { try { - var dir = new DirectoryInfo($"./Modes/{mode}"); + var dir = new DirectoryInfo($"./Modes/{mode.ToLower()}"); if (!dir.Exists) throw new DirectoryNotFoundException($"Mode not found: {dir.FullName}"); // Get the config files of the node foreach (var file in dir.GetFiles()) { - if (file.Name is "config.json" or "config.fs.json") + var targetFilePath = Path.Combine("./", file.Name); + file.CopyTo(targetFilePath, true); + } + // Process the plugin + var modePlugins = dir.GetDirectories(); + foreach (var plugin in modePlugins) + { + // if the plugin does not exist, maybe consider install it + if (!Directory.Exists($"Plugins/{plugin}/")) { - var targetFilePath = Path.Combine("./", file.Name); - file.CopyTo(targetFilePath, true); + await InstallPluginAsync(plugin.Name); } - else + + // Get existing plugins and delete them if they are not in the mode + new DirectoryInfo("Plugins/").GetDirectories().ForEach(p => { - var plugin = file.Name.Split('.')[0]; - // if the plugin no longer exists, just ignore it. - if (!Directory.Exists($"Plugins/{plugin}/")) continue; - file.CopyTo($"Plugins/{plugin}/config.json", true); - } + if (modePlugins.Any(k => k.Name == p.Name)) return; + try + { + ConsoleHelper.Info("Removing plugin ", p.Name); + Directory.Delete($"Plugins/{p.Name}", true); + } + catch + { + // ignored + } + }); } } catch (Exception e) diff --git a/neo-cli/CLI/MainService.Plugins.cs b/neo-cli/CLI/MainService.Plugins.cs index cbd041e36..8adb4245d 100644 --- a/neo-cli/CLI/MainService.Plugins.cs +++ b/neo-cli/CLI/MainService.Plugins.cs @@ -1,10 +1,10 @@ -// Copyright (C) 2016-2021 The Neo Project. -// -// The neo-cli is free software distributed under the MIT software +// Copyright (C) 2016-2022 The Neo Project. +// +// The neo-cli is free software distributed under the MIT software // license, see the accompanying file LICENSE in the main directory of -// the project or http://www.opensource.org/licenses/mit-license.php +// the project 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. @@ -143,6 +143,16 @@ private async Task InstallPluginAsync(string pluginName, HashSet install await InstallDependenciesAsync(es, installed); } zip.ExtractToDirectory("./", true); + // Save the config.json to current mode + try + { + // what if the file already exists in the mode? OK, lets overwrite it then. + File.Copy($"Plugins/{pluginName}/config.json", $"Modes/{_currentMode}/{pluginName}/config.json", true); + } + catch + { + // ignored + } } /// @@ -175,7 +185,7 @@ private async Task InstallDependenciesAsync(Stream config, HashSet insta /// private static bool PluginExists(string pluginName) { - return File.Exists($"Plugins/{pluginName}.dll"); + return File.Exists($"Plugins/{pluginName}/{pluginName}.dll"); } /// @@ -229,8 +239,8 @@ private void OnUnInstallCommand(string pluginName) try { - DeleteFiles(new[] { $"Plugins/{pluginName}.dll", $"Plugins/{pluginName}/config.json" }); - Directory.Delete($"Plugins/{pluginName}", false); + // DeleteFiles(new[] { $"Plugins/{pluginName}/{pluginName}.dll", $"Plugins/{pluginName}/config.json" }); + Directory.Delete($"Plugins/{pluginName}", true); } catch (IOException) { @@ -239,23 +249,6 @@ private void OnUnInstallCommand(string pluginName) ConsoleHelper.Info("Uninstall successful, please restart neo-cli."); } - private static void DeleteFiles(IEnumerable list) - { - foreach (var file in list) - { - try - { - if (!File.Exists(file)) continue; - ConsoleHelper.Info("Deleting ", file); - File.Delete(file); - } - catch (Exception) - { - // ignored - } - } - } - /// /// Process "plugins" command /// From fedde51b689978e0321f68005b91c904a3682771 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Sat, 2 Jul 2022 23:10:00 -0400 Subject: [PATCH 27/65] merge master --- neo-cli/CLI/MainService.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/neo-cli/CLI/MainService.cs b/neo-cli/CLI/MainService.cs index 432e95736..597efe427 100644 --- a/neo-cli/CLI/MainService.cs +++ b/neo-cli/CLI/MainService.cs @@ -34,7 +34,6 @@ using System.Reflection; using System.Text.RegularExpressions; using System.Threading; -using Akka.Util.Internal; using Array = System.Array; namespace Neo.CLI @@ -405,9 +404,7 @@ public async void Start(string[] args) break; } // Load the mode (network) - LoadMode(mode); - _ = new Logger(); - + await LoadMode(mode); ProtocolSettings protocol = ProtocolSettings.Load("config.json"); NeoSystem = new NeoSystem(protocol, Settings.Default.Storage.Engine, string.Format(Settings.Default.Storage.Path, protocol.Network.ToString("X8"))); @@ -418,7 +415,6 @@ public async void Start(string[] args) foreach (var plugin in Plugin.Plugins) { // Register plugins commands - RegisterCommand(plugin, plugin.Name); } From 7aac00922c6fe0628f2f556428b21493bd11454a Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 14 Jul 2022 08:18:55 -0400 Subject: [PATCH 28/65] Update neo-cli/CLI/MainService.Mode.cs Co-authored-by: Nicole <43694095+nicolegys@users.noreply.github.com> --- neo-cli/CLI/MainService.Mode.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 4a1f35961..508065ad2 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -129,7 +129,7 @@ private async Task LoadMode(string mode) foreach (var plugin in modePlugins) { // if the plugin does not exist, maybe consider install it - if (!Directory.Exists($"Plugins/{plugin}/")) + if (!Directory.Exists($"Plugins/{plugin.Name}/")) { await InstallPluginAsync(plugin.Name); } From 817bae63c11083f4bd7c8e84855588aabd025342 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 14 Jul 2022 08:41:23 -0400 Subject: [PATCH 29/65] fix issues as nico comments --- neo-cli/CLI/MainService.Mode.cs | 84 ++++++++++++++++++++++++--------- 1 file changed, 62 insertions(+), 22 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 508065ad2..3630a2768 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -58,11 +58,12 @@ private void OnSaveMode(string modeName) if (!targetMode.Exists) Directory.CreateDirectory(targetMode.FullName); // Get the config files of the node - foreach (var file in dir.GetFiles().Where(p => p.Extension == ".json")) - { - var targetFilePath = Path.Combine(targetMode.FullName, file.Name); - file.CopyTo(targetFilePath, true); - } + MoveModeConfig(modeName.ToLower()); + // foreach (var file in dir.GetFiles().Where(p => p.Extension == ".json")) + // { + // var targetFilePath = Path.Combine(targetMode.FullName, file.Name); + // file.CopyTo(targetFilePath, true); + // } var plugins = new DirectoryInfo("./Plugins"); // Cache directories before we start copying var dirs = plugins.GetDirectories(); @@ -110,7 +111,7 @@ private void OnDeleteMode(string modeName) /// /// name of the mode /// if the mode is not found - private async Task LoadMode(string mode) + private Task LoadMode(string mode) { try { @@ -126,28 +127,67 @@ private async Task LoadMode(string mode) } // Process the plugin var modePlugins = dir.GetDirectories(); - foreach (var plugin in modePlugins) + + modePlugins.ForEach(async p => { // if the plugin does not exist, maybe consider install it - if (!Directory.Exists($"Plugins/{plugin.Name}/")) + if (!Directory.Exists($"Plugins/{p.Name}/")) { - await InstallPluginAsync(plugin.Name); + await InstallPluginAsync(p.Name); } + File.Copy($"Modes/{mode.ToLower()}/{p.Name}.json", + $"Plugins/{p.Name}/config.json", true); + }); + MoveModeConfig(mode.ToLower(), false); - // Get existing plugins and delete them if they are not in the mode - new DirectoryInfo("Plugins/").GetDirectories().ForEach(p => + // Get existing plugins and delete them if they are not in the mode + new DirectoryInfo("Plugins/").GetDirectories().ForEach(p => + { + if (modePlugins.Any(k => k.Name == p.Name)) return; + try + { + ConsoleHelper.Info("Removing plugin ", p.Name); + Directory.Delete($"Plugins/{p.Name}", true); + } + catch { - if (modePlugins.Any(k => k.Name == p.Name)) return; - try - { - ConsoleHelper.Info("Removing plugin ", p.Name); - Directory.Delete($"Plugins/{p.Name}", true); - } - catch - { - // ignored - } - }); + // ignored + } + }); + } + catch (Exception e) + { + Console.WriteLine(e); + throw; + } + return Task.CompletedTask; + } + + /// save config.json and config.fs.json to the mode directory + /// name of the mode + /// + /// if the mode is not found + private void MoveModeConfig(string mode, bool toMode=true) + { + var modeDir = new DirectoryInfo($"./Modes/{mode.ToLower()}"); + var configDir = new DirectoryInfo($"./"); + if (!modeDir.Exists) + throw new DirectoryNotFoundException($"Mode not found: {modeDir.FullName}"); + try + { + if (toMode) + { + File.Copy(configDir.FullName + "/config.json", + modeDir.FullName + "/config.json", true); + File.Copy(configDir.FullName + "/config.fs.json", + modeDir.FullName + "/config.fs.json", true); + } + else + { + File.Copy(modeDir.FullName + "/config.json", + configDir.FullName + "/config.json", true); + File.Copy(modeDir.FullName + "/config.fs.json", + configDir.FullName + "/config.fs.json", true); } } catch (Exception e) From 7745c8d4f1b19c1cab2af3f7eac025d55c2d0dfd Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 14 Jul 2022 08:42:42 -0400 Subject: [PATCH 30/65] minor update --- neo-cli/CLI/MainService.Mode.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 3630a2768..59fffe8cf 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -167,10 +167,10 @@ private Task LoadMode(string mode) /// name of the mode /// /// if the mode is not found - private void MoveModeConfig(string mode, bool toMode=true) + private static void MoveModeConfig(string mode, bool toMode=true) { var modeDir = new DirectoryInfo($"./Modes/{mode.ToLower()}"); - var configDir = new DirectoryInfo($"./"); + var configDir = new DirectoryInfo("./"); if (!modeDir.Exists) throw new DirectoryNotFoundException($"Mode not found: {modeDir.FullName}"); try From f921835fe2c583ffec133488f21d9666de88ddbd Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Fri, 15 Jul 2022 00:24:09 -0400 Subject: [PATCH 31/65] fix plugin delete issue --- neo-cli/CLI/MainService.Mode.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 59fffe8cf..2e4940174 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -20,8 +20,7 @@ namespace Neo.CLI; partial class MainService { /// - /// Process "mode list" command - /// Mode name + /// Process "mode list" command. /// [ConsoleCommand("mode list", Category = "Mode Commands")] private void OnListModes() @@ -144,6 +143,7 @@ private Task LoadMode(string mode) new DirectoryInfo("Plugins/").GetDirectories().ForEach(p => { if (modePlugins.Any(k => k.Name == p.Name)) return; + if(!File.Exists($"Plugins/{p.Name}/config.json")) return; try { ConsoleHelper.Info("Removing plugin ", p.Name); From e6e225e20842f8e4f72773ceaea63bdf25763b75 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Mon, 18 Jul 2022 07:40:56 -0400 Subject: [PATCH 32/65] Update neo-cli/CLI/MainService.Mode.cs Co-authored-by: Nicole <43694095+nicolegys@users.noreply.github.com> --- neo-cli/CLI/MainService.Mode.cs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 2e4940174..12f9b5d90 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -118,12 +118,6 @@ private Task LoadMode(string mode) if (!dir.Exists) throw new DirectoryNotFoundException($"Mode not found: {dir.FullName}"); - // Get the config files of the node - foreach (var file in dir.GetFiles()) - { - var targetFilePath = Path.Combine("./", file.Name); - file.CopyTo(targetFilePath, true); - } // Process the plugin var modePlugins = dir.GetDirectories(); From f3fd7aab21ab3da94d308a199387a7532d468f65 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Mon, 18 Jul 2022 07:47:51 -0400 Subject: [PATCH 33/65] fix path issue --- neo-cli/CLI/MainService.Mode.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 12f9b5d90..53357e49e 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -119,7 +119,7 @@ private Task LoadMode(string mode) throw new DirectoryNotFoundException($"Mode not found: {dir.FullName}"); // Process the plugin - var modePlugins = dir.GetDirectories(); + var modePlugins = dir.GetFiles(); modePlugins.ForEach(async p => { From 91eb460720e5036cbc0e8405f1790e6296239fe6 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Mon, 18 Jul 2022 07:50:34 -0400 Subject: [PATCH 34/65] fix format --- neo-cli/CLI/MainService.Mode.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 53357e49e..87a40a7ac 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -126,7 +126,7 @@ private Task LoadMode(string mode) // if the plugin does not exist, maybe consider install it if (!Directory.Exists($"Plugins/{p.Name}/")) { - await InstallPluginAsync(p.Name); + await InstallPluginAsync(p.Name); } File.Copy($"Modes/{mode.ToLower()}/{p.Name}.json", $"Plugins/{p.Name}/config.json", true); @@ -137,7 +137,7 @@ private Task LoadMode(string mode) new DirectoryInfo("Plugins/").GetDirectories().ForEach(p => { if (modePlugins.Any(k => k.Name == p.Name)) return; - if(!File.Exists($"Plugins/{p.Name}/config.json")) return; + if (!File.Exists($"Plugins/{p.Name}/config.json")) return; try { ConsoleHelper.Info("Removing plugin ", p.Name); @@ -161,7 +161,7 @@ private Task LoadMode(string mode) /// name of the mode /// /// if the mode is not found - private static void MoveModeConfig(string mode, bool toMode=true) + private static void MoveModeConfig(string mode, bool toMode = true) { var modeDir = new DirectoryInfo($"./Modes/{mode.ToLower()}"); var configDir = new DirectoryInfo("./"); From fd9203f1ce75f163b8c6a8d9870cd20c6abbc4c3 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Mon, 18 Jul 2022 13:06:23 -0400 Subject: [PATCH 35/65] fix plugin name issue --- neo-cli/CLI/MainService.Mode.cs | 20 +++++++------------- neo-cli/CLI/MainService.Plugins.cs | 9 ++++++--- 2 files changed, 13 insertions(+), 16 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 87a40a7ac..d92fd8695 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -50,19 +50,11 @@ private void OnSaveMode(string modeName) modeName = modeName.ToLower(); try { - var dir = new DirectoryInfo($"./"); - var targetMode = new DirectoryInfo($"Modes/{modeName}"); // Create the mode if it does not exist if (!targetMode.Exists) Directory.CreateDirectory(targetMode.FullName); - // Get the config files of the node MoveModeConfig(modeName.ToLower()); - // foreach (var file in dir.GetFiles().Where(p => p.Extension == ".json")) - // { - // var targetFilePath = Path.Combine(targetMode.FullName, file.Name); - // file.CopyTo(targetFilePath, true); - // } var plugins = new DirectoryInfo("./Plugins"); // Cache directories before we start copying var dirs = plugins.GetDirectories(); @@ -123,20 +115,22 @@ private Task LoadMode(string mode) modePlugins.ForEach(async p => { + var pluginName = Path.GetFileNameWithoutExtension(p.Name); // if the plugin does not exist, maybe consider install it - if (!Directory.Exists($"Plugins/{p.Name}/")) + if (p.Name.Contains("config")) return; + if (!Directory.Exists($"Plugins/{pluginName}/")) { - await InstallPluginAsync(p.Name); + await InstallPluginAsync(pluginName); } - File.Copy($"Modes/{mode.ToLower()}/{p.Name}.json", - $"Plugins/{p.Name}/config.json", true); + File.Copy($"Modes/{mode.ToLower()}/{p.Name}", + $"Plugins/{pluginName}/config.json", true); }); MoveModeConfig(mode.ToLower(), false); // Get existing plugins and delete them if they are not in the mode new DirectoryInfo("Plugins/").GetDirectories().ForEach(p => { - if (modePlugins.Any(k => k.Name == p.Name)) return; + if (modePlugins.Any(k => string.Compare(Path.GetFileNameWithoutExtension(k.Name), p.Name, StringComparison.OrdinalIgnoreCase) == 0)) return; if (!File.Exists($"Plugins/{p.Name}/config.json")) return; try { diff --git a/neo-cli/CLI/MainService.Plugins.cs b/neo-cli/CLI/MainService.Plugins.cs index 86fb564d4..6b5ecb46d 100644 --- a/neo-cli/CLI/MainService.Plugins.cs +++ b/neo-cli/CLI/MainService.Plugins.cs @@ -142,15 +142,17 @@ private async Task InstallPluginAsync(string pluginName, HashSet install await InstallDependenciesAsync(es, installed); } zip.ExtractToDirectory("./", true); + Console.WriteLine(); // Save the config.json to current mode try { // what if the file already exists in the mode? OK, lets overwrite it then. - File.Copy($"Plugins/{pluginName}/config.json", $"Modes/{_currentMode}/{pluginName}/config.json", true); + File.Copy($"Plugins/{pluginName}/config.json", $"Modes/{_currentMode}/{pluginName}.json", true); } - catch + catch (Exception e) { // ignored + Console.WriteLine(e.Message); } } @@ -184,7 +186,8 @@ private async Task InstallDependenciesAsync(Stream config, HashSet insta /// private static bool PluginExists(string pluginName) { - return Plugin.Plugins.Any(p => p.Name.Equals(pluginName, StringComparison.InvariantCultureIgnoreCase)); + return Plugin.Plugins.Any(p => p.Name.Equals(pluginName, StringComparison.InvariantCultureIgnoreCase)) || + new DirectoryInfo("Plugins").GetDirectories().Any(p => p.Name.Equals(pluginName, StringComparison.InvariantCultureIgnoreCase)); } /// From 87feb0f6050570a1fdb85bf29477f25693aefdef Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Wed, 20 Jul 2022 08:48:56 -0400 Subject: [PATCH 36/65] fix config issue while install plugin from the mode --- neo-cli/CLI/MainService.Mode.cs | 6 +++--- neo-cli/CLI/MainService.Plugins.cs | 5 ++++- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index d92fd8695..7c87c0789 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -120,7 +120,7 @@ private Task LoadMode(string mode) if (p.Name.Contains("config")) return; if (!Directory.Exists($"Plugins/{pluginName}/")) { - await InstallPluginAsync(pluginName); + await InstallPluginAsync(pluginName, overWrite:true, saveConfig:false); } File.Copy($"Modes/{mode.ToLower()}/{p.Name}", $"Plugins/{pluginName}/config.json", true); @@ -130,8 +130,8 @@ private Task LoadMode(string mode) // Get existing plugins and delete them if they are not in the mode new DirectoryInfo("Plugins/").GetDirectories().ForEach(p => { - if (modePlugins.Any(k => string.Compare(Path.GetFileNameWithoutExtension(k.Name), p.Name, StringComparison.OrdinalIgnoreCase) == 0)) return; - if (!File.Exists($"Plugins/{p.Name}/config.json")) return; + if (modePlugins.Any(k => string.Compare(Path.GetFileNameWithoutExtension(k.Name), p.Name, StringComparison.OrdinalIgnoreCase) == 0) + || !File.Exists($"Plugins/{p.Name}/config.json")) return; try { ConsoleHelper.Info("Removing plugin ", p.Name); diff --git a/neo-cli/CLI/MainService.Plugins.cs b/neo-cli/CLI/MainService.Plugins.cs index 6b5ecb46d..9feb6b09c 100644 --- a/neo-cli/CLI/MainService.Plugins.cs +++ b/neo-cli/CLI/MainService.Plugins.cs @@ -121,8 +121,9 @@ private async Task DownloadPluginAsync(string pluginName) /// /// name of the plugin /// Install by force for `update` + /// Need to save the config file to the mode private async Task InstallPluginAsync(string pluginName, HashSet installed = null, - bool overWrite = false) + bool overWrite = false, bool saveConfig = true) { installed ??= new HashSet(); if (!installed.Add(pluginName)) return; @@ -143,6 +144,8 @@ private async Task InstallPluginAsync(string pluginName, HashSet install } zip.ExtractToDirectory("./", true); Console.WriteLine(); + + if (!saveConfig) return; // Save the config.json to current mode try { From d30b8d1fbe8d05f988ddc8e51bd11a4bb5e935c9 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Wed, 27 Jul 2022 20:09:53 -0400 Subject: [PATCH 37/65] add warning info --- neo-cli/CLI/MainService.Mode.cs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 7c87c0789..f65c3c589 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -19,6 +19,8 @@ namespace Neo.CLI; partial class MainService { + private bool needRestart = false; + /// /// Process "mode list" command. /// @@ -121,6 +123,7 @@ private Task LoadMode(string mode) if (!Directory.Exists($"Plugins/{pluginName}/")) { await InstallPluginAsync(pluginName, overWrite:true, saveConfig:false); + needRestart = true; } File.Copy($"Modes/{mode.ToLower()}/{p.Name}", $"Plugins/{pluginName}/config.json", true); @@ -136,12 +139,18 @@ private Task LoadMode(string mode) { ConsoleHelper.Info("Removing plugin ", p.Name); Directory.Delete($"Plugins/{p.Name}", true); + needRestart = true; } catch { // ignored } }); + + if (needRestart) + { + ConsoleHelper.Warning("Please restart the node to apply the changes."); + } } catch (Exception e) { From 589488541b6eeaaab364ec001ae0217455aafbd5 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Wed, 27 Jul 2022 20:12:04 -0400 Subject: [PATCH 38/65] stop the node --- neo-cli/CLI/MainService.Mode.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index f65c3c589..eb48abd33 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -150,6 +150,7 @@ private Task LoadMode(string mode) if (needRestart) { ConsoleHelper.Warning("Please restart the node to apply the changes."); + OnStop(); } } catch (Exception e) From f83ab4f0211abe183ed8e1d922aa1f0ac0a9fdb1 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Wed, 27 Jul 2022 20:13:48 -0400 Subject: [PATCH 39/65] rename and remove --- neo-cli/CLI/MainService.Mode.cs | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index eb48abd33..871d5c507 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -8,18 +8,17 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. -using Neo.ConsoleService; using System; using System.IO; using System.Linq; -using System.Text; using System.Threading.Tasks; using Akka.Util.Internal; +using Neo.ConsoleService; namespace Neo.CLI; partial class MainService { - private bool needRestart = false; + private bool _needRestart = false; /// /// Process "mode list" command. @@ -123,7 +122,7 @@ private Task LoadMode(string mode) if (!Directory.Exists($"Plugins/{pluginName}/")) { await InstallPluginAsync(pluginName, overWrite:true, saveConfig:false); - needRestart = true; + _needRestart = true; } File.Copy($"Modes/{mode.ToLower()}/{p.Name}", $"Plugins/{pluginName}/config.json", true); @@ -139,7 +138,7 @@ private Task LoadMode(string mode) { ConsoleHelper.Info("Removing plugin ", p.Name); Directory.Delete($"Plugins/{p.Name}", true); - needRestart = true; + _needRestart = true; } catch { @@ -147,7 +146,7 @@ private Task LoadMode(string mode) } }); - if (needRestart) + if (_needRestart) { ConsoleHelper.Warning("Please restart the node to apply the changes."); OnStop(); From 9af9e0c67d1cd0b191c382400c4216ccdd7294f3 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Tue, 2 Aug 2022 13:08:58 -0400 Subject: [PATCH 40/65] fix async issue --- neo-cli/CLI/MainService.Mode.cs | 9 +-------- neo-cli/CLI/MainService.cs | 8 ++++++++ 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 871d5c507..18bc5cbbb 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -18,7 +18,6 @@ namespace Neo.CLI; partial class MainService { - private bool _needRestart = false; /// /// Process "mode list" command. @@ -121,7 +120,7 @@ private Task LoadMode(string mode) if (p.Name.Contains("config")) return; if (!Directory.Exists($"Plugins/{pluginName}/")) { - await InstallPluginAsync(pluginName, overWrite:true, saveConfig:false); + await InstallPluginAsync(pluginName, overWrite: true, saveConfig: false); _needRestart = true; } File.Copy($"Modes/{mode.ToLower()}/{p.Name}", @@ -145,12 +144,6 @@ private Task LoadMode(string mode) // ignored } }); - - if (_needRestart) - { - ConsoleHelper.Warning("Please restart the node to apply the changes."); - OnStop(); - } } catch (Exception e) { diff --git a/neo-cli/CLI/MainService.cs b/neo-cli/CLI/MainService.cs index 4476e304d..a390fc8b1 100644 --- a/neo-cli/CLI/MainService.cs +++ b/neo-cli/CLI/MainService.cs @@ -47,6 +47,7 @@ public partial class MainService : ConsoleServiceBase, IWalletProvider private Wallet _currentWallet; public LocalNode LocalNode; private string _currentMode = "mainnet"; + private bool _needRestart = false; public Wallet CurrentWallet { @@ -405,6 +406,13 @@ public async void Start(string[] args) } // Load the mode (network) await LoadMode(mode); + if (_needRestart) + { + ConsoleHelper.Warning("Please restart the node to apply the changes."); + OnStop(); + return; + } + ProtocolSettings protocol = ProtocolSettings.Load("config.json"); NeoSystem = new NeoSystem(protocol, Settings.Default.Storage.Engine, string.Format(Settings.Default.Storage.Path, protocol.Network.ToString("X8"))); From d38e39e5515611199f820c22c0a81c4b2d059a2b Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Wed, 10 Aug 2022 16:00:38 -0400 Subject: [PATCH 41/65] in case of duplicly install plugin while loading mode --- neo-cli/CLI/MainService.Mode.cs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 18bc5cbbb..96bb00d77 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -102,7 +102,7 @@ private void OnDeleteMode(string modeName) /// /// name of the mode /// if the mode is not found - private Task LoadMode(string mode) + private async Task LoadMode(string mode) { try { @@ -113,19 +113,21 @@ private Task LoadMode(string mode) // Process the plugin var modePlugins = dir.GetFiles(); - modePlugins.ForEach(async p => + // loop modePlugins + foreach (var plugin in modePlugins) { - var pluginName = Path.GetFileNameWithoutExtension(p.Name); + var pluginName = Path.GetFileNameWithoutExtension(plugin.Name); // if the plugin does not exist, maybe consider install it - if (p.Name.Contains("config")) return; + if (plugin.Name.Contains("config")) continue; if (!Directory.Exists($"Plugins/{pluginName}/")) { await InstallPluginAsync(pluginName, overWrite: true, saveConfig: false); _needRestart = true; } - File.Copy($"Modes/{mode.ToLower()}/{p.Name}", + File.Copy($"Modes/{mode.ToLower()}/{plugin.Name}", $"Plugins/{pluginName}/config.json", true); - }); + } + MoveModeConfig(mode.ToLower(), false); // Get existing plugins and delete them if they are not in the mode @@ -150,7 +152,6 @@ private Task LoadMode(string mode) Console.WriteLine(e); throw; } - return Task.CompletedTask; } /// save config.json and config.fs.json to the mode directory From dd699991116154e1c531acfd6aa1167e589cca84 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 8 Sep 2022 08:15:47 -0400 Subject: [PATCH 42/65] fix case in path --- neo-cli/CLI/Helper.cs | 24 ++++++++++++++++++++++++ neo-cli/CLI/MainService.Plugins.cs | 6 ++++-- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/neo-cli/CLI/Helper.cs b/neo-cli/CLI/Helper.cs index c2f1ccf13..914b46b56 100644 --- a/neo-cli/CLI/Helper.cs +++ b/neo-cli/CLI/Helper.cs @@ -8,6 +8,8 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. +using System.IO; + namespace Neo.CLI { internal static class Helper @@ -22,5 +24,27 @@ public static bool IsYes(this string input) } public static string ToBase64String(this byte[] input) => System.Convert.ToBase64String(input); + + // get the actual case of a path with case-insensitive file system + public static string GetActualPath(string path) + { + if (string.IsNullOrEmpty(path)) + return path; + + var parts = path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); + var actualPath = Directory.GetCurrentDirectory(); + + foreach (var dir in parts) + { + + var dirs = Directory.GetDirectories(actualPath, dir); + if (dirs.Length == 0) + return path; + + actualPath = Path.Combine(actualPath, dirs[0]); + } + + return actualPath; + } } } diff --git a/neo-cli/CLI/MainService.Plugins.cs b/neo-cli/CLI/MainService.Plugins.cs index c1fff7b1a..802cc4710 100644 --- a/neo-cli/CLI/MainService.Plugins.cs +++ b/neo-cli/CLI/MainService.Plugins.cs @@ -149,8 +149,10 @@ private async Task InstallPluginAsync(string pluginName, HashSet install // Save the config.json to current mode try { - // what if the file already exists in the mode? OK, lets overwrite it then. - File.Copy($"Plugins/{pluginName}/config.json", $"Modes/{_currentMode}/{pluginName}.json", true); + var config = Helper.GetActualPath($"Plugins/{pluginName}") + "/config.json"; + if (File.Exists(config)) + // what if the file already exists in the mode? OK, lets overwrite it then. + File.Copy(config, $"Modes/{_currentMode}/{pluginName}.json", true); } catch (Exception e) { From 6a4df3441b3d03029c75d14b28c1939edc6460af Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 8 Sep 2022 09:58:15 -0400 Subject: [PATCH 43/65] add plugin file --- Neo.ConsoleService/ConsoleServiceBase.cs | 9 +++++++- neo-cli/CLI/MainService.Mode.cs | 29 ++++++++++++++++++++---- neo-cli/CLI/MainService.Plugins.cs | 5 ++++ neo-cli/Modes/mainnet/.PLUGINS | 1 + neo-cli/Modes/privatenet/.PLUGINS | 4 ++++ neo-cli/Modes/testnet/.PLUGINS | 1 + 6 files changed, 43 insertions(+), 6 deletions(-) create mode 100644 neo-cli/Modes/mainnet/.PLUGINS create mode 100644 neo-cli/Modes/privatenet/.PLUGINS create mode 100644 neo-cli/Modes/testnet/.PLUGINS diff --git a/Neo.ConsoleService/ConsoleServiceBase.cs b/Neo.ConsoleService/ConsoleServiceBase.cs index d5799b4b6..78680d344 100644 --- a/Neo.ConsoleService/ConsoleServiceBase.cs +++ b/Neo.ConsoleService/ConsoleServiceBase.cs @@ -291,7 +291,14 @@ public virtual void OnStart(string[] args) public virtual void OnStop() { - _shutdownAcknowledged.Signal(); + try + { + _shutdownAcknowledged.Signal(); + } + catch + { + // ignore + } } public string ReadUserInput(string prompt, bool password = false) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 96bb00d77..8286952a7 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -111,20 +111,21 @@ private async Task LoadMode(string mode) throw new DirectoryNotFoundException($"Mode not found: {dir.FullName}"); // Process the plugin - var modePlugins = dir.GetFiles(); + var modePlugins = File.ReadAllLines($"./Modes/{_currentMode}/.PLUGINS"); // loop modePlugins foreach (var plugin in modePlugins) { - var pluginName = Path.GetFileNameWithoutExtension(plugin.Name); + var pluginName = Path.GetFileNameWithoutExtension(plugin); // if the plugin does not exist, maybe consider install it - if (plugin.Name.Contains("config")) continue; + if (plugin.Contains("config")) continue; if (!Directory.Exists($"Plugins/{pluginName}/")) { await InstallPluginAsync(pluginName, overWrite: true, saveConfig: false); _needRestart = true; } - File.Copy($"Modes/{mode.ToLower()}/{plugin.Name}", + if (File.Exists($"Modes/{mode.ToLower()}/{plugin.ToLower()}.json")) + File.Copy($"Modes/{mode.ToLower()}/{plugin}.json", $"Plugins/{pluginName}/config.json", true); } @@ -133,7 +134,7 @@ private async Task LoadMode(string mode) // Get existing plugins and delete them if they are not in the mode new DirectoryInfo("Plugins/").GetDirectories().ForEach(p => { - if (modePlugins.Any(k => string.Compare(Path.GetFileNameWithoutExtension(k.Name), p.Name, StringComparison.OrdinalIgnoreCase) == 0) + if (modePlugins.Any(k => string.Compare(Path.GetFileNameWithoutExtension(k), p.Name, StringComparison.OrdinalIgnoreCase) == 0) || !File.Exists($"Plugins/{p.Name}/config.json")) return; try { @@ -187,4 +188,22 @@ private static void MoveModeConfig(string mode, bool toMode = true) throw; } } + + // Add plugin to .PLUGINS file + private void AddPluginToMode(string pluginName) + { + var plugins = File.ReadAllLines($"./Modes/{_currentMode}/.PLUGINS"); + if (plugins.Contains(pluginName)) return; + var newPlugins = plugins.Append(pluginName).ToArray(); + File.WriteAllLines($"./Modes/{_currentMode}/.PLUGINS", newPlugins); + } + + // Remove plugin from .PLUGINS file + private void RemovePluginFromMode(string pluginName) + { + var plugins = File.ReadAllLines($"./Modes/{_currentMode}/.PLUGINS"); + if (!plugins.Contains(pluginName)) return; + var newPlugins = plugins.Where(p => p != pluginName).ToArray(); + File.WriteAllLines($"./Modes/{_currentMode}/.PLUGINS", newPlugins); + } } diff --git a/neo-cli/CLI/MainService.Plugins.cs b/neo-cli/CLI/MainService.Plugins.cs index 802cc4710..dfa0b631b 100644 --- a/neo-cli/CLI/MainService.Plugins.cs +++ b/neo-cli/CLI/MainService.Plugins.cs @@ -153,6 +153,7 @@ private async Task InstallPluginAsync(string pluginName, HashSet install if (File.Exists(config)) // what if the file already exists in the mode? OK, lets overwrite it then. File.Copy(config, $"Modes/{_currentMode}/{pluginName}.json", true); + AddPluginToMode(pluginName); } catch (Exception e) { @@ -234,6 +235,10 @@ private void OnUnInstallCommand(string pluginName) try { Directory.Delete($"Plugins/{pluginName}", true); + var config = $"Modes/{_currentMode}/{pluginName}.json"; + if (File.Exists(config)) + File.Delete(config); + RemovePluginFromMode(pluginName); } catch (IOException) { } ConsoleHelper.Info("Uninstall successful, please restart neo-cli."); diff --git a/neo-cli/Modes/mainnet/.PLUGINS b/neo-cli/Modes/mainnet/.PLUGINS new file mode 100644 index 000000000..3e16d9f30 --- /dev/null +++ b/neo-cli/Modes/mainnet/.PLUGINS @@ -0,0 +1 @@ +LevelDBStore diff --git a/neo-cli/Modes/privatenet/.PLUGINS b/neo-cli/Modes/privatenet/.PLUGINS new file mode 100644 index 000000000..61c2a05da --- /dev/null +++ b/neo-cli/Modes/privatenet/.PLUGINS @@ -0,0 +1,4 @@ +LevelDBStore +RpcServer +ApplicationLogs +DBFTPlugin diff --git a/neo-cli/Modes/testnet/.PLUGINS b/neo-cli/Modes/testnet/.PLUGINS new file mode 100644 index 000000000..3e16d9f30 --- /dev/null +++ b/neo-cli/Modes/testnet/.PLUGINS @@ -0,0 +1 @@ +LevelDBStore From 2a98ccb38d1a429ccebf02dbf194bce15c66c262 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 8 Sep 2022 10:06:10 -0400 Subject: [PATCH 44/65] on create new mode --- Neo.ConsoleService/ConsoleServiceBase.cs | 2 +- neo-cli/CLI/MainService.Mode.cs | 15 +++++++++------ neo-cli/CLI/MainService.Plugins.cs | 4 ++-- neo-cli/CLI/MainService.cs | 2 +- 4 files changed, 13 insertions(+), 10 deletions(-) diff --git a/Neo.ConsoleService/ConsoleServiceBase.cs b/Neo.ConsoleService/ConsoleServiceBase.cs index 78680d344..6277c7f86 100644 --- a/Neo.ConsoleService/ConsoleServiceBase.cs +++ b/Neo.ConsoleService/ConsoleServiceBase.cs @@ -297,7 +297,7 @@ public virtual void OnStop() } catch { - // ignore + // ignore } } diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 8286952a7..ebd5f045d 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -58,6 +58,8 @@ private void OnSaveMode(string modeName) var plugins = new DirectoryInfo("./Plugins"); // Cache directories before we start copying var dirs = plugins.GetDirectories(); + // Create an empty .PLUGINS file + File.Create($"Modes/{modeName}/.PLUGINS").Close(); // Save the Plugin files foreach (var plugin in dirs) { @@ -65,6 +67,7 @@ private void OnSaveMode(string modeName) { file.CopyTo($"Modes/{modeName}/{plugin.Name}.json", true); } + AddPluginToMode(plugin.Name, modeName); } } catch (Exception e) @@ -190,20 +193,20 @@ private static void MoveModeConfig(string mode, bool toMode = true) } // Add plugin to .PLUGINS file - private void AddPluginToMode(string pluginName) + private void AddPluginToMode(string pluginName, string modeName) { - var plugins = File.ReadAllLines($"./Modes/{_currentMode}/.PLUGINS"); + var plugins = File.ReadAllLines($"./Modes/{modeName}/.PLUGINS"); if (plugins.Contains(pluginName)) return; var newPlugins = plugins.Append(pluginName).ToArray(); - File.WriteAllLines($"./Modes/{_currentMode}/.PLUGINS", newPlugins); + File.WriteAllLines($"./Modes/{modeName}/.PLUGINS", newPlugins); } // Remove plugin from .PLUGINS file - private void RemovePluginFromMode(string pluginName) + private void RemovePluginFromMode(string pluginName, string modeName) { - var plugins = File.ReadAllLines($"./Modes/{_currentMode}/.PLUGINS"); + var plugins = File.ReadAllLines($"./Modes/{modeName}/.PLUGINS"); if (!plugins.Contains(pluginName)) return; var newPlugins = plugins.Where(p => p != pluginName).ToArray(); - File.WriteAllLines($"./Modes/{_currentMode}/.PLUGINS", newPlugins); + File.WriteAllLines($"./Modes/{modeName}/.PLUGINS", newPlugins); } } diff --git a/neo-cli/CLI/MainService.Plugins.cs b/neo-cli/CLI/MainService.Plugins.cs index dfa0b631b..217d1990a 100644 --- a/neo-cli/CLI/MainService.Plugins.cs +++ b/neo-cli/CLI/MainService.Plugins.cs @@ -153,7 +153,7 @@ private async Task InstallPluginAsync(string pluginName, HashSet install if (File.Exists(config)) // what if the file already exists in the mode? OK, lets overwrite it then. File.Copy(config, $"Modes/{_currentMode}/{pluginName}.json", true); - AddPluginToMode(pluginName); + AddPluginToMode(pluginName, _currentMode); } catch (Exception e) { @@ -238,7 +238,7 @@ private void OnUnInstallCommand(string pluginName) var config = $"Modes/{_currentMode}/{pluginName}.json"; if (File.Exists(config)) File.Delete(config); - RemovePluginFromMode(pluginName); + RemovePluginFromMode(pluginName, _currentMode); } catch (IOException) { } ConsoleHelper.Info("Uninstall successful, please restart neo-cli."); diff --git a/neo-cli/CLI/MainService.cs b/neo-cli/CLI/MainService.cs index c8285910c..df13892bb 100644 --- a/neo-cli/CLI/MainService.cs +++ b/neo-cli/CLI/MainService.cs @@ -46,7 +46,7 @@ public partial class MainService : ConsoleServiceBase, IWalletProvider private Wallet _currentWallet; public LocalNode LocalNode; - private string _currentMode = "mainnet"; + private static string _currentMode = "mainnet"; private bool _needRestart = false; public Wallet CurrentWallet From f5f6b8a062699462f96531cc934f7d5baf40388d Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 8 Sep 2022 13:45:37 -0400 Subject: [PATCH 45/65] add oracle mode --- neo-cli/Modes/oracle/.PLUGINS | 3 ++ neo-cli/Modes/oracle/config.fs.json | 53 +++++++++++++++++++ neo-cli/Modes/oracle/config.json | 68 +++++++++++++++++++++++++ neo-cli/Modes/oracle/oracleservice.json | 26 ++++++++++ neo-cli/neo-cli.csproj | 6 --- 5 files changed, 150 insertions(+), 6 deletions(-) create mode 100644 neo-cli/Modes/oracle/.PLUGINS create mode 100644 neo-cli/Modes/oracle/config.fs.json create mode 100644 neo-cli/Modes/oracle/config.json create mode 100644 neo-cli/Modes/oracle/oracleservice.json diff --git a/neo-cli/Modes/oracle/.PLUGINS b/neo-cli/Modes/oracle/.PLUGINS new file mode 100644 index 000000000..c0dfda6b2 --- /dev/null +++ b/neo-cli/Modes/oracle/.PLUGINS @@ -0,0 +1,3 @@ +LevelDBStore +RpcServer +OracleService diff --git a/neo-cli/Modes/oracle/config.fs.json b/neo-cli/Modes/oracle/config.fs.json new file mode 100644 index 000000000..94fb94a2a --- /dev/null +++ b/neo-cli/Modes/oracle/config.fs.json @@ -0,0 +1,53 @@ +{ + "ApplicationConfiguration": { + "Logger": { + "Path": "Logs", + "ConsoleOutput": false, + "Active": false + }, + "Storage": { + "Engine": "LevelDBStore", + "Path": "Data_LevelDB_{0}" + }, + "P2P": { + "Port": 40333, + "WsPort": 40334, + "MinDesiredConnections": 10, + "MaxConnections": 40, + "MaxConnectionsPerAddress": 3 + }, + "UnlockWallet": { + "Path": "", + "Password": "", + "IsActive": false + } + }, + "ProtocolConfiguration": { + "Network": 91414437, + "AddressVersion": 53, + "MillisecondsPerBlock": 15000, + "MaxTransactionsPerBlock": 512, + "MemoryPoolMaxTransactions": 50000, + "MaxTraceableBlocks": 2102400, + "InitialGasDistribution": 5200000000000000, + "ValidatorsCount": 7, + "StandbyCommittee": [ + "026fa34ec057d74c2fdf1a18e336d0bd597ea401a0b2ad57340d5c220d09f44086", + "039a9db2a30942b1843db673aeb0d4fd6433f74cec1d879de6343cb9fcf7628fa4", + "0366d255e7ce23ea6f7f1e4bedf5cbafe598705b47e6ec213ef13b2f0819e8ab33", + "023f9cb7bbe154d529d5c719fdc39feaa831a43ae03d2a4280575b60f52fa7bc52", + "039ba959e0ab6dc616df8b803692f1c30ba9071b76b05535eb994bf5bbc402ad5f", + "035a2a18cddafa25ad353dea5e6730a1b9fcb4b918c4a0303c4387bb9c3b816adf", + "031f4d9c66f2ec348832c48fd3a16dfaeb59e85f557ae1e07f6696d0375c64f97b" + ], + "SeedList": [ + "morph1.fs.neo.org:40333", + "morph2.fs.neo.org:40333", + "morph3.fs.neo.org:40333", + "morph4.fs.neo.org:40333", + "morph5.fs.neo.org:40333", + "morph6.fs.neo.org:40333", + "morph7.fs.neo.org:40333" + ] + } +} diff --git a/neo-cli/Modes/oracle/config.json b/neo-cli/Modes/oracle/config.json new file mode 100644 index 000000000..1c1e0aaa9 --- /dev/null +++ b/neo-cli/Modes/oracle/config.json @@ -0,0 +1,68 @@ +{ + "ApplicationConfiguration": { + "Logger": { + "Path": "Logs", + "ConsoleOutput": false, + "Active": false + }, + "Storage": { + "Engine": "LevelDBStore", + "Path": "Data_LevelDB_{0}" + }, + "P2P": { + "Port": 10333, + "WsPort": 10334, + "MinDesiredConnections": 10, + "MaxConnections": 40, + "MaxConnectionsPerAddress": 3 + }, + "UnlockWallet": { + "Path": "", + "Password": "", + "IsActive": false + } + }, + "ProtocolConfiguration": { + "Network": 860833102, + "AddressVersion": 53, + "MillisecondsPerBlock": 15000, + "MaxTransactionsPerBlock": 512, + "MemoryPoolMaxTransactions": 50000, + "MaxTraceableBlocks": 2102400, + "Hardforks": { + "HF_Aspidochelone": 1730000 + }, + "InitialGasDistribution": 5200000000000000, + "ValidatorsCount": 7, + "StandbyCommittee": [ + "03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c", + "02df48f60e8f3e01c48ff40b9b7f1310d7a8b2a193188befe1c2e3df740e895093", + "03b8d9d5771d8f513aa0869b9cc8d50986403b78c6da36890638c3d46a5adce04a", + "02ca0e27697b9c248f6f16e085fd0061e26f44da85b58ee835c110caa5ec3ba554", + "024c7b7fb6c310fccf1ba33b082519d82964ea93868d676662d4a59ad548df0e7d", + "02aaec38470f6aad0042c6e877cfd8087d2676b0f516fddd362801b9bd3936399e", + "02486fd15702c4490a26703112a5cc1d0923fd697a33406bd5a1c00e0013b09a70", + "023a36c72844610b4d34d1968662424011bf783ca9d984efa19a20babf5582f3fe", + "03708b860c1de5d87f5b151a12c2a99feebd2e8b315ee8e7cf8aa19692a9e18379", + "03c6aa6e12638b36e88adc1ccdceac4db9929575c3e03576c617c49cce7114a050", + "03204223f8c86b8cd5c89ef12e4f0dbb314172e9241e30c9ef2293790793537cf0", + "02a62c915cf19c7f19a50ec217e79fac2439bbaad658493de0c7d8ffa92ab0aa62", + "03409f31f0d66bdc2f70a9730b66fe186658f84a8018204db01c106edc36553cd0", + "0288342b141c30dc8ffcde0204929bb46aed5756b41ef4a56778d15ada8f0c6654", + "020f2887f41474cfeb11fd262e982051c1541418137c02a0f4961af911045de639", + "0222038884bbd1d8ff109ed3bdef3542e768eef76c1247aea8bc8171f532928c30", + "03d281b42002647f0113f36c7b8efb30db66078dfaaa9ab3ff76d043a98d512fde", + "02504acbc1f4b3bdad1d86d6e1a08603771db135a73e61c9d565ae06a1938cd2ad", + "0226933336f1b75baa42d42b71d9091508b638046d19abd67f4e119bf64a7cfb4d", + "03cdcea66032b82f5c30450e381e5295cae85c5e6943af716cc6b646352a6067dc", + "02cd5a5547119e24feaa7c2a0f37b8c9366216bab7054de0065c9be42084003c8a" + ], + "SeedList": [ + "seed1.neo.org:10333", + "seed2.neo.org:10333", + "seed3.neo.org:10333", + "seed4.neo.org:10333", + "seed5.neo.org:10333" + ] + } +} diff --git a/neo-cli/Modes/oracle/oracleservice.json b/neo-cli/Modes/oracle/oracleservice.json new file mode 100644 index 000000000..db7624545 --- /dev/null +++ b/neo-cli/Modes/oracle/oracleservice.json @@ -0,0 +1,26 @@ +{ + "PluginConfiguration": { + "Network": 860833102, + "Nodes": [ + "http://oracle1.ngd.network:10332", + "http://oracle2.ngd.network:10332", + "http://oracle3.ngd.network:10332", + "http://oracle.n3.nspcc.ru:10332" + ], + "MaxTaskTimeout": 432000000, + "MaxOracleTimeout": 10000, + "AllowPrivateHost": false, + "AllowedContentTypes": [ "application/json" ], + "Https": { + "Timeout": 10000 + }, + "NeoFS": { + "EndPoint": "http://st1.t5.fs.neo.org:8080", + "Timeout": 15000 + }, + "AutoStart": true + }, + "Dependency": [ + "RpcServer" + ] +} diff --git a/neo-cli/neo-cli.csproj b/neo-cli/neo-cli.csproj index 0ecb5f23e..9098e31c7 100644 --- a/neo-cli/neo-cli.csproj +++ b/neo-cli/neo-cli.csproj @@ -16,12 +16,6 @@ neo.ico - PreserveNewest From e73a42c712ebe29ad879d74c856b1f3bed625aba Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 8 Sep 2022 15:38:37 -0400 Subject: [PATCH 46/65] try to fix cpytofolder --- neo-cli/neo-cli.csproj | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/neo-cli/neo-cli.csproj b/neo-cli/neo-cli.csproj index 9098e31c7..a4b3f39d2 100644 --- a/neo-cli/neo-cli.csproj +++ b/neo-cli/neo-cli.csproj @@ -17,12 +17,14 @@ - - PreserveNewest - Modes\%(RecursiveDir)\%(Filename)%(Extension) - + + PreserveNewest + Modes\%(RecursiveDir)\%(Filename)%(Extension) + + + From ef186442e0a24fa19f92b5ff2395ca3541eb5ab0 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 8 Sep 2022 15:58:37 -0400 Subject: [PATCH 47/65] fix mode load issue --- neo-cli/CLI/MainService.Mode.cs | 18 +++++------ neo-cli/config.fs.json | 53 +++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 9 deletions(-) create mode 100644 neo-cli/config.fs.json diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index ebd5f045d..aca98cc39 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -109,7 +109,8 @@ private async Task LoadMode(string mode) { try { - var dir = new DirectoryInfo($"./Modes/{mode.ToLower()}"); + mode = mode.ToLower(); + var dir = new DirectoryInfo($"./Modes/{mode}"); if (!dir.Exists) throw new DirectoryNotFoundException($"Mode not found: {dir.FullName}"); @@ -117,22 +118,21 @@ private async Task LoadMode(string mode) var modePlugins = File.ReadAllLines($"./Modes/{_currentMode}/.PLUGINS"); // loop modePlugins - foreach (var plugin in modePlugins) + foreach (var pluginName in modePlugins) { - var pluginName = Path.GetFileNameWithoutExtension(plugin); - // if the plugin does not exist, maybe consider install it - if (plugin.Contains("config")) continue; + // if the plugin is not installed, install it if (!Directory.Exists($"Plugins/{pluginName}/")) { await InstallPluginAsync(pluginName, overWrite: true, saveConfig: false); _needRestart = true; } - if (File.Exists($"Modes/{mode.ToLower()}/{plugin.ToLower()}.json")) - File.Copy($"Modes/{mode.ToLower()}/{plugin}.json", + // if the mode has the plugin config, load the config from the mode + if (File.Exists($"Modes/{mode}/{pluginName}.json")) + File.Copy($"Modes/{mode}/{pluginName}.json", $"Plugins/{pluginName}/config.json", true); } - - MoveModeConfig(mode.ToLower(), false); + // get the system config file from the mode + MoveModeConfig(mode, false); // Get existing plugins and delete them if they are not in the mode new DirectoryInfo("Plugins/").GetDirectories().ForEach(p => diff --git a/neo-cli/config.fs.json b/neo-cli/config.fs.json new file mode 100644 index 000000000..94fb94a2a --- /dev/null +++ b/neo-cli/config.fs.json @@ -0,0 +1,53 @@ +{ + "ApplicationConfiguration": { + "Logger": { + "Path": "Logs", + "ConsoleOutput": false, + "Active": false + }, + "Storage": { + "Engine": "LevelDBStore", + "Path": "Data_LevelDB_{0}" + }, + "P2P": { + "Port": 40333, + "WsPort": 40334, + "MinDesiredConnections": 10, + "MaxConnections": 40, + "MaxConnectionsPerAddress": 3 + }, + "UnlockWallet": { + "Path": "", + "Password": "", + "IsActive": false + } + }, + "ProtocolConfiguration": { + "Network": 91414437, + "AddressVersion": 53, + "MillisecondsPerBlock": 15000, + "MaxTransactionsPerBlock": 512, + "MemoryPoolMaxTransactions": 50000, + "MaxTraceableBlocks": 2102400, + "InitialGasDistribution": 5200000000000000, + "ValidatorsCount": 7, + "StandbyCommittee": [ + "026fa34ec057d74c2fdf1a18e336d0bd597ea401a0b2ad57340d5c220d09f44086", + "039a9db2a30942b1843db673aeb0d4fd6433f74cec1d879de6343cb9fcf7628fa4", + "0366d255e7ce23ea6f7f1e4bedf5cbafe598705b47e6ec213ef13b2f0819e8ab33", + "023f9cb7bbe154d529d5c719fdc39feaa831a43ae03d2a4280575b60f52fa7bc52", + "039ba959e0ab6dc616df8b803692f1c30ba9071b76b05535eb994bf5bbc402ad5f", + "035a2a18cddafa25ad353dea5e6730a1b9fcb4b918c4a0303c4387bb9c3b816adf", + "031f4d9c66f2ec348832c48fd3a16dfaeb59e85f557ae1e07f6696d0375c64f97b" + ], + "SeedList": [ + "morph1.fs.neo.org:40333", + "morph2.fs.neo.org:40333", + "morph3.fs.neo.org:40333", + "morph4.fs.neo.org:40333", + "morph5.fs.neo.org:40333", + "morph6.fs.neo.org:40333", + "morph7.fs.neo.org:40333" + ] + } +} From ced9cc32d8a2dfee378a9822a21b5c34a6f8d1d7 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 8 Sep 2022 16:02:19 -0400 Subject: [PATCH 48/65] udpate the expect --- .github/workflows/test-neo-cli.expect | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.github/workflows/test-neo-cli.expect b/.github/workflows/test-neo-cli.expect index dbf41526b..3705377fc 100755 --- a/.github/workflows/test-neo-cli.expect +++ b/.github/workflows/test-neo-cli.expect @@ -7,6 +7,16 @@ set timeout 10 # Start neo-cli spawn dotnet out/neo-cli.dll +# Expect the main input prompt +expect { + "neo> " { send "exit\n"} + "error" { exit 2 } + timeout { exit 1 } +} + +# ReStart neo-cli +spawn dotnet out/neo-cli.dll + # Expect the main input prompt expect { "neo> " { } From 1056ec2921fa69afb7c3881c1bf4103e4f0ec84f Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 8 Sep 2022 16:06:42 -0400 Subject: [PATCH 49/65] Revert "udpate the expect" This reverts commit ced9cc32d8a2dfee378a9822a21b5c34a6f8d1d7. --- .github/workflows/test-neo-cli.expect | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/.github/workflows/test-neo-cli.expect b/.github/workflows/test-neo-cli.expect index 3705377fc..dbf41526b 100755 --- a/.github/workflows/test-neo-cli.expect +++ b/.github/workflows/test-neo-cli.expect @@ -7,16 +7,6 @@ set timeout 10 # Start neo-cli spawn dotnet out/neo-cli.dll -# Expect the main input prompt -expect { - "neo> " { send "exit\n"} - "error" { exit 2 } - timeout { exit 1 } -} - -# ReStart neo-cli -spawn dotnet out/neo-cli.dll - # Expect the main input prompt expect { "neo> " { } From e33c8683e2544a24c8beaf1002836c5c35f6011e Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 15 Sep 2022 09:44:05 -0400 Subject: [PATCH 50/65] fix plugin name case issue --- neo-cli/CLI/Helper.cs | 22 ---------------------- neo-cli/CLI/MainService.Mode.cs | 6 ++---- neo-cli/CLI/MainService.Plugins.cs | 15 +++++++++++---- 3 files changed, 13 insertions(+), 30 deletions(-) diff --git a/neo-cli/CLI/Helper.cs b/neo-cli/CLI/Helper.cs index 914b46b56..94297cc40 100644 --- a/neo-cli/CLI/Helper.cs +++ b/neo-cli/CLI/Helper.cs @@ -24,27 +24,5 @@ public static bool IsYes(this string input) } public static string ToBase64String(this byte[] input) => System.Convert.ToBase64String(input); - - // get the actual case of a path with case-insensitive file system - public static string GetActualPath(string path) - { - if (string.IsNullOrEmpty(path)) - return path; - - var parts = path.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); - var actualPath = Directory.GetCurrentDirectory(); - - foreach (var dir in parts) - { - - var dirs = Directory.GetDirectories(actualPath, dir); - if (dirs.Length == 0) - return path; - - actualPath = Path.Combine(actualPath, dirs[0]); - } - - return actualPath; - } } } diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index aca98cc39..269f91fc7 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -113,10 +113,8 @@ private async Task LoadMode(string mode) var dir = new DirectoryInfo($"./Modes/{mode}"); if (!dir.Exists) throw new DirectoryNotFoundException($"Mode not found: {dir.FullName}"); - // Process the plugin var modePlugins = File.ReadAllLines($"./Modes/{_currentMode}/.PLUGINS"); - // loop modePlugins foreach (var pluginName in modePlugins) { @@ -205,8 +203,8 @@ private void AddPluginToMode(string pluginName, string modeName) private void RemovePluginFromMode(string pluginName, string modeName) { var plugins = File.ReadAllLines($"./Modes/{modeName}/.PLUGINS"); - if (!plugins.Contains(pluginName)) return; - var newPlugins = plugins.Where(p => p != pluginName).ToArray(); + // if (plugins.All(p => !string.Equals(p, pluginName, StringComparison.CurrentCultureIgnoreCase))) return; + var newPlugins = plugins.Where(p => !string.Equals(p, pluginName, StringComparison.CurrentCultureIgnoreCase)).ToArray(); File.WriteAllLines($"./Modes/{modeName}/.PLUGINS", newPlugins); } } diff --git a/neo-cli/CLI/MainService.Plugins.cs b/neo-cli/CLI/MainService.Plugins.cs index 217d1990a..2aa4a16c5 100644 --- a/neo-cli/CLI/MainService.Plugins.cs +++ b/neo-cli/CLI/MainService.Plugins.cs @@ -149,11 +149,18 @@ private async Task InstallPluginAsync(string pluginName, HashSet install // Save the config.json to current mode try { - var config = Helper.GetActualPath($"Plugins/{pluginName}") + "/config.json"; - if (File.Exists(config)) + var pluginActualName=""; + foreach (var plugin in new DirectoryInfo("./Plugins").GetDirectories()) + { + if (plugin.Name.ToLower() != pluginName.ToLower()) continue; + pluginActualName = plugin.Name; + break; + } + + if (File.Exists($"Plugins/{pluginActualName}/config.json")) // what if the file already exists in the mode? OK, lets overwrite it then. - File.Copy(config, $"Modes/{_currentMode}/{pluginName}.json", true); - AddPluginToMode(pluginName, _currentMode); + File.Copy($"Plugins/{pluginActualName}/config.json", $"Modes/{_currentMode}/{pluginActualName}.json", true); + AddPluginToMode(pluginActualName, _currentMode); } catch (Exception e) { From 5dad265035b5d2f6c0987820136ab69fe0a21af4 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Wed, 21 Sep 2022 08:19:53 -0700 Subject: [PATCH 51/65] fix plugin name case issue and remove oracle mode --- neo-cli/CLI/MainService.Plugins.cs | 24 +++++---- neo-cli/Modes/oracle/.PLUGINS | 3 -- neo-cli/Modes/oracle/config.fs.json | 53 ------------------- neo-cli/Modes/oracle/config.json | 68 ------------------------- neo-cli/Modes/oracle/oracleservice.json | 26 ---------- 5 files changed, 15 insertions(+), 159 deletions(-) delete mode 100644 neo-cli/Modes/oracle/.PLUGINS delete mode 100644 neo-cli/Modes/oracle/config.fs.json delete mode 100644 neo-cli/Modes/oracle/config.json delete mode 100644 neo-cli/Modes/oracle/oracleservice.json diff --git a/neo-cli/CLI/MainService.Plugins.cs b/neo-cli/CLI/MainService.Plugins.cs index 2aa4a16c5..1e23fa9a9 100644 --- a/neo-cli/CLI/MainService.Plugins.cs +++ b/neo-cli/CLI/MainService.Plugins.cs @@ -120,6 +120,7 @@ private async Task DownloadPluginAsync(string pluginName) /// Install plugin from stream /// /// name of the plugin + /// installed dependency /// Install by force for `update` /// Need to save the config file to the mode private async Task InstallPluginAsync(string pluginName, HashSet installed = null, @@ -149,14 +150,7 @@ private async Task InstallPluginAsync(string pluginName, HashSet install // Save the config.json to current mode try { - var pluginActualName=""; - foreach (var plugin in new DirectoryInfo("./Plugins").GetDirectories()) - { - if (plugin.Name.ToLower() != pluginName.ToLower()) continue; - pluginActualName = plugin.Name; - break; - } - + var pluginActualName = GetPluginActualName(pluginName); if (File.Exists($"Plugins/{pluginActualName}/config.json")) // what if the file already exists in the mode? OK, lets overwrite it then. File.Copy($"Plugins/{pluginActualName}/config.json", $"Modes/{_currentMode}/{pluginActualName}.json", true); @@ -215,7 +209,7 @@ private void OnUnInstallCommand(string pluginName) ConsoleHelper.Warning("Plugin not found"); return; } - + pluginName = GetPluginActualName(pluginName); foreach (var p in Plugin.Plugins) { try @@ -271,5 +265,17 @@ private void OnPluginsCommand() ConsoleHelper.Warning("No loaded plugins"); } } + + private static string GetPluginActualName(string pluginName) + { + var pluginActualName=""; + foreach (var plugin in new DirectoryInfo("./Plugins").GetDirectories()) + { + if (!string.Equals(plugin.Name, pluginName, StringComparison.CurrentCultureIgnoreCase)) continue; + pluginActualName = plugin.Name; + break; + } + return pluginActualName; + } } } diff --git a/neo-cli/Modes/oracle/.PLUGINS b/neo-cli/Modes/oracle/.PLUGINS deleted file mode 100644 index c0dfda6b2..000000000 --- a/neo-cli/Modes/oracle/.PLUGINS +++ /dev/null @@ -1,3 +0,0 @@ -LevelDBStore -RpcServer -OracleService diff --git a/neo-cli/Modes/oracle/config.fs.json b/neo-cli/Modes/oracle/config.fs.json deleted file mode 100644 index 94fb94a2a..000000000 --- a/neo-cli/Modes/oracle/config.fs.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "ApplicationConfiguration": { - "Logger": { - "Path": "Logs", - "ConsoleOutput": false, - "Active": false - }, - "Storage": { - "Engine": "LevelDBStore", - "Path": "Data_LevelDB_{0}" - }, - "P2P": { - "Port": 40333, - "WsPort": 40334, - "MinDesiredConnections": 10, - "MaxConnections": 40, - "MaxConnectionsPerAddress": 3 - }, - "UnlockWallet": { - "Path": "", - "Password": "", - "IsActive": false - } - }, - "ProtocolConfiguration": { - "Network": 91414437, - "AddressVersion": 53, - "MillisecondsPerBlock": 15000, - "MaxTransactionsPerBlock": 512, - "MemoryPoolMaxTransactions": 50000, - "MaxTraceableBlocks": 2102400, - "InitialGasDistribution": 5200000000000000, - "ValidatorsCount": 7, - "StandbyCommittee": [ - "026fa34ec057d74c2fdf1a18e336d0bd597ea401a0b2ad57340d5c220d09f44086", - "039a9db2a30942b1843db673aeb0d4fd6433f74cec1d879de6343cb9fcf7628fa4", - "0366d255e7ce23ea6f7f1e4bedf5cbafe598705b47e6ec213ef13b2f0819e8ab33", - "023f9cb7bbe154d529d5c719fdc39feaa831a43ae03d2a4280575b60f52fa7bc52", - "039ba959e0ab6dc616df8b803692f1c30ba9071b76b05535eb994bf5bbc402ad5f", - "035a2a18cddafa25ad353dea5e6730a1b9fcb4b918c4a0303c4387bb9c3b816adf", - "031f4d9c66f2ec348832c48fd3a16dfaeb59e85f557ae1e07f6696d0375c64f97b" - ], - "SeedList": [ - "morph1.fs.neo.org:40333", - "morph2.fs.neo.org:40333", - "morph3.fs.neo.org:40333", - "morph4.fs.neo.org:40333", - "morph5.fs.neo.org:40333", - "morph6.fs.neo.org:40333", - "morph7.fs.neo.org:40333" - ] - } -} diff --git a/neo-cli/Modes/oracle/config.json b/neo-cli/Modes/oracle/config.json deleted file mode 100644 index 1c1e0aaa9..000000000 --- a/neo-cli/Modes/oracle/config.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "ApplicationConfiguration": { - "Logger": { - "Path": "Logs", - "ConsoleOutput": false, - "Active": false - }, - "Storage": { - "Engine": "LevelDBStore", - "Path": "Data_LevelDB_{0}" - }, - "P2P": { - "Port": 10333, - "WsPort": 10334, - "MinDesiredConnections": 10, - "MaxConnections": 40, - "MaxConnectionsPerAddress": 3 - }, - "UnlockWallet": { - "Path": "", - "Password": "", - "IsActive": false - } - }, - "ProtocolConfiguration": { - "Network": 860833102, - "AddressVersion": 53, - "MillisecondsPerBlock": 15000, - "MaxTransactionsPerBlock": 512, - "MemoryPoolMaxTransactions": 50000, - "MaxTraceableBlocks": 2102400, - "Hardforks": { - "HF_Aspidochelone": 1730000 - }, - "InitialGasDistribution": 5200000000000000, - "ValidatorsCount": 7, - "StandbyCommittee": [ - "03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c", - "02df48f60e8f3e01c48ff40b9b7f1310d7a8b2a193188befe1c2e3df740e895093", - "03b8d9d5771d8f513aa0869b9cc8d50986403b78c6da36890638c3d46a5adce04a", - "02ca0e27697b9c248f6f16e085fd0061e26f44da85b58ee835c110caa5ec3ba554", - "024c7b7fb6c310fccf1ba33b082519d82964ea93868d676662d4a59ad548df0e7d", - "02aaec38470f6aad0042c6e877cfd8087d2676b0f516fddd362801b9bd3936399e", - "02486fd15702c4490a26703112a5cc1d0923fd697a33406bd5a1c00e0013b09a70", - "023a36c72844610b4d34d1968662424011bf783ca9d984efa19a20babf5582f3fe", - "03708b860c1de5d87f5b151a12c2a99feebd2e8b315ee8e7cf8aa19692a9e18379", - "03c6aa6e12638b36e88adc1ccdceac4db9929575c3e03576c617c49cce7114a050", - "03204223f8c86b8cd5c89ef12e4f0dbb314172e9241e30c9ef2293790793537cf0", - "02a62c915cf19c7f19a50ec217e79fac2439bbaad658493de0c7d8ffa92ab0aa62", - "03409f31f0d66bdc2f70a9730b66fe186658f84a8018204db01c106edc36553cd0", - "0288342b141c30dc8ffcde0204929bb46aed5756b41ef4a56778d15ada8f0c6654", - "020f2887f41474cfeb11fd262e982051c1541418137c02a0f4961af911045de639", - "0222038884bbd1d8ff109ed3bdef3542e768eef76c1247aea8bc8171f532928c30", - "03d281b42002647f0113f36c7b8efb30db66078dfaaa9ab3ff76d043a98d512fde", - "02504acbc1f4b3bdad1d86d6e1a08603771db135a73e61c9d565ae06a1938cd2ad", - "0226933336f1b75baa42d42b71d9091508b638046d19abd67f4e119bf64a7cfb4d", - "03cdcea66032b82f5c30450e381e5295cae85c5e6943af716cc6b646352a6067dc", - "02cd5a5547119e24feaa7c2a0f37b8c9366216bab7054de0065c9be42084003c8a" - ], - "SeedList": [ - "seed1.neo.org:10333", - "seed2.neo.org:10333", - "seed3.neo.org:10333", - "seed4.neo.org:10333", - "seed5.neo.org:10333" - ] - } -} diff --git a/neo-cli/Modes/oracle/oracleservice.json b/neo-cli/Modes/oracle/oracleservice.json deleted file mode 100644 index db7624545..000000000 --- a/neo-cli/Modes/oracle/oracleservice.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "PluginConfiguration": { - "Network": 860833102, - "Nodes": [ - "http://oracle1.ngd.network:10332", - "http://oracle2.ngd.network:10332", - "http://oracle3.ngd.network:10332", - "http://oracle.n3.nspcc.ru:10332" - ], - "MaxTaskTimeout": 432000000, - "MaxOracleTimeout": 10000, - "AllowPrivateHost": false, - "AllowedContentTypes": [ "application/json" ], - "Https": { - "Timeout": 10000 - }, - "NeoFS": { - "EndPoint": "http://st1.t5.fs.neo.org:8080", - "Timeout": 15000 - }, - "AutoStart": true - }, - "Dependency": [ - "RpcServer" - ] -} From 009f802f80b6a50802bdb7703eda4f1d7f775ade Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 22 Sep 2022 02:06:46 -0700 Subject: [PATCH 52/65] format check --- neo-cli/neo-cli.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/neo-cli/neo-cli.csproj b/neo-cli/neo-cli.csproj index a4b3f39d2..d055821b5 100644 --- a/neo-cli/neo-cli.csproj +++ b/neo-cli/neo-cli.csproj @@ -17,7 +17,7 @@ - + PreserveNewest Modes\%(RecursiveDir)\%(Filename)%(Extension) From e79bde99744b8250d8ab3545c8ecaba9a222c2c8 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 22 Sep 2022 02:26:22 -0700 Subject: [PATCH 53/65] 1. config exists in mode and in mode => move config from mode to plugin 2. config exists in mode but not in plugin => delete config in mode 3. config not exists in mode but exists in plugin => move config from plugin to mode 4. config not exists in plugin not in mode => do nothing. --- neo-cli/CLI/MainService.Mode.cs | 4 ++-- neo-cli/CLI/MainService.Plugins.cs | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index 269f91fc7..cda133f1f 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -191,7 +191,7 @@ private static void MoveModeConfig(string mode, bool toMode = true) } // Add plugin to .PLUGINS file - private void AddPluginToMode(string pluginName, string modeName) + private static void AddPluginToMode(string pluginName, string modeName) { var plugins = File.ReadAllLines($"./Modes/{modeName}/.PLUGINS"); if (plugins.Contains(pluginName)) return; @@ -200,7 +200,7 @@ private void AddPluginToMode(string pluginName, string modeName) } // Remove plugin from .PLUGINS file - private void RemovePluginFromMode(string pluginName, string modeName) + private static void RemovePluginFromMode(string pluginName, string modeName) { var plugins = File.ReadAllLines($"./Modes/{modeName}/.PLUGINS"); // if (plugins.All(p => !string.Equals(p, pluginName, StringComparison.CurrentCultureIgnoreCase))) return; diff --git a/neo-cli/CLI/MainService.Plugins.cs b/neo-cli/CLI/MainService.Plugins.cs index 1e23fa9a9..ec98d34f5 100644 --- a/neo-cli/CLI/MainService.Plugins.cs +++ b/neo-cli/CLI/MainService.Plugins.cs @@ -20,7 +20,6 @@ using System.Net.Http; using System.Security.Cryptography; using System.Threading.Tasks; -using Akka.Util.Internal; namespace Neo.CLI { @@ -35,7 +34,7 @@ private async Task OnInstallCommandAsync(string pluginName) { if (PluginExists(pluginName)) { - ConsoleHelper.Warning($"Plugin already exist."); + ConsoleHelper.Warning("Plugin already exist."); return; } @@ -151,9 +150,10 @@ private async Task InstallPluginAsync(string pluginName, HashSet install try { var pluginActualName = GetPluginActualName(pluginName); - if (File.Exists($"Plugins/{pluginActualName}/config.json")) - // what if the file already exists in the mode? OK, lets overwrite it then. - File.Copy($"Plugins/{pluginActualName}/config.json", $"Modes/{_currentMode}/{pluginActualName}.json", true); + if(File.Exists($"Modes/{_currentMode}/{pluginActualName}.json")) + File.Copy($"Modes/{_currentMode}/{pluginActualName}.json", $"Plugins/{pluginActualName}/config.json", true); + else if (File.Exists($"Plugins/{pluginActualName}/config.json")) + File.Copy($"Plugins/{pluginActualName}/config.json", $"Modes/{_currentMode}/{pluginActualName}.json", false); AddPluginToMode(pluginActualName, _currentMode); } catch (Exception e) From bcad2a02f5852969600f11e013893c49538abbe6 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 22 Sep 2022 02:26:37 -0700 Subject: [PATCH 54/65] config.json --- neo-cli/CLI/MainService.Plugins.cs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/neo-cli/CLI/MainService.Plugins.cs b/neo-cli/CLI/MainService.Plugins.cs index ec98d34f5..45e398d1b 100644 --- a/neo-cli/CLI/MainService.Plugins.cs +++ b/neo-cli/CLI/MainService.Plugins.cs @@ -150,9 +150,20 @@ private async Task InstallPluginAsync(string pluginName, HashSet install try { var pluginActualName = GetPluginActualName(pluginName); - if(File.Exists($"Modes/{_currentMode}/{pluginActualName}.json")) - File.Copy($"Modes/{_currentMode}/{pluginActualName}.json", $"Plugins/{pluginActualName}/config.json", true); + if (File.Exists($"Modes/{_currentMode}/{pluginActualName}.json")) + { + if(File.Exists($"Plugins/{pluginActualName}/config.json")) + // plugin contains config.json && mode contains plugin.json + // replace the config.json with plugin.json from mode + File.Copy($"Modes/{_currentMode}/{pluginActualName}.json", $"Plugins/{pluginActualName}/config.json", true); + else + // plugin doesn't contain config.json && mode contains plugin.json + // delete the plugin.json from mode + File.Delete($"Modes/{_currentMode}/{pluginActualName}.json"); + } else if (File.Exists($"Plugins/{pluginActualName}/config.json")) + // plugin contains config.json && mode doesn't contain plugin.json + // copy the config.json to mode File.Copy($"Plugins/{pluginActualName}/config.json", $"Modes/{_currentMode}/{pluginActualName}.json", false); AddPluginToMode(pluginActualName, _currentMode); } From 86a717484eb4ffc2596590dc47f667d5f9d1ccc3 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Mon, 10 Oct 2022 08:04:29 -0400 Subject: [PATCH 55/65] fix format --- neo-cli/CLI/MainService.Plugins.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/neo-cli/CLI/MainService.Plugins.cs b/neo-cli/CLI/MainService.Plugins.cs index 45e398d1b..b8f04f6b9 100644 --- a/neo-cli/CLI/MainService.Plugins.cs +++ b/neo-cli/CLI/MainService.Plugins.cs @@ -152,7 +152,7 @@ private async Task InstallPluginAsync(string pluginName, HashSet install var pluginActualName = GetPluginActualName(pluginName); if (File.Exists($"Modes/{_currentMode}/{pluginActualName}.json")) { - if(File.Exists($"Plugins/{pluginActualName}/config.json")) + if (File.Exists($"Plugins/{pluginActualName}/config.json")) // plugin contains config.json && mode contains plugin.json // replace the config.json with plugin.json from mode File.Copy($"Modes/{_currentMode}/{pluginActualName}.json", $"Plugins/{pluginActualName}/config.json", true); @@ -279,8 +279,8 @@ private void OnPluginsCommand() private static string GetPluginActualName(string pluginName) { - var pluginActualName=""; - foreach (var plugin in new DirectoryInfo("./Plugins").GetDirectories()) + var pluginActualName = ""; + foreach (var plugin in new DirectoryInfo("./Plugins").GetDirectories()) { if (!string.Equals(plugin.Name, pluginName, StringComparison.CurrentCultureIgnoreCase)) continue; pluginActualName = plugin.Name; From 0bd73ce8116541414a6f7a6e5a14b49af26cd83e Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Wed, 26 Oct 2022 09:30:43 -0400 Subject: [PATCH 56/65] fix expect test --- neo-cli/neo-cli.csproj | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/neo-cli/neo-cli.csproj b/neo-cli/neo-cli.csproj index d055821b5..d9bce410f 100644 --- a/neo-cli/neo-cli.csproj +++ b/neo-cli/neo-cli.csproj @@ -16,21 +16,19 @@ neo.ico - - + + PreserveNewest + PreserveNewest Modes\%(RecursiveDir)\%(Filename)%(Extension) - - - - + + - + - From 842fc07f5279e5f98cf15cb099380e35846244c2 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Wed, 26 Oct 2022 09:55:26 -0400 Subject: [PATCH 57/65] fix path issue --- neo-cli/CLI/MainService.Mode.cs | 43 +++++++++++++++--------------- neo-cli/CLI/MainService.Plugins.cs | 26 ++++++++++-------- neo-cli/CLI/MainService.cs | 5 ++++ 3 files changed, 41 insertions(+), 33 deletions(-) diff --git a/neo-cli/CLI/MainService.Mode.cs b/neo-cli/CLI/MainService.Mode.cs index cda133f1f..291450e92 100644 --- a/neo-cli/CLI/MainService.Mode.cs +++ b/neo-cli/CLI/MainService.Mode.cs @@ -18,7 +18,6 @@ namespace Neo.CLI; partial class MainService { - /// /// Process "mode list" command. /// @@ -27,7 +26,7 @@ private void OnListModes() { try { - Directory.GetDirectories("./Modes/").ForEach(p => ConsoleHelper.Info(p)); + Directory.GetDirectories(ModePath).ForEach(p => ConsoleHelper.Info(p)); } catch (IOException) { @@ -50,22 +49,22 @@ private void OnSaveMode(string modeName) modeName = modeName.ToLower(); try { - var targetMode = new DirectoryInfo($"Modes/{modeName}"); + var targetMode = new DirectoryInfo($"{ModePath}/{modeName}"); // Create the mode if it does not exist if (!targetMode.Exists) Directory.CreateDirectory(targetMode.FullName); // Get the config files of the node MoveModeConfig(modeName.ToLower()); - var plugins = new DirectoryInfo("./Plugins"); + var plugins = new DirectoryInfo(PluginPath); // Cache directories before we start copying var dirs = plugins.GetDirectories(); // Create an empty .PLUGINS file - File.Create($"Modes/{modeName}/.PLUGINS").Close(); + File.Create($"{ModePath}/{modeName}/.PLUGINS").Close(); // Save the Plugin files foreach (var plugin in dirs) { foreach (var file in plugin.GetFiles().Where(p => p.Extension == ".json")) { - file.CopyTo($"Modes/{modeName}/{plugin.Name}.json", true); + file.CopyTo($"{ModePath}/{modeName}/{plugin.Name}.json", true); } AddPluginToMode(plugin.Name, modeName); } @@ -86,7 +85,7 @@ private void OnDeleteMode(string modeName) { try { - var dir = new DirectoryInfo($"Modes/{modeName.ToLower()}"); + var dir = new DirectoryInfo($"{ModePath}/{modeName.ToLower()}"); if (!dir.Exists) return; Directory.Delete(dir.FullName, true); @@ -110,37 +109,37 @@ private async Task LoadMode(string mode) try { mode = mode.ToLower(); - var dir = new DirectoryInfo($"./Modes/{mode}"); + var dir = new DirectoryInfo($"{ModePath}/{mode}"); if (!dir.Exists) throw new DirectoryNotFoundException($"Mode not found: {dir.FullName}"); // Process the plugin - var modePlugins = File.ReadAllLines($"./Modes/{_currentMode}/.PLUGINS"); + var modePlugins = File.ReadAllLines($"{ModePath}/{_currentMode}/.PLUGINS"); // loop modePlugins foreach (var pluginName in modePlugins) { // if the plugin is not installed, install it - if (!Directory.Exists($"Plugins/{pluginName}/")) + if (!Directory.Exists($"{PluginPath}/{pluginName}/")) { await InstallPluginAsync(pluginName, overWrite: true, saveConfig: false); _needRestart = true; } // if the mode has the plugin config, load the config from the mode - if (File.Exists($"Modes/{mode}/{pluginName}.json")) - File.Copy($"Modes/{mode}/{pluginName}.json", - $"Plugins/{pluginName}/config.json", true); + if (File.Exists($"{ModePath}/{mode}/{pluginName}.json")) + File.Copy($"{ModePath}/{mode}/{pluginName}.json", + $"{PluginPath}/{pluginName}/config.json", true); } // get the system config file from the mode MoveModeConfig(mode, false); // Get existing plugins and delete them if they are not in the mode - new DirectoryInfo("Plugins/").GetDirectories().ForEach(p => + new DirectoryInfo($"{PluginPath}/").GetDirectories().ForEach(p => { if (modePlugins.Any(k => string.Compare(Path.GetFileNameWithoutExtension(k), p.Name, StringComparison.OrdinalIgnoreCase) == 0) - || !File.Exists($"Plugins/{p.Name}/config.json")) return; + || !File.Exists($"{PluginPath}/{p.Name}/config.json")) return; try { ConsoleHelper.Info("Removing plugin ", p.Name); - Directory.Delete($"Plugins/{p.Name}", true); + Directory.Delete($"{PluginPath}/{p.Name}", true); _needRestart = true; } catch @@ -162,8 +161,8 @@ private async Task LoadMode(string mode) /// if the mode is not found private static void MoveModeConfig(string mode, bool toMode = true) { - var modeDir = new DirectoryInfo($"./Modes/{mode.ToLower()}"); - var configDir = new DirectoryInfo("./"); + var modeDir = new DirectoryInfo($"{ModePath}/{mode.ToLower()}"); + var configDir = new DirectoryInfo($"{StrExeFilePath}"); if (!modeDir.Exists) throw new DirectoryNotFoundException($"Mode not found: {modeDir.FullName}"); try @@ -193,18 +192,18 @@ private static void MoveModeConfig(string mode, bool toMode = true) // Add plugin to .PLUGINS file private static void AddPluginToMode(string pluginName, string modeName) { - var plugins = File.ReadAllLines($"./Modes/{modeName}/.PLUGINS"); + var plugins = File.ReadAllLines($"{ModePath}/{modeName}/.PLUGINS"); if (plugins.Contains(pluginName)) return; var newPlugins = plugins.Append(pluginName).ToArray(); - File.WriteAllLines($"./Modes/{modeName}/.PLUGINS", newPlugins); + File.WriteAllLines($"{ModePath}/{modeName}/.PLUGINS", newPlugins); } // Remove plugin from .PLUGINS file private static void RemovePluginFromMode(string pluginName, string modeName) { - var plugins = File.ReadAllLines($"./Modes/{modeName}/.PLUGINS"); + var plugins = File.ReadAllLines($"{ModePath}/{modeName}/.PLUGINS"); // if (plugins.All(p => !string.Equals(p, pluginName, StringComparison.CurrentCultureIgnoreCase))) return; var newPlugins = plugins.Where(p => !string.Equals(p, pluginName, StringComparison.CurrentCultureIgnoreCase)).ToArray(); - File.WriteAllLines($"./Modes/{modeName}/.PLUGINS", newPlugins); + File.WriteAllLines($"{ModePath}/{modeName}/.PLUGINS", newPlugins); } } diff --git a/neo-cli/CLI/MainService.Plugins.cs b/neo-cli/CLI/MainService.Plugins.cs index b8f04f6b9..fc08f17e6 100644 --- a/neo-cli/CLI/MainService.Plugins.cs +++ b/neo-cli/CLI/MainService.Plugins.cs @@ -142,7 +142,11 @@ private async Task InstallPluginAsync(string pluginName, HashSet install await using Stream es = entry.Open(); await InstallDependenciesAsync(es, installed); } - zip.ExtractToDirectory("./", true); + if (!Directory.Exists($"{StrExeFilePath}Plugins")) + { + Directory.CreateDirectory($"{StrExeFilePath}Plugins"); + } + zip.ExtractToDirectory($"{StrExeFilePath}", true); Console.WriteLine(); if (!saveConfig) return; @@ -150,21 +154,21 @@ private async Task InstallPluginAsync(string pluginName, HashSet install try { var pluginActualName = GetPluginActualName(pluginName); - if (File.Exists($"Modes/{_currentMode}/{pluginActualName}.json")) + if (File.Exists($"{ModePath}/{_currentMode}/{pluginActualName}.json")) { - if (File.Exists($"Plugins/{pluginActualName}/config.json")) + if (File.Exists($"{PluginPath}/{pluginActualName}/config.json")) // plugin contains config.json && mode contains plugin.json // replace the config.json with plugin.json from mode - File.Copy($"Modes/{_currentMode}/{pluginActualName}.json", $"Plugins/{pluginActualName}/config.json", true); + File.Copy($"{ModePath}/{_currentMode}/{pluginActualName}.json", $"{PluginPath}/{pluginActualName}/config.json", true); else // plugin doesn't contain config.json && mode contains plugin.json // delete the plugin.json from mode - File.Delete($"Modes/{_currentMode}/{pluginActualName}.json"); + File.Delete($"{ModePath}/{_currentMode}/{pluginActualName}.json"); } - else if (File.Exists($"Plugins/{pluginActualName}/config.json")) + else if (File.Exists($"{PluginPath}/{pluginActualName}/config.json")) // plugin contains config.json && mode doesn't contain plugin.json // copy the config.json to mode - File.Copy($"Plugins/{pluginActualName}/config.json", $"Modes/{_currentMode}/{pluginActualName}.json", false); + File.Copy($"{PluginPath}/{pluginActualName}/config.json", $"{ModePath}/{_currentMode}/{pluginActualName}.json", false); AddPluginToMode(pluginActualName, _currentMode); } catch (Exception e) @@ -225,7 +229,7 @@ private void OnUnInstallCommand(string pluginName) { try { - using var reader = File.OpenRead($"./Plugins/{p.Name}/config.json"); + using var reader = File.OpenRead($"{PluginPath}/{p.Name}/config.json"); if (new ConfigurationBuilder() .AddJsonStream(reader) .Build() @@ -246,8 +250,8 @@ private void OnUnInstallCommand(string pluginName) } try { - Directory.Delete($"Plugins/{pluginName}", true); - var config = $"Modes/{_currentMode}/{pluginName}.json"; + Directory.Delete($"{PluginPath}/{pluginName}", true); + var config = $"{ModePath}/{_currentMode}/{pluginName}.json"; if (File.Exists(config)) File.Delete(config); RemovePluginFromMode(pluginName, _currentMode); @@ -280,7 +284,7 @@ private void OnPluginsCommand() private static string GetPluginActualName(string pluginName) { var pluginActualName = ""; - foreach (var plugin in new DirectoryInfo("./Plugins").GetDirectories()) + foreach (var plugin in new DirectoryInfo($"{PluginPath}").GetDirectories()) { if (!string.Equals(plugin.Name, pluginName, StringComparison.CurrentCultureIgnoreCase)) continue; pluginActualName = plugin.Name; diff --git a/neo-cli/CLI/MainService.cs b/neo-cli/CLI/MainService.cs index df13892bb..ff2fe8fdc 100644 --- a/neo-cli/CLI/MainService.cs +++ b/neo-cli/CLI/MainService.cs @@ -49,6 +49,11 @@ public partial class MainService : ConsoleServiceBase, IWalletProvider private static string _currentMode = "mainnet"; private bool _needRestart = false; + static readonly string StrExeFilePath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); + static readonly string ModePath = Path.Combine(StrExeFilePath, "Modes"); + static readonly string PluginPath = Path.Combine(StrExeFilePath, "Plugins"); + + public Wallet CurrentWallet { get => _currentWallet; From 3d0682280d0c88b22e82b3e79be52a5080a2fc06 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Wed, 26 Oct 2022 20:27:01 -0400 Subject: [PATCH 58/65] fix path --- neo-cli/CLI/MainService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/neo-cli/CLI/MainService.cs b/neo-cli/CLI/MainService.cs index ff2fe8fdc..fd2edc401 100644 --- a/neo-cli/CLI/MainService.cs +++ b/neo-cli/CLI/MainService.cs @@ -395,7 +395,7 @@ public async void Start(string[] args) { i++; // Get all the modes - var modes = Directory.GetDirectories("./Modes/"); + var modes = Directory.GetDirectories($"{ModePath}/Modes/"); // Find the expected mode if (modes.Any(p => string.Equals(new DirectoryInfo(p).Name, args[i], StringComparison.CurrentCultureIgnoreCase))) { From 2a3e53e575e8ac40f07a41605cb61d112195c11f Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Wed, 26 Oct 2022 21:14:48 -0400 Subject: [PATCH 59/65] fix privatenet wallet path --- neo-cli/CLI/MainService.cs | 2 +- .../Modes/privatenet/NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP.json | 2 +- neo-cli/Modes/privatenet/config.json | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/neo-cli/CLI/MainService.cs b/neo-cli/CLI/MainService.cs index fd2edc401..3e10d6359 100644 --- a/neo-cli/CLI/MainService.cs +++ b/neo-cli/CLI/MainService.cs @@ -395,7 +395,7 @@ public async void Start(string[] args) { i++; // Get all the modes - var modes = Directory.GetDirectories($"{ModePath}/Modes/"); + var modes = Directory.GetDirectories($"{ModePath}/"); // Find the expected mode if (modes.Any(p => string.Equals(new DirectoryInfo(p).Name, args[i], StringComparison.CurrentCultureIgnoreCase))) { diff --git a/neo-cli/Modes/privatenet/NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP.json b/neo-cli/Modes/privatenet/NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP.json index e151b0b0b..823a076be 100644 --- a/neo-cli/Modes/privatenet/NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP.json +++ b/neo-cli/Modes/privatenet/NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP.json @@ -1 +1 @@ -{"extra":{},"scrypt":{"r":8,"p":8,"n":16384,"size":64},"name":"NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP","accounts":[{"address":"NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP","extra":{},"lock":false,"contract":{"script":"DCED7s02MiDW5N55Or\/rrgl3l2hGjFmjtuATKp6jsiAQ99hBVuezJw==","deployed":false,"parameters":[{"name":"signature","type":"signature"}]},"label":"NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP","key":"6PYTrLoLMT1Ms1H2msFTGUDRhHKXsZWA2Lj5rcF2GdPJju1Nuqy4npbef4","isDefault":true}],"version":"1.0"} \ No newline at end of file +{"extra":{},"scrypt":{"r":8,"p":8,"n":16384,"size":64},"name":"NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP","accounts":[{"address":"NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP","extra":{},"lock":false,"contract":{"script":"DCED7s02MiDW5N55Or\/rrgl3l2hGjFmjtuATKp6jsiAQ99hBVuezJw==","deployed":false,"parameters":[{"name":"signature","type":"Signature"}]},"label":"NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP","key":"6PYTrLoLMT1Ms1H2msFTGUDRhHKXsZWA2Lj5rcF2GdPJju1Nuqy4npbef4","isDefault":true}],"version":"1.0"} diff --git a/neo-cli/Modes/privatenet/config.json b/neo-cli/Modes/privatenet/config.json index 2add715bc..883d9155a 100644 --- a/neo-cli/Modes/privatenet/config.json +++ b/neo-cli/Modes/privatenet/config.json @@ -18,7 +18,7 @@ }, "UnlockWallet": { - "Path": "NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP.json", + "Path": "Modes/privatenet/NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP.json", "Password": "12345678", "IsActive": true } From f1977f09fbabd12825ab5e1200cc91bb8c575166 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Wed, 26 Oct 2022 21:39:10 -0400 Subject: [PATCH 60/65] fix expect --- .github/workflows/test-neo-cli.expect | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/test-neo-cli.expect b/.github/workflows/test-neo-cli.expect index dbf41526b..21ee4ceda 100755 --- a/.github/workflows/test-neo-cli.expect +++ b/.github/workflows/test-neo-cli.expect @@ -14,6 +14,10 @@ expect { timeout { exit 1 } } +sleep 5 + +spawn dotnet out/neo-cli.dll + # # Test 'create wallet' # From e12ad2d825e5cad7c6e54addd8ababc646216300 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 27 Oct 2022 08:53:28 -0400 Subject: [PATCH 61/65] Update neo-cli/Modes/privatenet/config.json Co-authored-by: Nicole <43694095+nicolegys@users.noreply.github.com> --- neo-cli/Modes/privatenet/config.json | 1 - 1 file changed, 1 deletion(-) diff --git a/neo-cli/Modes/privatenet/config.json b/neo-cli/Modes/privatenet/config.json index 883d9155a..05656f76e 100644 --- a/neo-cli/Modes/privatenet/config.json +++ b/neo-cli/Modes/privatenet/config.json @@ -15,7 +15,6 @@ "MinDesiredConnections": 10, "MaxConnections": 40, "MaxConnectionsPerAddress": 3 - }, "UnlockWallet": { "Path": "Modes/privatenet/NbVj8GhwToNv4WF2gVaoco6hbkMQ8hrHWP.json", From cb9604258ec6bbb08e0ba0c8c0794de52bd3a308 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Mon, 31 Oct 2022 09:19:32 -0400 Subject: [PATCH 62/65] Update neo-cli/CLI/MainService.Plugins.cs Co-authored-by: Nicole <43694095+nicolegys@users.noreply.github.com> --- neo-cli/CLI/MainService.Plugins.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/neo-cli/CLI/MainService.Plugins.cs b/neo-cli/CLI/MainService.Plugins.cs index fc08f17e6..d5a108ae8 100644 --- a/neo-cli/CLI/MainService.Plugins.cs +++ b/neo-cli/CLI/MainService.Plugins.cs @@ -142,9 +142,9 @@ private async Task InstallPluginAsync(string pluginName, HashSet install await using Stream es = entry.Open(); await InstallDependenciesAsync(es, installed); } - if (!Directory.Exists($"{StrExeFilePath}Plugins")) + if (!Directory.Exists($"{StrExeFilePath}/Plugins")) { - Directory.CreateDirectory($"{StrExeFilePath}Plugins"); + Directory.CreateDirectory($"{StrExeFilePath}/Plugins"); } zip.ExtractToDirectory($"{StrExeFilePath}", true); Console.WriteLine(); From 858a92240d84c4a78c1fd4ea61960828af9ca657 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Mon, 31 Oct 2022 09:19:57 -0400 Subject: [PATCH 63/65] Update neo-cli/CLI/MainService.Plugins.cs Co-authored-by: Nicole <43694095+nicolegys@users.noreply.github.com> --- neo-cli/CLI/MainService.Plugins.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/neo-cli/CLI/MainService.Plugins.cs b/neo-cli/CLI/MainService.Plugins.cs index d5a108ae8..273c531ca 100644 --- a/neo-cli/CLI/MainService.Plugins.cs +++ b/neo-cli/CLI/MainService.Plugins.cs @@ -209,7 +209,7 @@ private async Task InstallDependenciesAsync(Stream config, HashSet insta private static bool PluginExists(string pluginName) { return Plugin.Plugins.Any(p => p.Name.Equals(pluginName, StringComparison.InvariantCultureIgnoreCase)) || - new DirectoryInfo("Plugins").GetDirectories().Any(p => p.Name.Equals(pluginName, StringComparison.InvariantCultureIgnoreCase)); + new DirectoryInfo($"{StrExeFilePath}/Plugins").GetDirectories().Any(p => p.Name.Equals(pluginName, StringComparison.InvariantCultureIgnoreCase)); } /// From 305ab79684053adc319f2b7cdd775bff5157333a Mon Sep 17 00:00:00 2001 From: Shargon Date: Mon, 12 Dec 2022 01:56:33 -0800 Subject: [PATCH 64/65] Update Helper.cs --- neo-cli/CLI/Helper.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/neo-cli/CLI/Helper.cs b/neo-cli/CLI/Helper.cs index 94297cc40..c2f1ccf13 100644 --- a/neo-cli/CLI/Helper.cs +++ b/neo-cli/CLI/Helper.cs @@ -8,8 +8,6 @@ // Redistribution and use in source and binary forms with or without // modifications are permitted. -using System.IO; - namespace Neo.CLI { internal static class Helper From 2e0791913a15b45dc64e0af345622043ad623cf1 Mon Sep 17 00:00:00 2001 From: Jinghui Liao Date: Thu, 2 Feb 2023 06:51:06 -0500 Subject: [PATCH 65/65] update format --- neo-cli/neo-cli.csproj | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/neo-cli/neo-cli.csproj b/neo-cli/neo-cli.csproj index adf0e2ba9..d6c21172e 100644 --- a/neo-cli/neo-cli.csproj +++ b/neo-cli/neo-cli.csproj @@ -17,11 +17,11 @@ - - PreserveNewest - PreserveNewest - Modes\%(RecursiveDir)\%(Filename)%(Extension) - + + PreserveNewest + PreserveNewest + Modes\%(RecursiveDir)\%(Filename)%(Extension) +