diff --git a/Neo.ConsoleService/ConsoleHelper.cs b/Neo.ConsoleService/ConsoleHelper.cs new file mode 100644 index 000000000..fdf6f180c --- /dev/null +++ b/Neo.ConsoleService/ConsoleHelper.cs @@ -0,0 +1,65 @@ +using System; + +namespace Neo.ConsoleService +{ + public static class ConsoleHelper + { + private static readonly ConsoleColorSet InfoColor = new(ConsoleColor.Cyan); + private static readonly ConsoleColorSet WarningColor = new(ConsoleColor.Yellow); + private static readonly ConsoleColorSet ErrorColor = new(ConsoleColor.Red); + + /// + /// Info handles message in the format of "[tag]:[message]", + /// avoid using Info if the `tag` is too long + /// + /// The log message in pairs of (tag, message) + public static void Info(params string[] values) + { + var currentColor = new ConsoleColorSet(); + + for (int i = 0; i < values.Length; i++) + { + if (i % 2 == 0) + InfoColor.Apply(); + else + currentColor.Apply(); + Console.Write(values[i]); + } + currentColor.Apply(); + Console.WriteLine(); + } + + /// + /// Use warning if something unexpected happens + /// or the execution result is not correct. + /// Also use warning if you just want to remind + /// user of doing something. + /// + /// Warning message + public static void Warning(string msg) + { + Log("Warning", WarningColor, msg); + } + + /// + /// Use Error if the verification or input format check fails + /// or exception that breaks the execution of interactive + /// command throws. + /// + /// Error message + public static void Error(string msg) + { + Log("Error", ErrorColor, msg); + } + + private static void Log(string tag, ConsoleColorSet colorSet, string msg) + { + var currentColor = new ConsoleColorSet(); + + colorSet.Apply(); + Console.Write($"{tag}: "); + currentColor.Apply(); + Console.WriteLine(msg); + } + } +} diff --git a/Neo.ConsoleService/ConsoleServiceBase.cs b/Neo.ConsoleService/ConsoleServiceBase.cs index 34584222a..aa358ecd5 100644 --- a/Neo.ConsoleService/ConsoleServiceBase.cs +++ b/Neo.ConsoleService/ConsoleServiceBase.cs @@ -524,7 +524,7 @@ public void Run(string[] args) { if (Environment.OSVersion.Platform != PlatformID.Win32NT) { - Console.WriteLine("Only support for installing services on Windows."); + ConsoleHelper.Warning("Only support for installing services on Windows."); return; } string arguments = string.Format("create {0} start= auto binPath= \"{1}\"", ServiceName, Process.GetCurrentProcess().MainModule.FileName); @@ -546,7 +546,7 @@ public void Run(string[] args) { if (Environment.OSVersion.Platform != PlatformID.Win32NT) { - Console.WriteLine("Only support for installing services on Windows."); + ConsoleHelper.Warning("Only support for installing services on Windows."); return; } Process process = Process.Start(new ProcessStartInfo @@ -619,16 +619,16 @@ public virtual void RunConsole() { if (!OnCommand(line)) { - Console.WriteLine("error: Command not found"); + ConsoleHelper.Error("Command not found"); } } catch (TargetInvocationException ex) { - Console.WriteLine($"error: {ex.InnerException.Message}"); + ConsoleHelper.Error(ex.InnerException.Message); } catch (Exception ex) { - Console.WriteLine($"error: {ex.Message}"); + ConsoleHelper.Error(ex.Message); } } diff --git a/neo-cli/CLI/MainService.Blockchain.cs b/neo-cli/CLI/MainService.Blockchain.cs index f6b9efbaa..2c75a4315 100644 --- a/neo-cli/CLI/MainService.Blockchain.cs +++ b/neo-cli/CLI/MainService.Blockchain.cs @@ -28,7 +28,7 @@ private void OnExportBlocksStartCountCommand(uint start, uint count = uint.MaxVa uint height = NativeContract.Ledger.CurrentIndex(NeoSystem.StoreView); if (height < start) { - Console.WriteLine("Error: invalid start height."); + ConsoleHelper.Error("invalid start height."); return; } diff --git a/neo-cli/CLI/MainService.Contracts.cs b/neo-cli/CLI/MainService.Contracts.cs index 17a9bd182..3311081cb 100644 --- a/neo-cli/CLI/MainService.Contracts.cs +++ b/neo-cli/CLI/MainService.Contracts.cs @@ -45,10 +45,10 @@ private void OnDeployCommand(string filePath, string manifestPath = null) UInt160 hash = SmartContract.Helper.GetContractHash(tx.Sender, nef.CheckSum, manifest.Name); - Console.WriteLine($"Contract hash: {hash}"); - Console.WriteLine($"Gas consumed: {new BigDecimal((BigInteger)tx.SystemFee, NativeContract.GAS.Decimals)}"); - Console.WriteLine($"Network fee: {new BigDecimal((BigInteger)tx.NetworkFee, NativeContract.GAS.Decimals)}"); - Console.WriteLine($"Total fee: {new BigDecimal((BigInteger)(tx.SystemFee + tx.NetworkFee), NativeContract.GAS.Decimals)} GAS"); + ConsoleHelper.Info("Contract hash: ", $"{hash}"); + ConsoleHelper.Info("Gas consumed: ", $"{new BigDecimal((BigInteger)tx.SystemFee, NativeContract.GAS.Decimals)}"); + ConsoleHelper.Info("Network fee: ", $"{new BigDecimal((BigInteger)tx.NetworkFee, NativeContract.GAS.Decimals)}"); + ConsoleHelper.Info("Total fee: ", $"{new BigDecimal((BigInteger)(tx.SystemFee + tx.NetworkFee), NativeContract.GAS.Decimals)} GAS"); if (!ReadUserInput("Relay tx? (no|yes)").IsYes()) // Add this in case just want to get hash but not relay { return; @@ -98,22 +98,22 @@ private void OnUpdateCommand(UInt160 scriptHash, string filePath, string manifes } catch (InvalidOperationException e) { - Console.WriteLine("Error: " + GetExceptionMessage(e)); + ConsoleHelper.Error(GetExceptionMessage(e)); return; } ContractState contract = NativeContract.ContractManagement.GetContract(NeoSystem.StoreView, scriptHash); if (contract == null) { - Console.WriteLine($"Can't upgrade, contract hash not exist: {scriptHash}"); + ConsoleHelper.Warning($"Can't upgrade, contract hash not exist: {scriptHash}"); } else { - Console.WriteLine($"Contract hash: {scriptHash}"); - Console.WriteLine($"Updated times: {contract.UpdateCounter}"); - Console.WriteLine($"Gas consumed: {new BigDecimal((BigInteger)tx.SystemFee, NativeContract.GAS.Decimals)}"); - Console.WriteLine($"Network fee: {new BigDecimal((BigInteger)tx.NetworkFee, NativeContract.GAS.Decimals)}"); - Console.WriteLine($"Total fee: {new BigDecimal((BigInteger)(tx.SystemFee + tx.NetworkFee), NativeContract.GAS.Decimals)} GAS"); + ConsoleHelper.Info("Contract hash: ", $"{scriptHash}"); + ConsoleHelper.Info("Updated times: ", $"{contract.UpdateCounter}"); + ConsoleHelper.Info("Gas consumed: ", $"{new BigDecimal((BigInteger)tx.SystemFee, NativeContract.GAS.Decimals)}"); + ConsoleHelper.Info("Network fee: ", $"{new BigDecimal((BigInteger)tx.NetworkFee, NativeContract.GAS.Decimals)}"); + ConsoleHelper.Info("Total fee: ", $"{new BigDecimal((BigInteger)(tx.SystemFee + tx.NetworkFee), NativeContract.GAS.Decimals)} GAS"); if (!ReadUserInput("Relay tx? (no|yes)").IsYes()) // Add this in case just want to get hash but not relay { return; @@ -169,11 +169,13 @@ private void OnInvokeCommand(UInt160 scriptHash, string operation, JArray contra } catch (InvalidOperationException e) { - Console.WriteLine("Error: " + GetExceptionMessage(e)); + ConsoleHelper.Error(GetExceptionMessage(e)); return; } - Console.WriteLine($"Network fee: {new BigDecimal((BigInteger)tx.NetworkFee, NativeContract.GAS.Decimals)}"); - Console.WriteLine($"Total fee: {new BigDecimal((BigInteger)(tx.SystemFee + tx.NetworkFee), NativeContract.GAS.Decimals)} GAS"); + ConsoleHelper.Info("Network fee: ", + $"{new BigDecimal((BigInteger)tx.NetworkFee, NativeContract.GAS.Decimals)}\t", + "Total fee: ", + $"{new BigDecimal((BigInteger)(tx.SystemFee + tx.NetworkFee), NativeContract.GAS.Decimals)} GAS"); if (!ReadUserInput("Relay tx? (no|yes)").IsYes()) { return; diff --git a/neo-cli/CLI/MainService.NEP17.cs b/neo-cli/CLI/MainService.NEP17.cs index ea073efbd..8cce43dbf 100644 --- a/neo-cli/CLI/MainService.NEP17.cs +++ b/neo-cli/CLI/MainService.NEP17.cs @@ -62,7 +62,7 @@ private void OnTransferCommand(UInt160 tokenHash, UInt160 to, decimal amount, UI } catch (InvalidOperationException e) { - Console.WriteLine("Error: " + GetExceptionMessage(e)); + ConsoleHelper.Error(GetExceptionMessage(e)); return; } if (!ReadUserInput("Relay tx(no|yes)").IsYes()) @@ -91,7 +91,7 @@ private void OnBalanceOfCommand(UInt160 tokenHash, UInt160 address) var balance = new BigDecimal(((PrimitiveType)balanceResult).GetInteger(), asset.Decimals); Console.WriteLine(); - Console.WriteLine($"{asset.AssetName} balance: {balance}"); + ConsoleHelper.Info($"{asset.AssetName} balance: ", $"{balance}"); } /// @@ -103,7 +103,7 @@ private void OnNameCommand(UInt160 tokenHash) { ContractState contract = NativeContract.ContractManagement.GetContract(NeoSystem.StoreView, tokenHash); if (contract == null) Console.WriteLine($"Contract hash not exist: {tokenHash}"); - else Console.WriteLine($"Result : {contract.Manifest.Name.ToString()}"); + else ConsoleHelper.Info("Result: ", contract.Manifest.Name); } /// @@ -115,7 +115,7 @@ private void OnDecimalsCommand(UInt160 tokenHash) { if (!OnInvokeWithResult(tokenHash, "decimals", out StackItem result, null)) return; - Console.WriteLine($"Result : {((PrimitiveType)result).GetInteger()}"); + ConsoleHelper.Info("Result: ", $"{((PrimitiveType)result).GetInteger()}"); } /// @@ -130,7 +130,7 @@ private void OnTotalSupplyCommand(UInt160 tokenHash) var asset = new AssetDescriptor(NeoSystem.StoreView, NeoSystem.Settings, tokenHash); var totalSupply = new BigDecimal(((PrimitiveType)result).GetInteger(), asset.Decimals); - Console.WriteLine($"Result : {totalSupply}"); + ConsoleHelper.Info("Result: ", $"{totalSupply}"); } } } diff --git a/neo-cli/CLI/MainService.Native.cs b/neo-cli/CLI/MainService.Native.cs index 0947b0e89..3180cb183 100644 --- a/neo-cli/CLI/MainService.Native.cs +++ b/neo-cli/CLI/MainService.Native.cs @@ -23,7 +23,7 @@ partial class MainService [ConsoleCommand("list nativecontract", Category = "Native Contract")] private void OnListNativeContract() { - NativeContract.Contracts.ToList().ForEach(p => Console.WriteLine($"\t{p.Name,-20}{p.Hash}")); + NativeContract.Contracts.ToList().ForEach(p => ConsoleHelper.Info($"\t{p.Name,-20}", $"{p.Hash}")); } } } diff --git a/neo-cli/CLI/MainService.Network.cs b/neo-cli/CLI/MainService.Network.cs index db900d35d..cf5743a2d 100644 --- a/neo-cli/CLI/MainService.Network.cs +++ b/neo-cli/CLI/MainService.Network.cs @@ -34,7 +34,7 @@ private void OnBroadcastAddressCommand(IPAddress payload, ushort port) { if (payload == null) { - Console.WriteLine("You must input the payload to relay."); + ConsoleHelper.Warning("You must input the payload to relay."); return; } @@ -134,7 +134,7 @@ private void OnRelayCommand(JObject jsonObjectToRelay) { if (jsonObjectToRelay == null) { - Console.WriteLine("You must input JSON object to relay."); + ConsoleHelper.Warning("You must input JSON object to relay."); return; } @@ -143,21 +143,21 @@ private void OnRelayCommand(JObject jsonObjectToRelay) ContractParametersContext context = ContractParametersContext.Parse(jsonObjectToRelay.ToString(), NeoSystem.StoreView); if (!context.Completed) { - Console.WriteLine("The signature is incomplete."); + ConsoleHelper.Error("The signature is incomplete."); return; } if (!(context.Verifiable is Transaction tx)) { - Console.WriteLine($"Only support to relay transaction."); + ConsoleHelper.Warning("Only support to relay transaction."); return; } tx.Witnesses = context.GetWitnesses(); NeoSystem.Blockchain.Tell(tx); - Console.WriteLine($"Data relay success, the hash is shown as follows:{Environment.NewLine}{tx.Hash}"); + Console.WriteLine($"Data relay success, the hash is shown as follows: {Environment.NewLine}{tx.Hash}"); } catch (Exception e) { - Console.WriteLine("Error: " + GetExceptionMessage(e)); + ConsoleHelper.Error(GetExceptionMessage(e)); } } } diff --git a/neo-cli/CLI/MainService.Node.cs b/neo-cli/CLI/MainService.Node.cs index bc4fe2294..df879e5a2 100644 --- a/neo-cli/CLI/MainService.Node.cs +++ b/neo-cli/CLI/MainService.Node.cs @@ -35,10 +35,10 @@ private void OnShowPoolCommand(bool verbose = false) NeoSystem.MemPool.GetVerifiedAndUnverifiedTransactions( out IEnumerable verifiedTransactions, out IEnumerable unverifiedTransactions); - Console.WriteLine("Verified Transactions:"); + ConsoleHelper.Info("Verified Transactions:"); foreach (Transaction tx in verifiedTransactions) Console.WriteLine($" {tx.Hash} {tx.GetType().Name} {tx.NetworkFee} GAS_NetFee"); - Console.WriteLine("Unverified Transactions:"); + ConsoleHelper.Info("Unverified Transactions:"); foreach (Transaction tx in unverifiedTransactions) Console.WriteLine($" {tx.Hash} {tx.GetType().Name} {tx.NetworkFee} GAS_NetFee"); @@ -86,8 +86,14 @@ private void OnShowStateCommand() int linesWritten = 1; foreach (RemoteNode node in LocalNode.GetRemoteNodes().OrderByDescending(u => u.LastBlockIndex).Take(Console.WindowHeight - 2).ToArray()) { - Console.WriteLine( - $" ip: {node.Remote.Address,-15}\tport: {node.Remote.Port,-5}\tlisten: {node.ListenerTcpPort,-5}\theight: {node.LastBlockIndex,-7}"); + ConsoleHelper.Info(" ip: ", + $"{ node.Remote.Address,-15}\t", + "port: ", + $"{node.Remote.Port,-5}\t", + "listen: ", + $"{node.ListenerTcpPort,-5}\t", + "height: ", + $"{node.LastBlockIndex,-7}"); linesWritten++; } diff --git a/neo-cli/CLI/MainService.Plugins.cs b/neo-cli/CLI/MainService.Plugins.cs index 04b452432..dabab9dba 100644 --- a/neo-cli/CLI/MainService.Plugins.cs +++ b/neo-cli/CLI/MainService.Plugins.cs @@ -64,11 +64,11 @@ private void OnInstallCommand(string pluginName) try { zip.ExtractToDirectory("."); - Console.WriteLine($"Install successful, please restart neo-cli."); + ConsoleHelper.Info("Install successful, please restart neo-cli."); } catch (IOException) { - Console.WriteLine($"Plugin already exist."); + ConsoleHelper.Warning($"Plugin already exist."); } } } @@ -83,12 +83,12 @@ private void OnUnInstallCommand(string pluginName) var plugin = Plugin.Plugins.FirstOrDefault(p => p.Name == pluginName); if (plugin is null) { - Console.WriteLine("Plugin not found"); + ConsoleHelper.Warning("Plugin not found"); return; } if (plugin is Logger) { - Console.WriteLine("You cannot uninstall a built-in plugin."); + ConsoleHelper.Warning("You cannot uninstall a built-in plugin."); return; } @@ -101,7 +101,7 @@ private void OnUnInstallCommand(string pluginName) catch (IOException) { } - Console.WriteLine($"Uninstall successful, please restart neo-cli."); + ConsoleHelper.Info("Uninstall successful, please restart neo-cli."); } /// @@ -116,12 +116,12 @@ private void OnPluginsCommand() foreach (Plugin plugin in Plugin.Plugins) { if (plugin is Logger) continue; - Console.WriteLine($"\t{plugin.Name,-20}{plugin.Description}"); + ConsoleHelper.Info($"\t{plugin.Name,-20}", plugin.Description); } } else { - Console.WriteLine("No loaded plugins"); + ConsoleHelper.Warning("No loaded plugins"); } } } diff --git a/neo-cli/CLI/MainService.Tools.cs b/neo-cli/CLI/MainService.Tools.cs index 8eaa1949a..05d6df487 100644 --- a/neo-cli/CLI/MainService.Tools.cs +++ b/neo-cli/CLI/MainService.Tools.cs @@ -58,7 +58,7 @@ private void OnParseCommand(string value) if (!any) { - Console.WriteLine($"Was not possible to convert: '{value}'"); + ConsoleHelper.Warning($"Was not possible to convert: '{value}'"); } } diff --git a/neo-cli/CLI/MainService.Vote.cs b/neo-cli/CLI/MainService.Vote.cs index db33eb8bb..b8ffdb988 100644 --- a/neo-cli/CLI/MainService.Vote.cs +++ b/neo-cli/CLI/MainService.Vote.cs @@ -11,8 +11,8 @@ using Neo.ConsoleService; using Neo.Cryptography.ECC; using Neo.IO.Json; -using Neo.SmartContract.Native; using Neo.SmartContract; +using Neo.SmartContract.Native; using Neo.VM; using Neo.VM.Types; using Neo.Wallets; @@ -32,21 +32,19 @@ partial class MainService private void OnRegisterCandidateCommand(UInt160 account) { var testGas = NativeContract.NEO.GetRegisterPrice(NeoSystem.StoreView) + (BigInteger)Math.Pow(10, NativeContract.GAS.Decimals) * 10; - if (NoWallet()) return; - WalletAccount currentAccount = CurrentWallet.GetAccount(account); if (currentAccount == null) { - Console.WriteLine("This address isn't in your wallet!"); + ConsoleHelper.Warning("This address isn't in your wallet!"); return; } else { if (currentAccount.Lock || currentAccount.WatchOnly) { - Console.WriteLine("Locked or WatchOnly address."); + ConsoleHelper.Warning("Locked or WatchOnly address."); return; } } @@ -70,19 +68,18 @@ private void OnRegisterCandidateCommand(UInt160 account) private void OnUnregisterCandidateCommand(UInt160 account) { if (NoWallet()) return; - WalletAccount currentAccount = CurrentWallet.GetAccount(account); if (currentAccount == null) { - Console.WriteLine("This address isn't in your wallet!"); + ConsoleHelper.Warning("This address isn't in your wallet!"); return; } else { if (currentAccount.Lock || currentAccount.WatchOnly) { - Console.WriteLine("Locked or WatchOnly address."); + ConsoleHelper.Warning("Locked or WatchOnly address."); return; } } @@ -107,7 +104,6 @@ private void OnUnregisterCandidateCommand(UInt160 account) private void OnVoteCommand(UInt160 senderAccount, ECPoint publicKey) { if (NoWallet()) return; - byte[] script; using (ScriptBuilder scriptBuilder = new ScriptBuilder()) { @@ -126,7 +122,6 @@ private void OnVoteCommand(UInt160 senderAccount, ECPoint publicKey) private void OnUnvoteCommand(UInt160 senderAccount) { if (NoWallet()) return; - byte[] script; using (ScriptBuilder scriptBuilder = new ScriptBuilder()) { @@ -150,7 +145,7 @@ private void OnGetCandidatesCommand() if (resJArray.Count > 0) { Console.WriteLine(); - Console.WriteLine("Candidates:"); + ConsoleHelper.Info("Candidates:"); foreach (var item in resJArray) { @@ -175,7 +170,7 @@ private void OnGetCommitteeCommand() if (resJArray.Count > 0) { Console.WriteLine(); - Console.WriteLine("Committee:"); + ConsoleHelper.Info("Committee:"); foreach (var item in resJArray) { @@ -197,7 +192,7 @@ private void OnGetNextBlockValidatorsCommand() if (resJArray.Count > 0) { Console.WriteLine(); - Console.WriteLine("Next validators:"); + ConsoleHelper.Info("Next validators:"); foreach (var item in resJArray) { @@ -212,7 +207,7 @@ private void OnGetNextBlockValidatorsCommand() [ConsoleCommand("get accountstate", Category = "Vote Commands")] private void OnGetAccountState(UInt160 address) { - string notice = "Notice: No vote record!"; + string notice = "No vote record!"; var arg = new JObject(); arg["type"] = "Hash160"; arg["value"] = address.ToString(); @@ -221,7 +216,7 @@ private void OnGetAccountState(UInt160 address) Console.WriteLine(); if (result.IsNull) { - Console.WriteLine(notice); + ConsoleHelper.Warning(notice); return; } var resJArray = (VM.Types.Array)result; @@ -229,14 +224,14 @@ private void OnGetAccountState(UInt160 address) { if (value.IsNull) { - Console.WriteLine(notice); + ConsoleHelper.Warning(notice); return; } } var publickey = ECPoint.Parse(((ByteString)resJArray?[2])?.GetSpan().ToHexString(), ECCurve.Secp256r1); - Console.WriteLine("Voted: " + Contract.CreateSignatureRedeemScript(publickey).ToScriptHash().ToAddress(NeoSystem.Settings.AddressVersion)); - Console.WriteLine("Amount: " + new BigDecimal(((Integer)resJArray?[0]).GetInteger(), NativeContract.NEO.Decimals)); - Console.WriteLine("Block: " + ((Integer)resJArray?[1]).GetInteger()); + ConsoleHelper.Info("Voted: ", Contract.CreateSignatureRedeemScript(publickey).ToScriptHash().ToAddress(NeoSystem.Settings.AddressVersion)); + ConsoleHelper.Info("Amount: ", new BigDecimal(((Integer)resJArray?[0]).GetInteger(), NativeContract.NEO.Decimals).ToString()); + ConsoleHelper.Info("Block: ", ((Integer)resJArray?[1]).GetInteger().ToString()); } } } diff --git a/neo-cli/CLI/MainService.Wallet.cs b/neo-cli/CLI/MainService.Wallet.cs index f6ea2dfcc..f4835a5fa 100644 --- a/neo-cli/CLI/MainService.Wallet.cs +++ b/neo-cli/CLI/MainService.Wallet.cs @@ -38,13 +38,13 @@ private void OnOpenWallet(string path) { if (!File.Exists(path)) { - Console.WriteLine($"File does not exist"); + ConsoleHelper.Error("File does not exist"); return; } string password = ReadUserInput("password", true); if (password.Length == 0) { - Console.WriteLine("Cancelled"); + ConsoleHelper.Info("Cancelled"); return; } try @@ -53,7 +53,7 @@ private void OnOpenWallet(string path) } catch (System.Security.Cryptography.CryptographicException) { - Console.WriteLine($"Failed to open file \"{path}\""); + ConsoleHelper.Error($"Failed to open file \"{path}\""); } } @@ -65,7 +65,7 @@ private void OnCloseWalletCommand() { if (NoWallet()) return; CurrentWallet = null; - Console.WriteLine($"Wallet is closed"); + ConsoleHelper.Info("Wallet is closed"); } /// @@ -76,24 +76,24 @@ private void OnUpgradeWalletCommand(string path) { if (Path.GetExtension(path).ToLowerInvariant() != ".db3") { - Console.WriteLine("Can't upgrade the wallet file."); + ConsoleHelper.Warning("Can't upgrade the wallet file. Check if your wallet is in db3 format."); return; } if (!File.Exists(path)) { - Console.WriteLine("File does not exist."); + ConsoleHelper.Error("File does not exist."); return; } string password = ReadUserInput("password", true); if (password.Length == 0) { - Console.WriteLine("Cancelled"); + ConsoleHelper.Info("Cancelled"); return; } string path_new = Path.ChangeExtension(path, ".json"); if (File.Exists(path_new)) { - Console.WriteLine($"File '{path_new}' already exists"); + ConsoleHelper.Warning($"File '{path_new}' already exists"); return; } NEP6Wallet.Migrate(path_new, path, password, NeoSystem.Settings).Save(); @@ -155,11 +155,11 @@ private void OnDeleteAddressCommand(UInt160 address) { wallet.Save(); } - Console.WriteLine($"Address {address} deleted."); + ConsoleHelper.Info($"Address {address} deleted."); } else { - Console.WriteLine($"Address {address} doesn't exist."); + ConsoleHelper.Warning($"Address {address} doesn't exist."); } } } @@ -175,18 +175,18 @@ private void OnExportKeyCommand(string path = null, UInt160 scriptHash = null) if (NoWallet()) return; if (path != null && File.Exists(path)) { - Console.WriteLine($"Error: File '{path}' already exists"); + ConsoleHelper.Error($"File '{path}' already exists"); return; } string password = ReadUserInput("password", true); if (password.Length == 0) { - Console.WriteLine("Cancelled"); + ConsoleHelper.Info("Cancelled"); return; } if (!CurrentWallet.VerifyPassword(password)) { - Console.WriteLine("Incorrect password"); + ConsoleHelper.Error("Incorrect password"); return; } IEnumerable keys; @@ -213,13 +213,13 @@ private void OnCreateWalletCommand(string path, string wifOrFile = null) string password = ReadUserInput("password", true); if (password.Length == 0) { - Console.WriteLine("Cancelled"); + ConsoleHelper.Info("Cancelled"); return; } string password2 = ReadUserInput("repeat password", true); if (password != password2) { - Console.WriteLine("Error"); + ConsoleHelper.Error("Two passwords not match."); return; } if (File.Exists(path)) @@ -245,7 +245,7 @@ private void OnImportMultisigAddress(ushort m, ECPoint[] publicKeys) if (m < 1 || m > n || n > 1024) { - Console.WriteLine("Error. Invalid parameters."); + ConsoleHelper.Error("Invalid parameters."); return; } @@ -256,7 +256,7 @@ private void OnImportMultisigAddress(ushort m, ECPoint[] publicKeys) if (CurrentWallet is NEP6Wallet wallet) wallet.Save(); - Console.WriteLine("Multisig. Addr.: " + multiSignContract.ScriptHash.ToAddress(NeoSystem.Settings.AddressVersion)); + ConsoleHelper.Info("Multisig. Addr.: ", multiSignContract.ScriptHash.ToAddress(NeoSystem.Settings.AddressVersion)); } /// @@ -278,7 +278,7 @@ private void OnImportKeyCommand(string wifOrFile) if (!fileInfo.Exists) { - Console.WriteLine($"Error: File '{fileInfo.FullName}' doesn't exists"); + ConsoleHelper.Error($"File '{fileInfo.FullName}' doesn't exists"); return; } @@ -309,8 +309,8 @@ private void OnImportKeyCommand(string wifOrFile) { WalletAccount account = CurrentWallet.CreateAccount(prikey); Array.Clear(prikey, 0, prikey.Length); - Console.WriteLine($"Address: {account.Address}"); - Console.WriteLine($" Pubkey: {account.GetKey().PublicKey.EncodePoint(true).ToHexString()}"); + ConsoleHelper.Info("Address: ", account.Address); + ConsoleHelper.Info(" Pubkey: ", account.GetKey().PublicKey.EncodePoint(true).ToHexString()); } if (CurrentWallet is NEP6Wallet wallet) wallet.Save(); @@ -335,7 +335,7 @@ private void OnImportWatchOnlyCommand(string addressOrFile) if (!fileInfo.Exists) { - Console.WriteLine($"Error: File '{fileInfo.FullName}' doesn't exists"); + ConsoleHelper.Warning($"File '{fileInfo.FullName}' doesn't exists"); return; } @@ -363,12 +363,12 @@ private void OnImportWatchOnlyCommand(string addressOrFile) WalletAccount account = CurrentWallet.GetAccount(address); if (account is not null) { - Console.WriteLine("This address is already in your wallet"); + ConsoleHelper.Warning("This address is already in your wallet"); } else { account = CurrentWallet.CreateAccount(address); - Console.WriteLine($"Address: {account.Address}"); + ConsoleHelper.Info("Address: ", account.Address); } } if (CurrentWallet is NEP6Wallet wallet) @@ -405,8 +405,8 @@ private void OnListAddressCommand() type = "Deployed-Nonstandard"; } - Console.WriteLine($"{" Address: "}{account.Address}\t{type}"); - Console.WriteLine($"{"ScriptHash: "}{account.ScriptHash}\n"); + ConsoleHelper.Info(" Address: ", $"{account.Address}\t{type}"); + ConsoleHelper.Info("ScriptHash: ", $"{account.ScriptHash}\n"); } } @@ -421,15 +421,15 @@ private void OnListAssetCommand() foreach (UInt160 account in CurrentWallet.GetAccounts().Select(p => p.ScriptHash)) { Console.WriteLine(account.ToAddress(NeoSystem.Settings.AddressVersion)); - Console.WriteLine($"NEO: {CurrentWallet.GetBalance(snapshot, NativeContract.NEO.Hash, account)}"); - Console.WriteLine($"GAS: {CurrentWallet.GetBalance(snapshot, NativeContract.GAS.Hash, account)}"); + ConsoleHelper.Info("NEO: ", $"{CurrentWallet.GetBalance(snapshot, NativeContract.NEO.Hash, account)}"); + ConsoleHelper.Info("GAS: ", $"{CurrentWallet.GetBalance(snapshot, NativeContract.GAS.Hash, account)}"); Console.WriteLine(); } Console.WriteLine("----------------------------------------------------"); - Console.WriteLine($"Total: NEO: {CurrentWallet.GetAvailable(snapshot, NativeContract.NEO.Hash),10} GAS: {CurrentWallet.GetAvailable(snapshot, NativeContract.GAS.Hash),18}"); + ConsoleHelper.Info("Total: NEO: ", $"{CurrentWallet.GetAvailable(snapshot, NativeContract.NEO.Hash),10} ", "GAS: ", $"{CurrentWallet.GetAvailable(snapshot, NativeContract.GAS.Hash),18}"); Console.WriteLine(); - Console.WriteLine("NEO hash: " + NativeContract.NEO.Hash); - Console.WriteLine("GAS hash: " + NativeContract.GAS.Hash); + ConsoleHelper.Info("NEO hash: ", NativeContract.NEO.Hash.ToString()); + ConsoleHelper.Info("GAS hash: ", NativeContract.GAS.Hash.ToString()); } /// @@ -441,9 +441,10 @@ private void OnListKeyCommand() if (NoWallet()) return; foreach (WalletAccount account in CurrentWallet.GetAccounts().Where(p => p.HasKey)) { - Console.WriteLine($" Address: {account.Address}"); - Console.WriteLine($"ScriptHash: {account.ScriptHash}"); - Console.WriteLine($" PublicKey: {account.GetKey().PublicKey.EncodePoint(true).ToHexString()}\n"); + ConsoleHelper.Info(" Address: ", account.Address); + ConsoleHelper.Info("ScriptHash: ", account.ScriptHash.ToString()); + ConsoleHelper.Info(" PublicKey: ", account.GetKey().PublicKey.EncodePoint(true).ToHexString()); + Console.WriteLine(); } } @@ -458,7 +459,7 @@ private void OnSignCommand(JObject jsonObjectToSign) if (jsonObjectToSign == null) { - Console.WriteLine("You must input JSON object pending signature data."); + ConsoleHelper.Warning("You must input JSON object pending signature data."); return; } try @@ -467,19 +468,19 @@ private void OnSignCommand(JObject jsonObjectToSign) ContractParametersContext context = ContractParametersContext.Parse(jsonObjectToSign.ToString(), snapshot); if (context.Network != neoSystem.Settings.Network) { - Console.WriteLine("Network mismatch."); + ConsoleHelper.Warning("Network mismatch."); return; } else if (!CurrentWallet.Sign(context)) { - Console.WriteLine("Non-existent private key in wallet."); + ConsoleHelper.Warning("Non-existent private key in wallet."); return; } - Console.WriteLine($"Signed Output:{Environment.NewLine}{context}"); + ConsoleHelper.Info("Signed Output: ", $"{Environment.NewLine}{context}"); } catch (Exception e) { - Console.WriteLine("Error: " + GetExceptionMessage(e)); + ConsoleHelper.Error(GetExceptionMessage(e)); } } @@ -499,12 +500,12 @@ private void OnSendCommand(UInt160 asset, UInt160 to, string amount, UInt160 fro string password = ReadUserInput("password", true); if (password.Length == 0) { - Console.WriteLine("Cancelled"); + ConsoleHelper.Info("Cancelled"); return; } if (!CurrentWallet.VerifyPassword(password)) { - Console.WriteLine("Incorrect password"); + ConsoleHelper.Error("Incorrect password"); return; } var snapshot = NeoSystem.StoreView; @@ -512,7 +513,7 @@ private void OnSendCommand(UInt160 asset, UInt160 to, string amount, UInt160 fro AssetDescriptor descriptor = new AssetDescriptor(snapshot, NeoSystem.Settings, asset); if (!BigDecimal.TryParse(amount, descriptor.Decimals, out BigDecimal decimalAmount) || decimalAmount.Sign <= 0) { - Console.WriteLine("Incorrect Amount Format"); + ConsoleHelper.Error("Incorrect Amount Format"); return; } try @@ -536,13 +537,13 @@ private void OnSendCommand(UInt160 asset, UInt160 to, string amount, UInt160 fro } catch (Exception e) { - Console.WriteLine("Error: " + GetExceptionMessage(e)); + ConsoleHelper.Error(GetExceptionMessage(e)); return; } if (tx == null) { - Console.WriteLine("Insufficient funds"); + ConsoleHelper.Warning("Insufficient funds"); return; } @@ -552,12 +553,11 @@ private void OnSendCommand(UInt160 asset, UInt160 to, string amount, UInt160 fro { tx.Witnesses = context.GetWitnesses(); NeoSystem.Blockchain.Tell(tx); - Console.WriteLine($"TXID: {tx.Hash}"); + ConsoleHelper.Info("TXID:\n", $"{tx.Hash}"); } else { - Console.WriteLine("SignatureContext:"); - Console.WriteLine(context.ToString()); + ConsoleHelper.Info("SignatureContext:\n", $"{context}"); } } @@ -573,7 +573,7 @@ private void OnShowGasCommand() uint height = NativeContract.Ledger.CurrentIndex(snapshot) + 1; foreach (UInt160 account in CurrentWallet.GetAccounts().Select(p => p.ScriptHash)) gas += NativeContract.NEO.UnclaimedGas(snapshot, account, height); - Console.WriteLine($"Unclaimed gas: {new BigDecimal(gas, NativeContract.GAS.Decimals)}"); + ConsoleHelper.Info("Unclaimed gas: ", new BigDecimal(gas, NativeContract.GAS.Decimals).ToString()); } /// @@ -586,19 +586,19 @@ private void OnChangePasswordCommand() string oldPassword = ReadUserInput("password", true); if (oldPassword.Length == 0) { - Console.WriteLine("Cancelled"); + ConsoleHelper.Info("Cancelled"); return; } if (!CurrentWallet.VerifyPassword(oldPassword)) { - Console.WriteLine("Incorrect password"); + ConsoleHelper.Error("Incorrect password"); return; } string newPassword = ReadUserInput("New password", true); string newPasswordReEntered = ReadUserInput("Re-Enter Password", true); if (!newPassword.Equals(newPasswordReEntered)) { - Console.WriteLine("Two passwords entered are inconsistent!"); + ConsoleHelper.Error("Two passwords entered are inconsistent!"); return; } @@ -607,7 +607,7 @@ private void OnChangePasswordCommand() string backupFile = wallet.Path + ".bak"; if (!File.Exists(wallet.Path) || File.Exists(backupFile)) { - Console.WriteLine("Wallet backup fail"); + ConsoleHelper.Error("Wallet backup fail"); return; } try @@ -616,7 +616,7 @@ private void OnChangePasswordCommand() } catch (IOException) { - Console.WriteLine("Wallet backup fail"); + ConsoleHelper.Error("Wallet backup fail"); return; } } @@ -630,7 +630,7 @@ private void OnChangePasswordCommand() } else { - Console.WriteLine("Failed to change password"); + ConsoleHelper.Error("Failed to change password"); } } @@ -643,7 +643,7 @@ private void SignAndSendTx(DataCache snapshot, Transaction tx) } catch (InvalidOperationException e) { - Console.WriteLine($"Error creating contract params: " + GetExceptionMessage(e)); + ConsoleHelper.Error("Failed creating contract params: " + GetExceptionMessage(e)); throw; } CurrentWallet.Sign(context); @@ -651,12 +651,11 @@ private void SignAndSendTx(DataCache snapshot, Transaction tx) { tx.Witnesses = context.GetWitnesses(); NeoSystem.Blockchain.Tell(tx); - Console.WriteLine($"Signed and relayed transaction with hash={tx.Hash}"); + ConsoleHelper.Info("Signed and relayed transaction with hash:\n", $"{tx.Hash}"); } else { - Console.WriteLine("Incomplete signature:"); - Console.WriteLine(context.ToString()); + ConsoleHelper.Info("Incomplete signature:\n", $"{context}"); } } } diff --git a/neo-cli/CLI/MainService.cs b/neo-cli/CLI/MainService.cs index 27f389766..5020f651e 100644 --- a/neo-cli/CLI/MainService.cs +++ b/neo-cli/CLI/MainService.cs @@ -145,15 +145,15 @@ public void CreateWallet(string path, string password, bool createDefaultAccount ((NEP6Wallet)CurrentWallet).Unlock(password); break; default: - Console.WriteLine("Wallet files in that format are not supported, please use a .json or .db3 file extension."); + ConsoleHelper.Warning("Wallet files in that format are not supported, please use a .json or .db3 file extension."); return; } if (createDefaultAccount) { WalletAccount account = CurrentWallet.CreateAccount(); - Console.WriteLine($" Address: {account.Address}"); - Console.WriteLine($" Pubkey: {account.GetKey().PublicKey.EncodePoint(true).ToHexString()}"); - Console.WriteLine($"ScriptHash: {account.ScriptHash}"); + ConsoleHelper.Info(" Address: ", account.Address); + ConsoleHelper.Info(" Pubkey: ", account.GetKey().PublicKey.EncodePoint(true).ToHexString()); + ConsoleHelper.Info("ScriptHash: ", $"{account.ScriptHash}"); } if (CurrentWallet is NEP6Wallet wallet) wallet.Save(); @@ -225,7 +225,7 @@ private IEnumerable GetBlocksFromFile() private bool NoWallet() { if (CurrentWallet != null) return false; - Console.WriteLine("You have to open the wallet first."); + ConsoleHelper.Error("You have to open the wallet first."); return true; } @@ -439,15 +439,15 @@ public async void Start(string[] args) } catch (FileNotFoundException) { - Console.WriteLine($"Warning: wallet file \"{Settings.Default.UnlockWallet.Path}\" not found."); + ConsoleHelper.Warning($"wallet file \"{Settings.Default.UnlockWallet.Path}\" not found."); } catch (System.Security.Cryptography.CryptographicException) { - Console.WriteLine($"Failed to open file \"{Settings.Default.UnlockWallet.Path}\""); + ConsoleHelper.Error($"Failed to open file \"{Settings.Default.UnlockWallet.Path}\""); } catch (Exception ex) { - Console.WriteLine($"error: {ex.GetBaseException().Message}"); + ConsoleHelper.Error(ex.GetBaseException().Message); } } } @@ -533,7 +533,7 @@ private void SendTransaction(byte[] script, UInt160 account = null, long gas = T try { Transaction tx = CurrentWallet.MakeTransaction(snapshot, script, account, signers, maxGas: gas); - Console.WriteLine($"Invoking script with: '{tx.Script.ToBase64String()}'"); + ConsoleHelper.Info("Invoking script with: ", $"'{tx.Script.ToBase64String()}'"); using (ApplicationEngine engine = ApplicationEngine.Run(tx.Script, snapshot, container: tx, settings: NeoSystem.Settings, gas: gas)) { @@ -550,7 +550,7 @@ private void SendTransaction(byte[] script, UInt160 account = null, long gas = T } catch (InvalidOperationException e) { - Console.WriteLine("Error: " + GetExceptionMessage(e)); + ConsoleHelper.Error(GetExceptionMessage(e)); return; } @@ -583,7 +583,7 @@ private bool OnInvokeWithResult(UInt160 scriptHash, string operation, out StackI ContractState contract = NativeContract.ContractManagement.GetContract(NeoSystem.StoreView, scriptHash); if (contract == null) { - Console.WriteLine("Contract does not exist."); + ConsoleHelper.Error("Contract does not exist."); result = StackItem.Null; return false; } @@ -591,7 +591,7 @@ private bool OnInvokeWithResult(UInt160 scriptHash, string operation, out StackI { if (contract.Manifest.Abi.GetMethod(operation, parameters.Count) == null) { - Console.WriteLine("This method does not not exist in this contract."); + ConsoleHelper.Error("This method does not not exist in this contract."); result = StackItem.Null; return false; } @@ -603,7 +603,7 @@ private bool OnInvokeWithResult(UInt160 scriptHash, string operation, out StackI { scriptBuilder.EmitDynamicCall(scriptHash, operation, parameters.ToArray()); script = scriptBuilder.ToArray(); - Console.WriteLine($"Invoking script with: '{script.ToBase64String()}'"); + ConsoleHelper.Info("Invoking script with: ", $"'{script.ToBase64String()}'"); } if (verificable is Transaction tx) @@ -619,14 +619,14 @@ private bool OnInvokeWithResult(UInt160 scriptHash, string operation, out StackI private void PrintExecutionOutput(ApplicationEngine engine, bool showStack = true) { - Console.WriteLine($"VM State: {engine.State}"); - Console.WriteLine($"Gas Consumed: {new BigDecimal((BigInteger)engine.GasConsumed, NativeContract.GAS.Decimals)}"); + ConsoleHelper.Info("VM State: ", engine.State.ToString()); + ConsoleHelper.Info("Gas Consumed: ", new BigDecimal((BigInteger)engine.GasConsumed, NativeContract.GAS.Decimals).ToString()); if (showStack) - Console.WriteLine($"Result Stack: {new JArray(engine.ResultStack.Select(p => p.ToJson()))}"); + ConsoleHelper.Info("Result Stack: ", new JArray(engine.ResultStack.Select(p => p.ToJson())).ToString()); if (engine.State == VMState.FAULT) - Console.WriteLine("Error: " + GetExceptionMessage(engine.FaultException)); + ConsoleHelper.Error(GetExceptionMessage(engine.FaultException)); } static string GetExceptionMessage(Exception exception)