From 906b3f25f694be513711e481e7a14bdb49987cb6 Mon Sep 17 00:00:00 2001 From: Anna Shaleva Date: Tue, 5 Sep 2023 08:47:40 +0300 Subject: [PATCH 01/30] DBFTPlugin: adapt Conflicts attribute verification (#802) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * DBFTPlugin: adapt Conflicts attribute verification Depends on https://github.com/neo-project/neo/pull/2818, see the https://github.com/neo-project/neo/pull/2818#issuecomment-1548814976. Signed-off-by: Anna Shaleva * Fix Conflicts attribute verification Fetch the update from core: https://github.com/neo-project/neo/pull/2818#issuecomment-1562554901. * Fetch on-chain conflict signer fix from core Use new API from https://github.com/neo-project/neo/pull/2818/commits/ee7333f1696b66a59a742abcf7d6615528db9724. --------- Signed-off-by: Anna Shaleva Co-authored-by: Vitor Nazário Coelho Co-authored-by: Owen Zhang <38493437+superboyiii@users.noreply.github.com> Co-authored-by: Jimmy --- .../Consensus/ConsensusService.OnMessage.cs | 13 ++++++++ src/DBFTPlugin/Consensus/ConsensusService.cs | 33 ++++++++++++++++++- 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/DBFTPlugin/Consensus/ConsensusService.OnMessage.cs b/src/DBFTPlugin/Consensus/ConsensusService.OnMessage.cs index df358fdc4..cac84a8d4 100644 --- a/src/DBFTPlugin/Consensus/ConsensusService.OnMessage.cs +++ b/src/DBFTPlugin/Consensus/ConsensusService.OnMessage.cs @@ -127,13 +127,26 @@ private void OnPrepareRequestReceived(ExtensiblePayload payload, PrepareRequest { if (mempoolVerified.TryGetValue(hash, out Transaction tx)) { + if (NativeContract.Ledger.ContainsConflictHash(context.Snapshot, hash, tx.Signers.Select(s => s.Account))) + { + Log($"Invalid request: transaction has on-chain conflict", LogLevel.Warning); + return; + } + if (!AddTransaction(tx, false)) return; } else { if (neoSystem.MemPool.TryGetValue(hash, out tx)) + { + if (NativeContract.Ledger.ContainsConflictHash(context.Snapshot, hash, tx.Signers.Select(s => s.Account))) + { + Log($"Invalid request: transaction has on-chain conflict", LogLevel.Warning); + return; + } unverified.Add(tx); + } } } foreach (Transaction tx in unverified) diff --git a/src/DBFTPlugin/Consensus/ConsensusService.cs b/src/DBFTPlugin/Consensus/ConsensusService.cs index e50ab42d2..dc8f66ff1 100644 --- a/src/DBFTPlugin/Consensus/ConsensusService.cs +++ b/src/DBFTPlugin/Consensus/ConsensusService.cs @@ -257,7 +257,38 @@ private bool AddTransaction(Transaction tx, bool verify) { if (verify) { - VerifyResult result = tx.Verify(neoSystem.Settings, context.Snapshot, context.VerificationContext); + // At this step we're sure that there's no on-chain transaction that conflicts with + // the provided tx because of the previous Blockchain's OnReceive check. Thus, we only + // need to check that current context doesn't contain conflicting transactions. + VerifyResult result; + + // Firstly, check whether tx has Conlicts attribute with the hash of one of the context's transactions. + foreach (var h in tx.GetAttributes().Select(attr => attr.Hash)) + { + if (context.TransactionHashes.Contains(h)) + { + result = VerifyResult.HasConflicts; + Log($"Rejected tx: {tx.Hash}, {result}{Environment.NewLine}{tx.ToArray().ToHexString()}", LogLevel.Warning); + RequestChangeView(ChangeViewReason.TxInvalid); + return false; + } + } + // After that, check whether context's transactions have Conflicts attribute with tx's hash. + foreach (var pooledTx in context.Transactions.Values) + { + if (pooledTx.GetAttributes().Select(attr => attr.Hash).Contains(tx.Hash)) + { + result = VerifyResult.HasConflicts; + Log($"Rejected tx: {tx.Hash}, {result}{Environment.NewLine}{tx.ToArray().ToHexString()}", LogLevel.Warning); + RequestChangeView(ChangeViewReason.TxInvalid); + return false; + } + } + + // We've ensured that there's no conlicting transactions in the context, thus, can safely provide an empty conflicting list + // for futher verification. + var conflictingTxs = new List(); + result = tx.Verify(neoSystem.Settings, context.Snapshot, context.VerificationContext, conflictingTxs); if (result != VerifyResult.Succeed) { Log($"Rejected tx: {tx.Hash}, {result}{Environment.NewLine}{tx.ToArray().ToHexString()}", LogLevel.Warning); From 1416bb986fa44ed258a7b314b3cff55c9f93af1f Mon Sep 17 00:00:00 2001 From: Shargon Date: Tue, 5 Sep 2023 12:18:52 +0200 Subject: [PATCH 02/30] Fix 3.6 (#816) * Fix 3.6 * Update nuget * Fix version --- src/DBFTPlugin/Consensus/ConsensusService.cs | 2 +- src/Directory.Build.props | 4 ++-- src/RocksDBStore/RocksDBStore.csproj | 2 +- src/SQLiteWallet/SQLiteWallet.csproj | 2 +- .../Neo.Cryptography.MPTTrie.Tests.csproj | 6 ++++++ .../Neo.Network.RPC.Tests.csproj | 12 +++++++++--- .../Neo.Plugins.OracleService.Tests.csproj | 10 ++++++++-- .../Neo.Plugins.RpcServer.Tests.csproj | 8 +++++++- .../Neo.Plugins.Storage.Tests.csproj | 6 ++++++ 9 files changed, 41 insertions(+), 11 deletions(-) diff --git a/src/DBFTPlugin/Consensus/ConsensusService.cs b/src/DBFTPlugin/Consensus/ConsensusService.cs index dc8f66ff1..dcf17f84f 100644 --- a/src/DBFTPlugin/Consensus/ConsensusService.cs +++ b/src/DBFTPlugin/Consensus/ConsensusService.cs @@ -45,7 +45,7 @@ private class Timer { public uint Height; public byte ViewNumber; } /// This will be cleared every block (so it will not grow out of control, but is used to prevent repeatedly /// responding to the same message. /// - private readonly HashSet knownHashes = new HashSet(); + private readonly HashSet knownHashes = new(); /// /// This variable is only true during OnRecoveryMessageReceived /// diff --git a/src/Directory.Build.props b/src/Directory.Build.props index edf759437..cc6740f46 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -2,7 +2,7 @@ - 3.5.0 + 3.6.0 net7.0 Neo.Plugins The Neo Project @@ -21,7 +21,7 @@ - + diff --git a/src/RocksDBStore/RocksDBStore.csproj b/src/RocksDBStore/RocksDBStore.csproj index 4ab704d0e..d098bb8d3 100644 --- a/src/RocksDBStore/RocksDBStore.csproj +++ b/src/RocksDBStore/RocksDBStore.csproj @@ -6,7 +6,7 @@ - + diff --git a/src/SQLiteWallet/SQLiteWallet.csproj b/src/SQLiteWallet/SQLiteWallet.csproj index 49b8de1e8..e1d77a3f1 100644 --- a/src/SQLiteWallet/SQLiteWallet.csproj +++ b/src/SQLiteWallet/SQLiteWallet.csproj @@ -7,7 +7,7 @@ - + diff --git a/tests/Neo.Cryptography.MPTTrie.Tests/Neo.Cryptography.MPTTrie.Tests.csproj b/tests/Neo.Cryptography.MPTTrie.Tests/Neo.Cryptography.MPTTrie.Tests.csproj index 1b75c6025..aec30cd98 100644 --- a/tests/Neo.Cryptography.MPTTrie.Tests/Neo.Cryptography.MPTTrie.Tests.csproj +++ b/tests/Neo.Cryptography.MPTTrie.Tests/Neo.Cryptography.MPTTrie.Tests.csproj @@ -7,4 +7,10 @@ + + + + + + diff --git a/tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj b/tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj index 03a168e92..9815f51e9 100644 --- a/tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj +++ b/tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj @@ -5,9 +5,9 @@ - - - + + + all runtime; build; native; contentfiles; analyzers; buildtransitive @@ -23,4 +23,10 @@ + + + + + + diff --git a/tests/Neo.Plugins.OracleService.Tests/Neo.Plugins.OracleService.Tests.csproj b/tests/Neo.Plugins.OracleService.Tests/Neo.Plugins.OracleService.Tests.csproj index ca84e4303..f2a836e3c 100644 --- a/tests/Neo.Plugins.OracleService.Tests/Neo.Plugins.OracleService.Tests.csproj +++ b/tests/Neo.Plugins.OracleService.Tests/Neo.Plugins.OracleService.Tests.csproj @@ -6,12 +6,18 @@ - - + + + + + + + + diff --git a/tests/Neo.Plugins.RpcServer.Tests/Neo.Plugins.RpcServer.Tests.csproj b/tests/Neo.Plugins.RpcServer.Tests/Neo.Plugins.RpcServer.Tests.csproj index 422b0ae28..6105eaf11 100644 --- a/tests/Neo.Plugins.RpcServer.Tests/Neo.Plugins.RpcServer.Tests.csproj +++ b/tests/Neo.Plugins.RpcServer.Tests/Neo.Plugins.RpcServer.Tests.csproj @@ -10,7 +10,13 @@ - + + + + + + + diff --git a/tests/Neo.Plugins.Storage.Tests/Neo.Plugins.Storage.Tests.csproj b/tests/Neo.Plugins.Storage.Tests/Neo.Plugins.Storage.Tests.csproj index c6798b71a..2cdcc8345 100644 --- a/tests/Neo.Plugins.Storage.Tests/Neo.Plugins.Storage.Tests.csproj +++ b/tests/Neo.Plugins.Storage.Tests/Neo.Plugins.Storage.Tests.csproj @@ -9,4 +9,10 @@ + + + + + + From 09c2879958a916e0867fc78c64a04edfabe6935f Mon Sep 17 00:00:00 2001 From: Owen Zhang <38493437+superboyiii@users.noreply.github.com> Date: Tue, 5 Sep 2023 19:02:04 +0800 Subject: [PATCH 03/30] remove Travis logo (#818) --- README.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/README.md b/README.md index 0919ba2fd..91e0aa3b4 100644 --- a/README.md +++ b/README.md @@ -7,9 +7,6 @@

- - Current TravisCI build status. - License From 3e0efe6583f14f15e0c41df7b3302f6fc6160d5e Mon Sep 17 00:00:00 2001 From: Shine Li Date: Wed, 13 Sep 2023 18:34:03 +0800 Subject: [PATCH 04/30] init (#821) --- src/RpcServer/RpcServer.SmartContract.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/RpcServer/RpcServer.SmartContract.cs b/src/RpcServer/RpcServer.SmartContract.cs index cf22c2780..1a7c24c17 100644 --- a/src/RpcServer/RpcServer.SmartContract.cs +++ b/src/RpcServer/RpcServer.SmartContract.cs @@ -23,6 +23,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading; +using Array = System.Array; namespace Neo.Plugins { @@ -169,9 +170,9 @@ private static Signer[] SignersFromJson(JArray _params, ProtocolSettings setting { Account = AddressToScriptHash(u["account"].AsString(), settings.AddressVersion), Scopes = (WitnessScope)Enum.Parse(typeof(WitnessScope), u["scopes"]?.AsString()), - AllowedContracts = ((JArray)u["allowedcontracts"])?.Select(p => UInt160.Parse(p.AsString())).ToArray(), - AllowedGroups = ((JArray)u["allowedgroups"])?.Select(p => ECPoint.Parse(p.AsString(), ECCurve.Secp256r1)).ToArray(), - Rules = ((JArray)u["rules"])?.Select(r => WitnessRule.FromJson((JObject)r)).ToArray(), + AllowedContracts = ((JArray)u["allowedcontracts"])?.Select(p => UInt160.Parse(p.AsString())).ToArray() ?? Array.Empty(), + AllowedGroups = ((JArray)u["allowedgroups"])?.Select(p => ECPoint.Parse(p.AsString(), ECCurve.Secp256r1)).ToArray() ?? Array.Empty(), + Rules = ((JArray)u["rules"])?.Select(r => WitnessRule.FromJson((JObject)r)).ToArray() ?? Array.Empty(), }).ToArray(); // Validate format From 63e3ec3dc4092ea83f010b1fe9704a70129fbcda Mon Sep 17 00:00:00 2001 From: edge Date: Fri, 15 Sep 2023 11:16:08 +0100 Subject: [PATCH 05/30] add hardfork settings to getversion (#823) --- src/RpcServer/RpcServer.Node.cs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/RpcServer/RpcServer.Node.cs b/src/RpcServer/RpcServer.Node.cs index 7c8dfeaa8..4c6a0109a 100644 --- a/src/RpcServer/RpcServer.Node.cs +++ b/src/RpcServer/RpcServer.Node.cs @@ -82,6 +82,13 @@ protected virtual JToken GetVersion(JArray _params) json["protocol"]["maxtransactionsperblock"] = system.Settings.MaxTransactionsPerBlock; json["protocol"]["memorypoolmaxtransactions"] = system.Settings.MemoryPoolMaxTransactions; json["protocol"]["initialgasdistribution"] = system.Settings.InitialGasDistribution; + json["protocol"]["hardforks"] = new JArray(system.Settings.Hardforks.Select(hf => + { + JObject forkJson = new(); + forkJson["name"] = hf.Key; + forkJson["blockheight"] = hf.Value; + return forkJson; + })); return json; } From d36dcbbad6aca803eb49b562ba791843e51d5b8d Mon Sep 17 00:00:00 2001 From: Shine Li Date: Mon, 25 Sep 2023 11:19:51 +0800 Subject: [PATCH 06/30] Fix RpcClient TxConflict (#830) * init * support not valid before --- src/RpcClient/Utility.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/RpcClient/Utility.cs b/src/RpcClient/Utility.cs index 159af4046..24b7b8551 100644 --- a/src/RpcClient/Utility.cs +++ b/src/RpcClient/Utility.cs @@ -197,6 +197,14 @@ public static TransactionAttribute TransactionAttributeFromJson(JObject json) Code = Enum.Parse(json["code"].AsString()), Result = Convert.FromBase64String(json["result"].AsString()), }, + TransactionAttributeType.NotValidBefore => new NotValidBefore() + { + Height = (uint)json["height"].AsNumber(), + }, + TransactionAttributeType.Conflicts => new Conflicts() + { + Hash = UInt256.Parse(json["hash"].AsString()) + }, _ => throw new FormatException(), }; } From 7b4145caa64c785b322d9169bdc34e5db0d1980b Mon Sep 17 00:00:00 2001 From: Owen Zhang <38493437+superboyiii@users.noreply.github.com> Date: Mon, 25 Sep 2023 23:08:35 +0800 Subject: [PATCH 07/30] v3.6.1 (#831) --- src/Directory.Build.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Directory.Build.props b/src/Directory.Build.props index cc6740f46..717700b72 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -2,7 +2,7 @@ - 3.6.0 + 3.6.1 net7.0 Neo.Plugins The Neo Project From 6ead78007ba6003eb050f7c7bffeb4e2476f348e Mon Sep 17 00:00:00 2001 From: Christopher Schuchardt Date: Tue, 26 Sep 2023 07:46:58 -0400 Subject: [PATCH 08/30] Added hardfork to RpcClient (#825) * Added hardfork to RpcClient * fixed unit test for getversionasync --- src/RpcClient/Models/RpcVersion.cs | 10 ++++++++++ tests/Neo.Network.RPC.Tests/RpcTestCases.json | 8 +++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/RpcClient/Models/RpcVersion.cs b/src/RpcClient/Models/RpcVersion.cs index d978c2991..2b02dd714 100644 --- a/src/RpcClient/Models/RpcVersion.cs +++ b/src/RpcClient/Models/RpcVersion.cs @@ -9,6 +9,9 @@ // modifications are permitted. using Neo.Json; +using System; +using System.Collections.Generic; +using System.Linq; namespace Neo.Network.RPC.Models { @@ -25,6 +28,7 @@ public class RpcProtocol public uint MaxTransactionsPerBlock { get; set; } public int MemoryPoolMaxTransactions { get; set; } public ulong InitialGasDistribution { get; set; } + public IReadOnlyDictionary Hardforks { get; set; } public JObject ToJson() { @@ -38,6 +42,11 @@ public JObject ToJson() json["maxtransactionsperblock"] = MaxTransactionsPerBlock; json["memorypoolmaxtransactions"] = MemoryPoolMaxTransactions; json["initialgasdistribution"] = InitialGasDistribution; + json["hardforks"] = new JArray(Hardforks.Select(s => new JObject() + { + ["name"] = s.Key, + ["blockheight"] = s.Value, + })); return json; } @@ -54,6 +63,7 @@ public static RpcProtocol FromJson(JObject json) MaxTransactionsPerBlock = (uint)json["maxtransactionsperblock"].AsNumber(), MemoryPoolMaxTransactions = (int)json["memorypoolmaxtransactions"].AsNumber(), InitialGasDistribution = (ulong)json["initialgasdistribution"].AsNumber(), + Hardforks = new Dictionary(((JArray)json["hardforks"]).Select(s => new KeyValuePair(Enum.Parse(s["name"].AsString()), (uint)s["blockheight"].AsNumber()))), }; } } diff --git a/tests/Neo.Network.RPC.Tests/RpcTestCases.json b/tests/Neo.Network.RPC.Tests/RpcTestCases.json index f8b1e59b8..b65d4da18 100644 --- a/tests/Neo.Network.RPC.Tests/RpcTestCases.json +++ b/tests/Neo.Network.RPC.Tests/RpcTestCases.json @@ -2491,7 +2491,13 @@ "addressversion": 0, "maxtransactionsperblock": 0, "memorypoolmaxtransactions": 0, - "initialgasdistribution": 0 + "initialgasdistribution": 0, + "hardforks": [ + { + "name": "HF_Aspidochelone", + "blockheight": 0 + } + ] } } } From 12746bf301c86729f7724802409df041fd7c9bcf Mon Sep 17 00:00:00 2001 From: Anna Shaleva Date: Sun, 15 Oct 2023 08:00:54 +0300 Subject: [PATCH 09/30] RpcServer, RpcClient: strip HF_ prefix from `getversion` response (#838) * RpcServer, RpcClient: strip HF_ prefix from `getversion` response It's nice to have clear hardfork ame without hardfork prefix so that the resulting hardfork JSON-ized name can be applicable by both C# and NeoGo nodes. Signed-off-by: Anna Shaleva * tests: adjust `getversion` test response Strip `HF_` prefix from the hardforks response. Fix @cschuchardt88's review: https://github.com/neo-project/neo-modules/pull/838#discussion_r1357709898. Signed-off-by: Anna Shaleva * Check `HF_` prefix before cutting/adding it to JSON-ized hardforks Fix @shargon's review: https://github.com/neo-project/neo-modules/pull/838#pullrequestreview-1675991434. Signed-off-by: Anna Shaleva --------- Signed-off-by: Anna Shaleva --- src/RpcClient/Models/RpcVersion.cs | 15 +++++++++++++-- src/RpcServer/RpcServer.Node.cs | 8 +++++++- tests/Neo.Network.RPC.Tests/RpcTestCases.json | 2 +- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/RpcClient/Models/RpcVersion.cs b/src/RpcClient/Models/RpcVersion.cs index 2b02dd714..286006fb0 100644 --- a/src/RpcClient/Models/RpcVersion.cs +++ b/src/RpcClient/Models/RpcVersion.cs @@ -44,7 +44,8 @@ public JObject ToJson() json["initialgasdistribution"] = InitialGasDistribution; json["hardforks"] = new JArray(Hardforks.Select(s => new JObject() { - ["name"] = s.Key, + // Strip HF_ prefix. + ["name"] = StripPrefix(s.Key.ToString(), "HF_"), ["blockheight"] = s.Value, })); return json; @@ -63,9 +64,19 @@ public static RpcProtocol FromJson(JObject json) MaxTransactionsPerBlock = (uint)json["maxtransactionsperblock"].AsNumber(), MemoryPoolMaxTransactions = (int)json["memorypoolmaxtransactions"].AsNumber(), InitialGasDistribution = (ulong)json["initialgasdistribution"].AsNumber(), - Hardforks = new Dictionary(((JArray)json["hardforks"]).Select(s => new KeyValuePair(Enum.Parse(s["name"].AsString()), (uint)s["blockheight"].AsNumber()))), + Hardforks = new Dictionary(((JArray)json["hardforks"]).Select(s => + { + var name = s["name"].AsString(); + // Add HF_ prefix to the hardfork response for proper Hardfork enum parsing. + return new KeyValuePair(Enum.Parse(name.StartsWith("HF_") ? name : $"HF_{name}"), (uint)s["blockheight"].AsNumber()); + })), }; } + + private static string StripPrefix(string s, string prefix) + { + return s.StartsWith(prefix) ? s.Substring(prefix.Length) : s; + } } public int TcpPort { get; set; } diff --git a/src/RpcServer/RpcServer.Node.cs b/src/RpcServer/RpcServer.Node.cs index 4c6a0109a..519f85498 100644 --- a/src/RpcServer/RpcServer.Node.cs +++ b/src/RpcServer/RpcServer.Node.cs @@ -85,13 +85,19 @@ protected virtual JToken GetVersion(JArray _params) json["protocol"]["hardforks"] = new JArray(system.Settings.Hardforks.Select(hf => { JObject forkJson = new(); - forkJson["name"] = hf.Key; + // Strip "HF_" prefix. + forkJson["name"] = StripPrefix(hf.Key.ToString(), "HF_"); forkJson["blockheight"] = hf.Value; return forkJson; })); return json; } + private static string StripPrefix(string s, string prefix) + { + return s.StartsWith(prefix) ? s.Substring(prefix.Length) : s; + } + [RpcMethod] protected virtual JToken SendRawTransaction(JArray _params) { diff --git a/tests/Neo.Network.RPC.Tests/RpcTestCases.json b/tests/Neo.Network.RPC.Tests/RpcTestCases.json index b65d4da18..903d48307 100644 --- a/tests/Neo.Network.RPC.Tests/RpcTestCases.json +++ b/tests/Neo.Network.RPC.Tests/RpcTestCases.json @@ -2494,7 +2494,7 @@ "initialgasdistribution": 0, "hardforks": [ { - "name": "HF_Aspidochelone", + "name": "Aspidochelone", "blockheight": 0 } ] From 4f55458bda29a0e80258add2a3768dcc014ab24d Mon Sep 17 00:00:00 2001 From: Shine Li Date: Mon, 23 Oct 2023 14:55:42 +0800 Subject: [PATCH 10/30] Add Cancel Tx RpcApi (#837) * init * Update src/RpcServer/RpcServer.Wallet.cs Co-authored-by: Christopher Schuchardt * Update src/RpcServer/RpcServer.Wallet.cs Co-authored-by: Owen Zhang <38493437+superboyiii@users.noreply.github.com> * Update src/RpcServer/RpcServer.Wallet.cs Co-authored-by: Owen Zhang <38493437+superboyiii@users.noreply.github.com> * Clean empty lines * Clean empty lines * Update src/RpcServer/RpcServer.Wallet.cs --------- Co-authored-by: Christopher Schuchardt Co-authored-by: Owen Zhang <38493437+superboyiii@users.noreply.github.com> Co-authored-by: Shargon Co-authored-by: Jimmy --- src/RpcClient/RpcClient.cs | 10 ++++++ src/RpcServer/RpcServer.Wallet.cs | 51 +++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) diff --git a/src/RpcClient/RpcClient.cs b/src/RpcClient/RpcClient.cs index 957025f1a..6291ce044 100644 --- a/src/RpcClient/RpcClient.cs +++ b/src/RpcClient/RpcClient.cs @@ -645,6 +645,16 @@ public async Task SendToAddressAsync(string assetId, string address, st .ConfigureAwait(false); } + ///

+ /// Cancel Tx. + /// + /// This function returns Signed Transaction JSON if successful, ContractParametersContext JSON if signing failed. + public async Task CancelTransactionAsync(UInt256 txId, string[] signers, string extraFee) + { + JToken[] parameters = signers.Select(s => (JString)s.AsScriptHash()).ToArray(); + return (JObject)await RpcSendAsync(GetRpcName(), txId.ToString(), new JArray(parameters), extraFee).ConfigureAwait(false); + } + #endregion Wallet #region Plugins diff --git a/src/RpcServer/RpcServer.Wallet.cs b/src/RpcServer/RpcServer.Wallet.cs index 7ced0421a..097dafcd3 100644 --- a/src/RpcServer/RpcServer.Wallet.cs +++ b/src/RpcServer/RpcServer.Wallet.cs @@ -319,6 +319,57 @@ protected virtual JToken SendToAddress(JArray _params) return SignAndRelay(snapshot, tx); } + [RpcMethod] + protected virtual JToken CancelTransaction(JArray _params) + { + CheckWallet(); + var txid = UInt256.Parse(_params[0].AsString()); + TransactionState state = NativeContract.Ledger.GetTransactionState(system.StoreView, txid); + if (state != null) + { + throw new RpcException(32700, "This tx is already confirmed, can't be cancelled."); + } + + var conflict = new TransactionAttribute[] { new Conflicts() { Hash = txid } }; + Signer[] signers = _params.Count >= 2 ? ((JArray)_params[1]).Select(j => new Signer() { Account = AddressToScriptHash(j.AsString(), system.Settings.AddressVersion), Scopes = WitnessScope.None }).ToArray() : Array.Empty(); + if (!signers.Any()) + { + throw new RpcException(32701, "no signers"); + } + + Transaction tx = new Transaction + { + Signers = signers, + Attributes = conflict, + Witnesses = Array.Empty(), + }; + + try + { + tx = wallet.MakeTransaction(system.StoreView, new[] { (byte)OpCode.RET }, signers[0].Account, signers, conflict); + } + catch (InvalidOperationException e) + { + throw new RpcException(-500, GetExceptionMessage(e)); + } + + if (system.MemPool.TryGetValue(txid, out Transaction conflictTx)) + { + tx.NetworkFee = Math.Max(tx.NetworkFee, conflictTx.NetworkFee) + 1; + } + else if (_params.Count >= 3) + { + var extraFee = _params[2].AsString(); + AssetDescriptor descriptor = new(system.StoreView, system.Settings, NativeContract.GAS.Hash); + if (!BigDecimal.TryParse(extraFee, descriptor.Decimals, out BigDecimal decimalExtraFee) || decimalExtraFee.Sign <= 0) + { + throw new RpcException(32702, "Incorrect Amount Format"); + } + tx.NetworkFee += (long)decimalExtraFee.Value; + }; + return SignAndRelay(system.StoreView, tx); + } + [RpcMethod] protected virtual JToken InvokeContractVerify(JArray _params) { From 35993a4dbcf78e889c35c00a0cbb019cafe42e3d Mon Sep 17 00:00:00 2001 From: Christopher Schuchardt Date: Tue, 7 Nov 2023 23:14:14 -0500 Subject: [PATCH 11/30] RpcClient: Check for NEP17 Transfer (#833) * added issue 775 * changed with output * changed error to match error of spec * fixed exception output * fixed issue 775 * Added `.ConfigureAwait(false)` to `InvokeScriptAsync` * Removed unused namespaces and fixed formatting * fixed tests for CreateTransferTxAsync * Code comment removed for invalid param * Use Assert in script for nep-17 transfers Revert "v3.6.1 (#831)" This reverts commit 7b4145caa64c785b322d9169bdc34e5db0d1980b. * fixed tests * Update Directory.Build.props guess i went back to much * Add argument --------- Co-authored-by: Shargon Co-authored-by: Owen Zhang <38493437+superboyiii@users.noreply.github.com> --- src/RpcClient/Nep17API.cs | 14 ++++++++--- src/RpcClient/WalletAPI.cs | 28 +++++++++++++-------- tests/Neo.Network.RPC.Tests/UT_Nep17API.cs | 12 ++++++--- tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs | 23 +++++++++++------ 4 files changed, 51 insertions(+), 26 deletions(-) diff --git a/src/RpcClient/Nep17API.cs b/src/RpcClient/Nep17API.cs index 54fde2e6e..f0aa19dfd 100644 --- a/src/RpcClient/Nep17API.cs +++ b/src/RpcClient/Nep17API.cs @@ -132,15 +132,18 @@ public async Task GetTokenInfoAsync(string contractHash) /// to account script hash /// transfer amount /// onPayment data + /// Add assert at the end of the script /// - public async Task CreateTransferTxAsync(UInt160 scriptHash, KeyPair fromKey, UInt160 to, BigInteger amount, object data = null) + public async Task CreateTransferTxAsync(UInt160 scriptHash, KeyPair fromKey, UInt160 to, BigInteger amount, object data = null, bool addAssert = true) { var sender = Contract.CreateSignatureRedeemScript(fromKey.PublicKey).ToScriptHash(); Signer[] signers = new[] { new Signer { Scopes = WitnessScope.CalledByEntry, Account = sender } }; byte[] script = scriptHash.MakeScript("transfer", sender, to, amount, data); + if (addAssert) script = script.Concat(new[] { (byte)OpCode.ASSERT }).ToArray(); - TransactionManagerFactory factory = new TransactionManagerFactory(rpcClient); + TransactionManagerFactory factory = new(rpcClient); TransactionManager manager = await factory.MakeTransactionAsync(script, signers).ConfigureAwait(false); + return await manager .AddSignature(fromKey) .SignAsync().ConfigureAwait(false); @@ -156,17 +159,20 @@ public async Task CreateTransferTxAsync(UInt160 scriptHash, KeyPair /// to account /// transfer amount /// onPayment data + /// Add assert at the end of the script /// - public async Task CreateTransferTxAsync(UInt160 scriptHash, int m, ECPoint[] pubKeys, KeyPair[] fromKeys, UInt160 to, BigInteger amount, object data = null) + public async Task CreateTransferTxAsync(UInt160 scriptHash, int m, ECPoint[] pubKeys, KeyPair[] fromKeys, UInt160 to, BigInteger amount, object data = null, bool addAssert = true) { if (m > fromKeys.Length) throw new ArgumentException($"Need at least {m} KeyPairs for signing!"); var sender = Contract.CreateMultiSigContract(m, pubKeys).ScriptHash; Signer[] signers = new[] { new Signer { Scopes = WitnessScope.CalledByEntry, Account = sender } }; byte[] script = scriptHash.MakeScript("transfer", sender, to, amount, data); + if (addAssert) script = script.Concat(new[] { (byte)OpCode.ASSERT }).ToArray(); - TransactionManagerFactory factory = new TransactionManagerFactory(rpcClient); + TransactionManagerFactory factory = new(rpcClient); TransactionManager manager = await factory.MakeTransactionAsync(script, signers).ConfigureAwait(false); + return await manager .AddMultiSig(fromKeys, m, pubKeys) .SignAsync().ConfigureAwait(false); diff --git a/src/RpcClient/WalletAPI.cs b/src/RpcClient/WalletAPI.cs index fc66fc131..8cac51763 100644 --- a/src/RpcClient/WalletAPI.cs +++ b/src/RpcClient/WalletAPI.cs @@ -109,11 +109,12 @@ public Task GetTokenBalanceAsync(string tokenHash, string account) /// /// wif or private key /// Example: WIF ("KyXwTh1hB76RRMquSvnxZrJzQx7h9nQP2PCRL38v6VDb5ip3nf1p"), PrivateKey ("450d6c2a04b5b470339a745427bae6828400cf048400837d73c415063835e005") + /// Add assert at the end of the script /// The transaction sended - public Task ClaimGasAsync(string key) + public Task ClaimGasAsync(string key, bool addAssert = true) { KeyPair keyPair = Utility.GetKeyPair(key); - return ClaimGasAsync(keyPair); + return ClaimGasAsync(keyPair, addAssert); } /// @@ -121,12 +122,13 @@ public Task ClaimGasAsync(string key) /// This function will transfer NEO balance from account to itself /// /// keyPair + /// Add assert at the end of the script /// The transaction sended - public async Task ClaimGasAsync(KeyPair keyPair) + public async Task ClaimGasAsync(KeyPair keyPair, bool addAssert = true) { UInt160 toHash = Contract.CreateSignatureRedeemScript(keyPair.PublicKey).ToScriptHash(); BigInteger balance = await nep17API.BalanceOfAsync(NativeContract.NEO.Hash, toHash).ConfigureAwait(false); - Transaction transaction = await nep17API.CreateTransferTxAsync(NativeContract.NEO.Hash, keyPair, toHash, balance).ConfigureAwait(false); + Transaction transaction = await nep17API.CreateTransferTxAsync(NativeContract.NEO.Hash, keyPair, toHash, balance, null, addAssert).ConfigureAwait(false); await rpcClient.SendRawTransactionAsync(transaction).ConfigureAwait(false); return transaction; } @@ -139,8 +141,10 @@ public async Task ClaimGasAsync(KeyPair keyPair) /// Example: WIF ("KyXwTh1hB76RRMquSvnxZrJzQx7h9nQP2PCRL38v6VDb5ip3nf1p"), PrivateKey ("450d6c2a04b5b470339a745427bae6828400cf048400837d73c415063835e005") /// address or account script hash /// token amount + /// onPayment data + /// Add assert at the end of the script /// - public async Task TransferAsync(string tokenHash, string fromKey, string toAddress, decimal amount, object data = null) + public async Task TransferAsync(string tokenHash, string fromKey, string toAddress, decimal amount, object data = null, bool addAssert = true) { UInt160 scriptHash = Utility.GetScriptHash(tokenHash, rpcClient.protocolSettings); var decimals = await nep17API.DecimalsAsync(scriptHash).ConfigureAwait(false); @@ -148,7 +152,7 @@ public async Task TransferAsync(string tokenHash, string fromKey, s KeyPair from = Utility.GetKeyPair(fromKey); UInt160 to = Utility.GetScriptHash(toAddress, rpcClient.protocolSettings); BigInteger amountInteger = amount.ToBigInteger(decimals); - return await TransferAsync(scriptHash, from, to, amountInteger, data).ConfigureAwait(false); + return await TransferAsync(scriptHash, from, to, amountInteger, data, addAssert).ConfigureAwait(false); } /// @@ -158,10 +162,12 @@ public async Task TransferAsync(string tokenHash, string fromKey, s /// from KeyPair /// to account script hash /// transfer amount + /// onPayment data + /// Add assert at the end of the script /// - public async Task TransferAsync(UInt160 scriptHash, KeyPair from, UInt160 to, BigInteger amountInteger, object data = null) + public async Task TransferAsync(UInt160 scriptHash, KeyPair from, UInt160 to, BigInteger amountInteger, object data = null, bool addAssert = true) { - Transaction transaction = await nep17API.CreateTransferTxAsync(scriptHash, from, to, amountInteger, data).ConfigureAwait(false); + Transaction transaction = await nep17API.CreateTransferTxAsync(scriptHash, from, to, amountInteger, data, addAssert).ConfigureAwait(false); await rpcClient.SendRawTransactionAsync(transaction).ConfigureAwait(false); return transaction; } @@ -175,10 +181,12 @@ public async Task TransferAsync(UInt160 scriptHash, KeyPair from, U /// sign keys /// to account /// transfer amount + /// onPayment data + /// Add assert at the end of the script /// - public async Task TransferAsync(UInt160 scriptHash, int m, ECPoint[] pubKeys, KeyPair[] keys, UInt160 to, BigInteger amountInteger, object data = null) + public async Task TransferAsync(UInt160 scriptHash, int m, ECPoint[] pubKeys, KeyPair[] keys, UInt160 to, BigInteger amountInteger, object data = null, bool addAssert = true) { - Transaction transaction = await nep17API.CreateTransferTxAsync(scriptHash, m, pubKeys, keys, to, amountInteger, data).ConfigureAwait(false); + Transaction transaction = await nep17API.CreateTransferTxAsync(scriptHash, m, pubKeys, keys, to, amountInteger, data, addAssert).ConfigureAwait(false); await rpcClient.SendRawTransactionAsync(transaction).ConfigureAwait(false); return transaction; } diff --git a/tests/Neo.Network.RPC.Tests/UT_Nep17API.cs b/tests/Neo.Network.RPC.Tests/UT_Nep17API.cs index 566efc9e4..315f573e7 100644 --- a/tests/Neo.Network.RPC.Tests/UT_Nep17API.cs +++ b/tests/Neo.Network.RPC.Tests/UT_Nep17API.cs @@ -137,16 +137,20 @@ public async Task TestGetTokenInfo() [TestMethod] public async Task TestTransfer() { - byte[] testScript = NativeContract.GAS.Hash.MakeScript("transfer", sender, UInt160.Zero, new BigInteger(1_00000000), null); + byte[] testScript = NativeContract.GAS.Hash.MakeScript("transfer", sender, UInt160.Zero, new BigInteger(1_00000000), null) + .Concat(new[] { (byte)OpCode.ASSERT }) + .ToArray(); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter()); var client = rpcClientMock.Object; - var result = await nep17API.CreateTransferTxAsync(NativeContract.GAS.Hash, keyPair1, UInt160.Zero, new BigInteger(1_00000000)); + var result = await nep17API.CreateTransferTxAsync(NativeContract.GAS.Hash, keyPair1, UInt160.Zero, new BigInteger(1_00000000), null, true); - testScript = NativeContract.GAS.Hash.MakeScript("transfer", sender, UInt160.Zero, new BigInteger(1_00000000), string.Empty); + testScript = NativeContract.GAS.Hash.MakeScript("transfer", sender, UInt160.Zero, new BigInteger(1_00000000), string.Empty) + .Concat(new[] { (byte)OpCode.ASSERT }) + .ToArray(); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter()); - result = await nep17API.CreateTransferTxAsync(NativeContract.GAS.Hash, keyPair1, UInt160.Zero, new BigInteger(1_00000000), string.Empty); + result = await nep17API.CreateTransferTxAsync(NativeContract.GAS.Hash, keyPair1, UInt160.Zero, new BigInteger(1_00000000), string.Empty, true); Assert.IsNotNull(result); } } diff --git a/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs b/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs index 991c7f8b8..14ec43053 100644 --- a/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs +++ b/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs @@ -8,6 +8,7 @@ using Neo.SmartContract.Native; using Neo.VM; using Neo.Wallets; +using System.Linq; using System.Numerics; using System.Threading.Tasks; @@ -89,7 +90,7 @@ public async Task TestClaimGas() json["hash"] = UInt256.Zero.ToString(); rpcClientMock.Setup(p => p.RpcSendAsync("sendrawtransaction", It.IsAny())).ReturnsAsync(json); - var tranaction = await walletAPI.ClaimGasAsync(keyPair1.Export()); + var tranaction = await walletAPI.ClaimGasAsync(keyPair1.Export(), false); Assert.AreEqual(testScript.ToHexString(), tranaction.Script.Span.ToHexString()); } @@ -99,14 +100,16 @@ public async Task TestTransfer() byte[] decimalsScript = NativeContract.GAS.Hash.MakeScript("decimals"); UT_TransactionManager.MockInvokeScript(rpcClientMock, decimalsScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(8) }); - byte[] testScript = NativeContract.GAS.Hash.MakeScript("transfer", sender, UInt160.Zero, NativeContract.GAS.Factor * 100, null); + byte[] testScript = NativeContract.GAS.Hash.MakeScript("transfer", sender, UInt160.Zero, NativeContract.GAS.Factor * 100, null) + .Concat(new[] { (byte)OpCode.ASSERT }) + .ToArray(); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_10000000) }); var json = new JObject(); json["hash"] = UInt256.Zero.ToString(); rpcClientMock.Setup(p => p.RpcSendAsync("sendrawtransaction", It.IsAny())).ReturnsAsync(json); - var tranaction = await walletAPI.TransferAsync(NativeContract.GAS.Hash.ToString(), keyPair1.Export(), UInt160.Zero.ToAddress(client.protocolSettings.AddressVersion), 100); + var tranaction = await walletAPI.TransferAsync(NativeContract.GAS.Hash.ToString(), keyPair1.Export(), UInt160.Zero.ToAddress(client.protocolSettings.AddressVersion), 100, null, true); Assert.AreEqual(testScript.ToHexString(), tranaction.Script.Span.ToHexString()); } @@ -121,19 +124,21 @@ public async Task TestTransferfromMultiSigAccount() byte[] decimalsScript = NativeContract.GAS.Hash.MakeScript("decimals"); UT_TransactionManager.MockInvokeScript(rpcClientMock, decimalsScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(8) }); - byte[] testScript = NativeContract.GAS.Hash.MakeScript("transfer", multiSender, UInt160.Zero, NativeContract.GAS.Factor * 100, null); + byte[] testScript = NativeContract.GAS.Hash.MakeScript("transfer", multiSender, UInt160.Zero, NativeContract.GAS.Factor * 100, null) + .Concat(new[] { (byte)OpCode.ASSERT }) + .ToArray(); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_10000000) }); var json = new JObject(); json["hash"] = UInt256.Zero.ToString(); rpcClientMock.Setup(p => p.RpcSendAsync("sendrawtransaction", It.IsAny())).ReturnsAsync(json); - var tranaction = await walletAPI.TransferAsync(NativeContract.GAS.Hash, 1, new[] { keyPair1.PublicKey }, new[] { keyPair1 }, UInt160.Zero, NativeContract.GAS.Factor * 100); + var tranaction = await walletAPI.TransferAsync(NativeContract.GAS.Hash, 1, new[] { keyPair1.PublicKey }, new[] { keyPair1 }, UInt160.Zero, NativeContract.GAS.Factor * 100, null, true); Assert.AreEqual(testScript.ToHexString(), tranaction.Script.Span.ToHexString()); try { - tranaction = await walletAPI.TransferAsync(NativeContract.GAS.Hash, 2, new[] { keyPair1.PublicKey }, new[] { keyPair1 }, UInt160.Zero, NativeContract.GAS.Factor * 100); + tranaction = await walletAPI.TransferAsync(NativeContract.GAS.Hash, 2, new[] { keyPair1.PublicKey }, new[] { keyPair1 }, UInt160.Zero, NativeContract.GAS.Factor * 100, null, true); Assert.Fail(); } catch (System.Exception e) @@ -141,10 +146,12 @@ public async Task TestTransferfromMultiSigAccount() Assert.AreEqual(e.Message, $"Need at least 2 KeyPairs for signing!"); } - testScript = NativeContract.GAS.Hash.MakeScript("transfer", multiSender, UInt160.Zero, NativeContract.GAS.Factor * 100, string.Empty); + testScript = NativeContract.GAS.Hash.MakeScript("transfer", multiSender, UInt160.Zero, NativeContract.GAS.Factor * 100, string.Empty) + .Concat(new[] { (byte)OpCode.ASSERT }) + .ToArray(); UT_TransactionManager.MockInvokeScript(rpcClientMock, testScript, new ContractParameter { Type = ContractParameterType.Integer, Value = new BigInteger(1_10000000) }); - tranaction = await walletAPI.TransferAsync(NativeContract.GAS.Hash, 1, new[] { keyPair1.PublicKey }, new[] { keyPair1 }, UInt160.Zero, NativeContract.GAS.Factor * 100, string.Empty); + tranaction = await walletAPI.TransferAsync(NativeContract.GAS.Hash, 1, new[] { keyPair1.PublicKey }, new[] { keyPair1 }, UInt160.Zero, NativeContract.GAS.Factor * 100, string.Empty, true); Assert.AreEqual(testScript.ToHexString(), tranaction.Script.Span.ToHexString()); } From e9d8683360ae968a79ad4e3a70e95fac27584938 Mon Sep 17 00:00:00 2001 From: Christopher Schuchardt Date: Wed, 8 Nov 2023 02:23:39 -0500 Subject: [PATCH 12/30] Add Rest Web Server `WIP` (#810) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add new project for restserver * Added Utils, Node and contract controllers * updated license for each file. * Added plugin support for plugins to add dependencies via dependency injection. * Update to allow MaxPageSize * Added new settings for configuration. Added HTTP Basic Auth. Changed most classes to internal that didnt need to be public. Added Rest Server Middleware. Added the ability to block urls paths (for module rest server plugins). Added the ability to enable CORS and whitelist of urls. Added HTTP user and pass configurable. Added hot load of Controllers from plugin assemblies Changed Controllers to be "ApiController" class * Added CORS misconfiguation message to the user if auth and cors is enabled with no origins,. * Added Wallet API (untested) Added MaxTransactionFee to config Added Anything for Kestrel to be configurable * Added Nep17 tokens controller. Added Nep11 token controller. Changed namespaces and file names around. * Added invoke gas max amount Added peers route for node controller Changed RemoteNodeModel and TokenBalanceModel namespaces * Added blockchain controller Added Neo/Gas controller Added send raw transactions relay * Changed controllers to show error if is invalid node protocol network Fixed formating Added blacklist/disable controllers Removed DisableRoute list from config (wasn't being used) * Fixed RestServerMiddleware crashing if malformed basic auth is sent from end user * Changed json converter for UInt160 to validate Address and scripthash format Added InvokeScript to helper class Added ConvertToScriptHash for address to scripthash * Changes Namespaces * Fixed Wallet Transfers * Error Codes * Added Custom Exceptions Changed all controller parameters for json converters Added custom error handling Fixed wallet sessions Added wallet session manager removed development mode (not needed) Added session timeout to config file Added max allow sessions to config file * Added swagger support Added swagger configurable in config.json Changed controllers to reflect swagger Changed wallet controller to reset expiring for wallets per request * Made RestServer more generic and plugin friendly Added new json converter for block, transaction and contract removed the model associated with blocks, transactions, and contracts changed json settings for new json converters that were added * Changed now when wallets expire they will be terminated on time. Added Console Commands for wallet sessions * Fixed Block, transaction json converters for null values. Fixed UInt160, UInt256 json converters value not being set right in certain situations. Fixed wallet transfers for null signers * Fixed UInt160 and UInt256 with null values Fixed Wallet transfers with invalid data or output messages * Added full wallet functionality Changed wallet route paths around to be suit the means Fixed ECPoint json converter for reading Fixed UInt160 json converter Changed error out for invalid serialization of json on route parameters Fixed with dotnet format * Added Transactions with scripts Changed restricted wallet path to Environment.CurrentDirectory * Fixed typos with json properties in json converters. Changed NEP-11 Models to IReadOnlyDictionary and IEnumerable. * Changed Nep11 and Nep17 token classes to be more sounds on logic Fixed with dotnet format * Added swagger server discriptions for wallet controller. Fixed Guid json converter with values. * Fixes the transaction model for swagger * Added Swagger service descriptions * Fixed typos in swagger descriptions * Changed xml commecnts to RestServer only Because you can only use one xml file per swagger. Fixed some more typos * Removed GenerateDocumentationFile kind of point if other plugins cant add on to it. * Changed ExecutionEngineModel to be more swagger friendly * Fixed all the swagger json objects descriptions, types are now readable from the Swagger UI Added back xml comments does work with other plugins in swagger. Added SchemaFilter for removing unwanted properties from json objects in swagger. Fixed some type mapping for swagger Removed some type mapping for swagger * Removed unnecessary namespaces from file(s) * Changed WalletController to have expose more information for some errors Changed Swagger doc description and title * Changed to Swagger to support only OpenAPI version 2.0 for DotNet Standard 2.0/2.1 * Fixed CORS wasnt being set. * Changed WalletTimeout to WalletSessionTimeout Added WWWAuthenticate support for browsers Fixed wording of the 400 responses * Code clean up Changed MaxInvokeGas to MaxGasInvoke to match Rpc Server's * Changed names of controller from token to tokens Add basic auth handler removed not needed json converters added uint160 model binder merge * Added basic auth handler Added jsonconverters Moved Controllers to V1 folder for version control * Update timer to not be runaway timer * Updated Json Converter Settings * Added RestServer Docs --------- Co-authored-by: Christopher R. Schuchardt Co-authored-by: Vitor Nazário Coelho --- docs/RestServer/Addons.md | 108 +++ docs/RestServer/ConfigFile.md | 56 ++ docs/RestServer/README.md | 136 ++++ neo-modules.sln | 7 + .../BasicAuthenticationHandler.cs | 62 ++ src/RestServer/Binder/UInt160Binder.cs | 47 ++ .../Binder/UInt160BinderProvider.cs | 33 + .../Controllers/v1/ContractsController.cs | 214 ++++++ .../Controllers/v1/LedgerController.cs | 389 +++++++++++ .../Controllers/v1/NodeController.cs | 86 +++ .../Controllers/v1/TokensController.cs | 304 +++++++++ .../Controllers/v1/UtilsController.cs | 106 +++ .../Controllers/v1/WalletController.cs | 646 ++++++++++++++++++ .../Exceptions/AddressFormatException.cs | 18 + .../Exceptions/ApplicationEngineException.cs | 18 + .../Exceptions/BlockNotFoundException.cs | 18 + .../Exceptions/ContractNotFoundException.cs | 18 + .../InvalidParameterRangeException.cs | 18 + .../JsonPropertyNullOrEmptyException.cs | 19 + .../Exceptions/Nep11NotSupportedException.cs | 18 + .../Exceptions/Nep17NotSupportedException.cs | 18 + src/RestServer/Exceptions/NodeException.cs | 18 + .../Exceptions/NodeNetworkException.cs | 18 + .../QueryParameterNotFoundException.cs | 18 + src/RestServer/Exceptions/RestErrorCodes.cs | 19 + .../Exceptions/ScriptHashFormatException.cs | 18 + .../TransactionNotFoundException.cs | 18 + .../Exceptions/UInt256FormatException.cs | 18 + src/RestServer/Exceptions/WalletException.cs | 18 + .../WalletInsufficientFundsException.cs | 18 + .../Exceptions/WalletOpenException.cs | 19 + .../Exceptions/WalletSessionException.cs | 18 + .../Extensions/LedgerContractExtensions.cs | 142 ++++ src/RestServer/Extensions/ModelExtensions.cs | 99 +++ .../Extensions/UInt160Extensions.cs | 27 + src/RestServer/Helpers/ContractHelper.cs | 58 ++ src/RestServer/Helpers/ScriptHelper.cs | 59 ++ .../Middleware/RestServerMiddleware.cs | 43 ++ .../Models/Blockchain/AccountDetails.cs | 33 + src/RestServer/Models/CountModel.cs | 21 + src/RestServer/Models/Error/ErrorModel.cs | 32 + .../Error/ParameterFormatExceptionModel.cs | 28 + src/RestServer/Models/ExecutionEngineModel.cs | 49 ++ .../Models/Ledger/MemoryPoolCountModel.cs | 31 + src/RestServer/Models/Node/PluginModel.cs | 31 + .../Models/Node/ProtocolSettingsModel.cs | 40 ++ src/RestServer/Models/Node/RemoteNodeModel.cs | 36 + .../Models/Token/NEP11TokenModel.cs | 19 + .../Models/Token/NEP17TokenModel.cs | 23 + .../Models/Token/TokenBalanceModel.cs | 24 + .../Models/Utils/UtilsAddressIsValidModel.cs | 11 + .../Models/Utils/UtilsAddressModel.cs | 21 + .../Models/Utils/UtilsScriptHashModel.cs | 21 + .../Wallet/WalletAccountBalanceModel.cs | 26 + .../Models/Wallet/WalletAddressModel.cs | 51 ++ .../Models/Wallet/WalletAssetModel.cs | 54 ++ .../Wallet/WalletChangePasswordModel.cs | 40 ++ .../Models/Wallet/WalletCreateAccountModel.cs | 24 + .../Models/Wallet/WalletCreateModel.cs | 45 ++ .../Models/Wallet/WalletExportKeyModel.cs | 34 + .../Models/Wallet/WalletImportKey.cs | 27 + .../WalletImportMultiSigAddressModel.cs | 32 + .../Models/Wallet/WalletKeyModel.cs | 33 + .../Wallet/WalletMultiSignContractModel.cs | 34 + .../Models/Wallet/WalletOpenModel.cs | 33 + .../Models/Wallet/WalletSendModel.cs | 58 ++ .../Models/Wallet/WalletSessionModel.cs | 24 + .../Wallet/WalletTransactionScriptModel.cs | 35 + .../Json/BigDecimalJsonConverter.cs | 48 ++ .../Json/BlockHeaderJsonConverter.cs | 32 + .../Newtonsoft/Json/BlockJsonConverter.cs | 30 + .../Json/ContractAbiJsonConverter.cs | 28 + .../ContractEventDescriptorJsonConverter.cs | 28 + .../Json/ContractGroupJsonConverter.cs | 28 + .../Newtonsoft/Json/ContractJsonConverter.cs | 28 + .../Json/ContractManifestJsonConverter.cs | 28 + .../Json/ContractMethodJsonConverter.cs | 28 + .../ContractMethodParametersJsonConverter.cs | 27 + ...ontractParameterDefinitionJsonConverter.cs | 28 + .../Json/ContractParameterJsonConverter.cs | 33 + ...ntractPermissionDescriptorJsonConverter.cs | 28 + .../Json/ContractPermissionJsonConverter.cs | 28 + .../Newtonsoft/Json/ECPointJsonConverter.cs | 37 + .../Newtonsoft/Json/GuidJsonConverter.cs | 27 + .../Json/InteropInterfaceJsonConverter.cs | 31 + .../Json/MethodTokenJsonConverter.cs | 28 + .../Newtonsoft/Json/NefFileJsonConverter.cs | 24 + .../Json/ReadOnlyMemoryBytesJsonConverter.cs | 29 + .../Newtonsoft/Json/SignerJsonConverter.cs | 29 + .../Newtonsoft/Json/StackItemJsonConverter.cs | 33 + .../Json/TransactionAttributeJsonConverter.cs | 28 + .../Json/TransactionJsonConverter.cs | 28 + .../Newtonsoft/Json/UInt160JsonConverter.cs | 39 ++ .../Newtonsoft/Json/UInt256JsonConverter.cs | 36 + .../Newtonsoft/Json/VmArrayJsonConverter.cs | 31 + .../Newtonsoft/Json/VmBooleanJsonConverter.cs | 31 + .../Newtonsoft/Json/VmBufferJsonConverter.cs | 31 + .../Json/VmByteStringJsonConverter.cs | 31 + .../Newtonsoft/Json/VmIntegerJsonConverter.cs | 31 + .../Newtonsoft/Json/VmMapJsonConverter.cs | 31 + .../Newtonsoft/Json/VmNullJsonConverter.cs | 31 + .../Newtonsoft/Json/VmPointerJsonConverter.cs | 31 + .../Newtonsoft/Json/VmStructJsonConverter.cs | 31 + .../Json/WitnessConditionJsonConverter.cs | 95 +++ .../Newtonsoft/Json/WitnessJsonConverter.cs | 32 + .../Json/WitnessRuleJsonConverter.cs | 24 + .../BlackListControllerFeatureProvider.cs | 35 + src/RestServer/RestServer.csproj | 25 + src/RestServer/RestServerPlugin.Console.cs | 131 ++++ src/RestServer/RestServerPlugin.cs | 62 ++ src/RestServer/RestServerSettings.cs | 162 +++++ src/RestServer/RestServerUtility.JTokens.cs | 302 ++++++++ src/RestServer/RestServerUtility.cs | 346 ++++++++++ src/RestServer/RestWebServer.cs | 417 +++++++++++ src/RestServer/Tokens/NEP11Token.cs | 178 +++++ src/RestServer/Tokens/NEP17Token.cs | 75 ++ src/RestServer/WalletSessionManager.cs | 54 ++ src/RestServer/config.json | 27 + 118 files changed, 6972 insertions(+) create mode 100644 docs/RestServer/Addons.md create mode 100644 docs/RestServer/ConfigFile.md create mode 100644 docs/RestServer/README.md create mode 100644 src/RestServer/Authentication/BasicAuthenticationHandler.cs create mode 100644 src/RestServer/Binder/UInt160Binder.cs create mode 100644 src/RestServer/Binder/UInt160BinderProvider.cs create mode 100644 src/RestServer/Controllers/v1/ContractsController.cs create mode 100644 src/RestServer/Controllers/v1/LedgerController.cs create mode 100644 src/RestServer/Controllers/v1/NodeController.cs create mode 100644 src/RestServer/Controllers/v1/TokensController.cs create mode 100644 src/RestServer/Controllers/v1/UtilsController.cs create mode 100644 src/RestServer/Controllers/v1/WalletController.cs create mode 100644 src/RestServer/Exceptions/AddressFormatException.cs create mode 100644 src/RestServer/Exceptions/ApplicationEngineException.cs create mode 100644 src/RestServer/Exceptions/BlockNotFoundException.cs create mode 100644 src/RestServer/Exceptions/ContractNotFoundException.cs create mode 100644 src/RestServer/Exceptions/InvalidParameterRangeException.cs create mode 100644 src/RestServer/Exceptions/JsonPropertyNullOrEmptyException.cs create mode 100644 src/RestServer/Exceptions/Nep11NotSupportedException.cs create mode 100644 src/RestServer/Exceptions/Nep17NotSupportedException.cs create mode 100644 src/RestServer/Exceptions/NodeException.cs create mode 100644 src/RestServer/Exceptions/NodeNetworkException.cs create mode 100644 src/RestServer/Exceptions/QueryParameterNotFoundException.cs create mode 100644 src/RestServer/Exceptions/RestErrorCodes.cs create mode 100644 src/RestServer/Exceptions/ScriptHashFormatException.cs create mode 100644 src/RestServer/Exceptions/TransactionNotFoundException.cs create mode 100644 src/RestServer/Exceptions/UInt256FormatException.cs create mode 100644 src/RestServer/Exceptions/WalletException.cs create mode 100644 src/RestServer/Exceptions/WalletInsufficientFundsException.cs create mode 100644 src/RestServer/Exceptions/WalletOpenException.cs create mode 100644 src/RestServer/Exceptions/WalletSessionException.cs create mode 100644 src/RestServer/Extensions/LedgerContractExtensions.cs create mode 100644 src/RestServer/Extensions/ModelExtensions.cs create mode 100644 src/RestServer/Extensions/UInt160Extensions.cs create mode 100644 src/RestServer/Helpers/ContractHelper.cs create mode 100644 src/RestServer/Helpers/ScriptHelper.cs create mode 100644 src/RestServer/Middleware/RestServerMiddleware.cs create mode 100644 src/RestServer/Models/Blockchain/AccountDetails.cs create mode 100644 src/RestServer/Models/CountModel.cs create mode 100644 src/RestServer/Models/Error/ErrorModel.cs create mode 100644 src/RestServer/Models/Error/ParameterFormatExceptionModel.cs create mode 100644 src/RestServer/Models/ExecutionEngineModel.cs create mode 100644 src/RestServer/Models/Ledger/MemoryPoolCountModel.cs create mode 100644 src/RestServer/Models/Node/PluginModel.cs create mode 100644 src/RestServer/Models/Node/ProtocolSettingsModel.cs create mode 100644 src/RestServer/Models/Node/RemoteNodeModel.cs create mode 100644 src/RestServer/Models/Token/NEP11TokenModel.cs create mode 100644 src/RestServer/Models/Token/NEP17TokenModel.cs create mode 100644 src/RestServer/Models/Token/TokenBalanceModel.cs create mode 100644 src/RestServer/Models/Utils/UtilsAddressIsValidModel.cs create mode 100644 src/RestServer/Models/Utils/UtilsAddressModel.cs create mode 100644 src/RestServer/Models/Utils/UtilsScriptHashModel.cs create mode 100644 src/RestServer/Models/Wallet/WalletAccountBalanceModel.cs create mode 100644 src/RestServer/Models/Wallet/WalletAddressModel.cs create mode 100644 src/RestServer/Models/Wallet/WalletAssetModel.cs create mode 100644 src/RestServer/Models/Wallet/WalletChangePasswordModel.cs create mode 100644 src/RestServer/Models/Wallet/WalletCreateAccountModel.cs create mode 100644 src/RestServer/Models/Wallet/WalletCreateModel.cs create mode 100644 src/RestServer/Models/Wallet/WalletExportKeyModel.cs create mode 100644 src/RestServer/Models/Wallet/WalletImportKey.cs create mode 100644 src/RestServer/Models/Wallet/WalletImportMultiSigAddressModel.cs create mode 100644 src/RestServer/Models/Wallet/WalletKeyModel.cs create mode 100644 src/RestServer/Models/Wallet/WalletMultiSignContractModel.cs create mode 100644 src/RestServer/Models/Wallet/WalletOpenModel.cs create mode 100644 src/RestServer/Models/Wallet/WalletSendModel.cs create mode 100644 src/RestServer/Models/Wallet/WalletSessionModel.cs create mode 100644 src/RestServer/Models/Wallet/WalletTransactionScriptModel.cs create mode 100644 src/RestServer/Newtonsoft/Json/BigDecimalJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/BlockHeaderJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/BlockJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/ContractAbiJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/ContractEventDescriptorJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/ContractGroupJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/ContractJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/ContractManifestJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/ContractMethodJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/ContractMethodParametersJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/ContractParameterDefinitionJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/ContractParameterJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/ContractPermissionDescriptorJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/ContractPermissionJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/ECPointJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/GuidJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/InteropInterfaceJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/MethodTokenJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/NefFileJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/ReadOnlyMemoryBytesJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/SignerJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/StackItemJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/TransactionAttributeJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/TransactionJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/UInt160JsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/UInt256JsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/VmArrayJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/VmBooleanJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/VmBufferJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/VmByteStringJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/VmIntegerJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/VmMapJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/VmNullJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/VmPointerJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/VmStructJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/WitnessConditionJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/WitnessJsonConverter.cs create mode 100644 src/RestServer/Newtonsoft/Json/WitnessRuleJsonConverter.cs create mode 100644 src/RestServer/Providers/BlackListControllerFeatureProvider.cs create mode 100644 src/RestServer/RestServer.csproj create mode 100644 src/RestServer/RestServerPlugin.Console.cs create mode 100644 src/RestServer/RestServerPlugin.cs create mode 100644 src/RestServer/RestServerSettings.cs create mode 100644 src/RestServer/RestServerUtility.JTokens.cs create mode 100644 src/RestServer/RestServerUtility.cs create mode 100644 src/RestServer/RestWebServer.cs create mode 100644 src/RestServer/Tokens/NEP11Token.cs create mode 100644 src/RestServer/Tokens/NEP17Token.cs create mode 100644 src/RestServer/WalletSessionManager.cs create mode 100644 src/RestServer/config.json diff --git a/docs/RestServer/Addons.md b/docs/RestServer/Addons.md new file mode 100644 index 000000000..07be39f4b --- /dev/null +++ b/docs/RestServer/Addons.md @@ -0,0 +1,108 @@ +## RestServer Plugin +In this secion of you will learn how to make a `neo-cli` plugin that integrates with `RestServer` +plugin. Lets take a look at [Example Plugin](/examples/RestServerPlugin). + +- No reference to `RestServer` is reqired. +- Requires DotNet 7.0 + +## Folder Structure +```bash +Project +├── Controllers +│ └── ExampleController.cs +├── ExamplePlugin.cs +├── ExamplePlugin.csproj +├── Exceptions +│ └── CustomException.cs +└── Models + └── ErrorModel.cs +``` +The only thing that is important here is the `controllers` folder. This folder is required for the `RestServer` +plugin to register the controllers in its web server. This location is where you put all your controllers. + +## Controllers +The `controller` class is the same as ASP.Net Core's. Controllers must have their attribute set +as `[ApiController]` and inherent from `ControllerBase`. + +## Swagger Controller +A `Swagger` controller uses special attributes that are set on your controller's class. + +**Controller Class Attributes** +- `[Produces(MediaTypeNames.Application.Json)]` (_Required_) +- `[Consumes(MediaTypeNames.Application.Json)]` (_Required_) +- `[ApiExplorerSettings(GroupName = "v1")]` + - **GroupName** - _is which version of the API you are targeting._ +- `[ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(ErrorModel))]` (_Required_) + - **Type** - _Must have a base class of [error](#error-class)._ + +## Error Class +Needs to be the same as `RestServer` of else there will be some inconsistencies +with end users not knowing which type to use. This class can be `public` or `internal`. +Properties `Code`, `Name` and `Message` values can be whatever you desire. + +**Model** +```csharp +public class ErrorModel +{ + public int Code { get; set; }; + public string Name { get; set; }; + public string Message { get; set; }; +} +``` + +## Controller Actions +Controller actions need to have special attributes as well as code comments. + +- `[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(string))]` + +HTTP status code `200 (OK)` is required with return type defined. You can use more than one attribute. One per HTTP status code. + +### Action Example +```csharp +[HttpGet("contracts/{hash:required}/sayHello", Name = "GetSayHello")] +[ProducesResponseType(StatusCodes.Status204NoContent)] +[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(string))] +public IActionResult GetSayHello( + [FromRoute(Name = "hash")] + UInt160 scripthash) +{ + if (scripthash == UInt160.Zero) + return NoContent(); + return Ok($"Hello, {scripthash}"); +} +``` +Notice that the _above_ example also returns with HTTP status code of `204 No Content`. +This action `route` also extends the `contracts` API. Adding method `sayHello`. Routes +can be what you like as well. But if you want to extend on any existing controller you +must use existing routes paths. + +### Path(s) +- `/api/v1/contracts/` +- `/api/v1/ledger/` +- `/api/v1/node/` +- `/api/v1/tokens` +- `/api/v1/Utils/` + +### Excluded Path(s) +- `/api/v1/wallet/` + +_for security reasons_. + +### Code Comments for Swagger +```csharp +/// +/// +/// +/// +/// +/// Successful +/// An error occurred. See Response for details. +``` + +Also note that you need to have `GenerateDocumentationFile` enabled in your +`.csproj` file. The `xml` file that is generated; in our case would be `RestServerPlugin.xml`. +This file gets put in same directory `Plugins/RestServerPlugin/` which is in the root of `neo-node` +executable folder. Where you will see `neo-cli.exe`. + +File `RestServerPlugin.xml` will get added to `Swagger` automatically by the `RestServer` +plugin. diff --git a/docs/RestServer/ConfigFile.md b/docs/RestServer/ConfigFile.md new file mode 100644 index 000000000..303a920f1 --- /dev/null +++ b/docs/RestServer/ConfigFile.md @@ -0,0 +1,56 @@ +## Table + +| Name | Type | Description | +| :--- | :---: | :--- | +|**Network**|_uint32_|_Network you would like the `RestServer` to be enabled on._| +|**BindAddress**|_string_|_Ip address of the interface you want to bind too._| +|**Port**|_uint32_|_Port number to bind too._| +|**KeepAliveTimeout**|_uint32_|_Time to keep the request alive, in seconds._| +|**SslCertFile**|_string_|_Is the path and file name of a certificate file, relative to the directory that contains the node's executable files._| +|**SslCertPassword**|_string_|_Is the password required to access the `X.509` certificate data._| +|**TrustedAuthorities**|_StringArray_|_Tumbprints of the of the last certificate authority in the chain._| +|**EnableBasicAuthentication**|_boolean_|_enables basic authentication._| +|**RestUser**|_string_|_Basic authentication's `username`._| +|**RestPass**|_string_|_Basic authentication's `password`._| +|**EnableCors**|_boolean_|_Enables Cross-origin resource sharing (`CORS`). Note by default it enables `*` any origin._| +|**AllowOrigins**|_StringArray_|_A list of the origins to allow. Note needs to add origins for basic auth to work with `CORS`._| +|**DisableControllers**|_StringArray_|_A list of `controllers` to be disabled. Requires restart of the node, if changed._| +|**EnableCompression**|_boolean_|_Enables `GZip` data compression._| +|**CompressionLevel**|_enum_|_Compression level. Values can be `Fastest`, `Optimal`, `NoCompression` or `SmallestSize`_| +|**EnableForwardedHeaders**|_boolean_|_Enables response/request headers for proxy forwarding. (data center usage)_| +|**EnableSwagger**|_boolean_|_Enables `Swagger` with `Swagger UI` for the rest services._| +|**MaxPageSize**|_uint32_|_Max page size for searches on `Ledger`/`Contracts` route._| +|**MaxConcurrentConnections**|_int64_|_Max allow concurrent HTTP connections._| +|**MaxTransactionFee**|_int64_|_Max transaction fee for `wallet` transfers._| +|**MaxInvokeGas**|_int64_|_Max gas to be invoked on the `Neo` virtual machine._| +|**WalletSessionTimeout**|_uint32_|_When `wallet` session expires, in seconds._| + +## Default "Config.json" file +```json +{ + "PluginConfiguration": { + "Network": 860833102, + "BindAddress": "127.0.0.1", + "Port": 10339, + "KeepAliveTimeout": 120, + "SslCertFile": "", + "SslCertPassword": "", + "TrustedAuthorities": [], + "EnableBasicAuthentication": false, + "RestUser": "", + "RestPass": "", + "EnableCors": true, + "AllowOrigins": [], + "DisableControllers": [ "WalletController" ], + "EnableCompression": true, + "CompressionLevel": "SmallestSize", + "EnableForwardedHeaders": false, + "EnableSwagger": true, + "MaxPageSize": 50, + "MaxConcurrentConnections": 40, + "MaxTransactionFee": 10000000, + "MaxInvokeGas": 20000000, + "WalletSessionTimeout": 120 + } +} +``` diff --git a/docs/RestServer/README.md b/docs/RestServer/README.md new file mode 100644 index 000000000..05b068776 --- /dev/null +++ b/docs/RestServer/README.md @@ -0,0 +1,136 @@ +## RestServer +In this section you will learn about `RestServer` plugin and how it works. + +See [config.json](ConfigFile.md) for information about the configurations. + +## Dependencies +- **Microsoft.AspNetCore.JsonPatch.dll** `Required` +- **Microsoft.AspNetCore.Mvc.NewtonsoftJson.dll** `Required` +- **Microsoft.OpenApi.dll** `Swagger` +- **Swashbuckle.AspNetCore.Swagger.dll** `Swagger` +- **Swashbuckle.AspNetCore.SwaggerGen.dll** `Swagger` +- **Swashbuckle.AspNetCore.SwaggerUI.dll** `Swagger` +- **Swashbuckle.AspNetCore.Newtonsoft.dll** `Swagger` +- **RestServer.xml** `Swagger UI` + +These files go in the same directory as the `RestServer.dll`. In neo-cli +`plugins/RestServer/` folder. + +## Response Headers +| Name | Value(s) | Description | +| :---: | --- | :--- | +|**server**|_neo-cli/3.6.0 RestServer/3.6.0_|_`neo-cli` and `RestServer` version._| + +Custom headers can be added by [Neo RestServer Plugins](Addons.md). + +## JSON Serializer +`RestServer` uses custom Newtonsoft Json Converters to serialize controller action +responses and `route` parameters. + +**One Way Binding** - `Write` only. +- `Neo.SmartContract.ContractState` +- `Neo.SmartContract.NefFile` +- `Neo.SmartContract.MethodToken` +- `Neo.SmartContract.Native.TrimmedBlock` +- `Neo.SmartContract.Manifest.ContractAbi` +- `Neo.SmartContract.Manifest.ContractGroup` +- `Neo.SmartContract.Manifest.ContractManifest` +- `Neo.SmartContract.Manifest.ContractPermission` +- `Neo.SmartContract.Manifest.ContractPermissionDescriptor` +- `Neo.Network.P2P.Payloads.Block` +- `Neo.Network.P2P.Payloads.Header` +- `Neo.Network.P2P.Payloads.Signer` +- `Neo.Network.P2P.Payloads.TransactionAttribute` +- `Neo.Network.P2P.Payloads.Transaction` +- `Neo.Network.P2P.Payloads.Witness` + +**Two Way Binding** - `Read` & `Write` +- `System.Guid` +- `System.ReadOnlyMemory` +- `Neo.BigDecimal` +- `Neo.UInt160` +- `Neo.UInt256` +- `Neo.Cryptography.ECC.ECPoint` +- `Neo.VM.Types.Array` +- `Neo.VM.Types.Boolean` +- `Neo.VM.Types.Buffer` +- `Neo.VM.Types.ByteString` +- `Neo.VM.Types.Integer` +- `Neo.VM.Types.InteropInterface` +- `Neo.VM.Types.Null` +- `Neo.VM.Types.Map` +- `Neo.VM.Types.Pointer` +- `Neo.VM.Types.StackItem` +- `Neo.VM.Types.Struct` + +## Remote Endpoints +Parametes `{hash}` can be any Neo N3 address or scripthash; `{address}` can be any Neo N3 address **only**; `{number}` and `{index}` can be any _**uint32**_. + +**Parameter Examples** +- `{hash}` - _0xef4073a0f2b305a38ec4050e4d3d28bc40ea63f5_ **or** _NiHURyS83nX2mpxtA7xq84cGxVbHojj5Wc_ +- `{address}` - _NiHURyS83nX2mpxtA7xq84cGxVbHojj5Wc_ +- `{number}` - _1_ +- `{index}` - _2500000_ + +**Paths** +- Utils + - `[GET]` `/api/v1/utils/{hash}/address` + - `[GET]` `/api/v1/utils/{address}/scripthash` + - `[GET]` `/api/v1/utils/{hash}/{address}/validate` +- Node + - `[GET]` `/api/v1/node` + - `[GET]` `/api/v1/node/peers` + - `[GET]` `/api/v1/node/plugins` + - `[GET]` `/api/v1/node/settings` +- Ledger + - `[GET]` `/api/v1/ledger/neo/accounts` + - `[GET]` `/api/v1/ledger/gas/accounts` + - `[GET]` `/api/v1/ledger/blocks?page={number}&size={number}` + - `[GET]` `/api/v1/ledger/blocks/height` + - `[GET]` `/api/v1/ledger/blocks/{index}` + - `[GET]` `/api/v1/ledger/blocks/{index}/header` + - `[GET]` `/api/v1/ledger/blocks/{index}/witness` + - `[GET]` `/api/v1/ledger/blocks/{index}/transactions?page={number}&size={number}` + - `[GET]` `/api/v1/ledger/transactions/{hash}` + - `[GET]` `/api/v1/ledger/transactions/{hash}/witnesses` + - `[GET]` `/api/v1/ledger/transactions/{hash}/signers` + - `[GET]` `/api/v1/ledger/transactions/{hash}/atributes` + - `[GET]` `/api/v1/ledger/memorypool?page={number}&size={number}` + - `[GET]` `/api/v1/ledger/memorypool/verified?page={number}&size={number}` + - `[GET]` `/api/v1/ledger/memorypool/unverified?page={number}&size={number}` + - `[GET]` `/api/v1/ledger/memorypool/count` +- Tokens + - `[GET]` `/api/v1/tokens/balanceof/{address}` + - NFTs + - `[GET]` `/api/v1/tokens/nep-11?page={number}&size={number}` + - `[GET]` `/api/v1/tokens/nep-11/count` + - `[GET]` `/api/v1/tokens/nep-11/{hash}/balanceof/{address}` + - NEP-17 + - `[GET]` `/api/v1/tokens/nep-17?page={number}&size={number}` + - `[GET]` `/api/v1/tokens/nep-17/count` + - `[GET]` `/api/v1/tokens/nep-17/{hash}/balanceof/{address}` +- Contracts + - `[GET]` `/api/v1/contracts?page={number}&size={number}` + - `[GET]` `/api/v1/contracts/count` + - `[GET]` `/api/v1/contracts/{hash}` + - `[GET]` `/api/v1/contracts/{hash}/abi` + - `[GET]` `/api/v1/contracts/{hash}/manifest` + - `[GET]` `/api/v1/contracts/{hash}/nef` + - `[GET]` `/api/v1/contracts/{hash}/storage` +- Wallet + - `[POST]` `/api/v1/wallet/open` + - `[POST]` `/api/v1/wallet/create` + - `[POST]` `/api/v1/wallet/{session}/address/create` + - `[GET]` `/api/v1/wallet/{session}/address/list` + - `[GET]` `/api/v1/wallet/{session}/asset/list` + - `[GET]` `/api/v1/wallet/{session}/balance/list` + - `[POST]` `/api/v1/wallet/{session}/changepassword` + - `[GET]` `/api/v1/wallet/{session}/close` + - `[GET]` `/api/v1/wallet/{session}/delete/{address}` + - `[GET]` `/api/v1/wallet/{session}/export/{address}` + - `[GET]` `/api/v1/wallet/{session}/export` + - `[GET]` `/api/v1/wallet/{session}/gas/unclaimed` + - `[GET]` `/api/v1/wallet/{session}/key/list` + - `[POST]` `/api/v1/wallet/{session}/import` + - `[POST]` `/api/v1/wallet/{session}/import/multisigaddress` + - `[POST]` `/api/v1/wallet/{session}/transfer` diff --git a/neo-modules.sln b/neo-modules.sln index 8a1931586..926fc514a 100644 --- a/neo-modules.sln +++ b/neo-modules.sln @@ -43,6 +43,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SQLiteWallet", "src\SQLiteW EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StorageDumper", "src\StorageDumper\StorageDumper.csproj", "{938D86EA-0F48-436B-9255-4AD9A8E6B9AC}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RestServer", "src\RestServer\RestServer.csproj", "{A893825D-65FF-4FA9-85EF-16F3AC626A29}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -121,6 +123,10 @@ Global {938D86EA-0F48-436B-9255-4AD9A8E6B9AC}.Debug|Any CPU.Build.0 = Debug|Any CPU {938D86EA-0F48-436B-9255-4AD9A8E6B9AC}.Release|Any CPU.ActiveCfg = Release|Any CPU {938D86EA-0F48-436B-9255-4AD9A8E6B9AC}.Release|Any CPU.Build.0 = Release|Any CPU + {A893825D-65FF-4FA9-85EF-16F3AC626A29}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A893825D-65FF-4FA9-85EF-16F3AC626A29}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A893825D-65FF-4FA9-85EF-16F3AC626A29}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A893825D-65FF-4FA9-85EF-16F3AC626A29}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -144,6 +150,7 @@ Global {8D2EE375-2E2D-45FE-A4E9-0254D12C7554} = {59D802AB-C552-422A-B9C3-64D329FBCDCC} {D121D57A-512E-4F74-ADA1-24482BF5C42B} = {97E81C78-1637-481F-9485-DA1225E94C23} {938D86EA-0F48-436B-9255-4AD9A8E6B9AC} = {97E81C78-1637-481F-9485-DA1225E94C23} + {A893825D-65FF-4FA9-85EF-16F3AC626A29} = {97E81C78-1637-481F-9485-DA1225E94C23} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {61D3ADE6-BBFC-402D-AB42-1C71C9F9EDE3} diff --git a/src/RestServer/Authentication/BasicAuthenticationHandler.cs b/src/RestServer/Authentication/BasicAuthenticationHandler.cs new file mode 100644 index 000000000..17eb614fb --- /dev/null +++ b/src/RestServer/Authentication/BasicAuthenticationHandler.cs @@ -0,0 +1,62 @@ +// Copyright (C) 2015-2023 neo-restful-plugin. +// +// The RestServer 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 Microsoft.AspNetCore.Authentication; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Neo.Plugins.RestServer; +using System.Net.Http.Headers; +using System.Security.Claims; +using System.Text; +using System.Text.Encodings.Web; + +namespace RestServer.Authentication +{ + internal class BasicAuthenticationHandler : AuthenticationHandler + { + public BasicAuthenticationHandler( + IOptionsMonitor options, + ILoggerFactory logger, + UrlEncoder encoder, + ISystemClock clock) : base(options, logger, encoder, clock) + { + } + + protected override Task HandleAuthenticateAsync() + { + var authHeader = Request.Headers.Authorization; + if (string.IsNullOrEmpty(authHeader) == false && AuthenticationHeaderValue.TryParse(authHeader, out var authValue)) + { + if (authValue.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) && authValue.Parameter != null) + { + try + { + var decodedParams = Encoding.UTF8.GetString(Convert.FromBase64String(authValue.Parameter)); + var creds = decodedParams.Split(':', 2); + if (creds[0] == RestServerSettings.Current.RestUser && creds[1] == RestServerSettings.Current.RestPass) + { + var claims = new[] { new Claim(ClaimTypes.NameIdentifier, creds[0]) }; + var identity = new ClaimsIdentity(claims, Scheme.Name); + var principal = new ClaimsPrincipal(identity); + var ticket = new AuthenticationTicket(principal, Scheme.Name); + + return Task.FromResult(AuthenticateResult.Success(ticket)); + } + + } + catch (FormatException) + { + } + } + } + return Task.FromResult(AuthenticateResult.Fail("Authentication Failed!!!")); + } + } +} diff --git a/src/RestServer/Binder/UInt160Binder.cs b/src/RestServer/Binder/UInt160Binder.cs new file mode 100644 index 000000000..fa72ad595 --- /dev/null +++ b/src/RestServer/Binder/UInt160Binder.cs @@ -0,0 +1,47 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 Microsoft.AspNetCore.Mvc.ModelBinding; + +namespace Neo.Plugins.RestServer.Binder +{ + internal class UInt160Binder : IModelBinder + { + + public Task BindModelAsync(ModelBindingContext bindingContext) + { + _ = bindingContext ?? throw new ArgumentNullException(nameof(bindingContext)); + + if (bindingContext.BindingSource == BindingSource.Path || + bindingContext.BindingSource == BindingSource.Query) + { + var modelName = bindingContext.ModelName; + + // Try to fetch the value of the argument by name + var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName); + + if (valueProviderResult == ValueProviderResult.None) + return Task.CompletedTask; + + bindingContext.ModelState.SetModelValue(modelName, valueProviderResult); + + var value = valueProviderResult.FirstValue; + + // Check if the argument value is null or empty + if (string.IsNullOrEmpty(value)) + return Task.CompletedTask; + + var model = RestServerUtility.ConvertToScriptHash(value, RestServerPlugin.NeoSystem.Settings); + bindingContext.Result = ModelBindingResult.Success(model); + } + return Task.CompletedTask; + } + } +} diff --git a/src/RestServer/Binder/UInt160BinderProvider.cs b/src/RestServer/Binder/UInt160BinderProvider.cs new file mode 100644 index 000000000..f2aceeb1e --- /dev/null +++ b/src/RestServer/Binder/UInt160BinderProvider.cs @@ -0,0 +1,33 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.ModelBinding.Binders; + +namespace Neo.Plugins.RestServer.Binder +{ + internal class NeoBinderProvider : IModelBinderProvider + { + public IModelBinder GetBinder(ModelBinderProviderContext context) + { + if (context == null) + { + throw new ArgumentNullException(nameof(context)); + } + + if (context.Metadata.ModelType == typeof(UInt160)) + { + return new BinderTypeModelBinder(typeof(UInt160Binder)); + } + + return null; + } + } +} diff --git a/src/RestServer/Controllers/v1/ContractsController.cs b/src/RestServer/Controllers/v1/ContractsController.cs new file mode 100644 index 000000000..9c545da9e --- /dev/null +++ b/src/RestServer/Controllers/v1/ContractsController.cs @@ -0,0 +1,214 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Neo.Plugins.RestServer.Exceptions; +using Neo.Plugins.RestServer.Extensions; +using Neo.Plugins.RestServer.Helpers; +using Neo.Plugins.RestServer.Models; +using Neo.Plugins.RestServer.Models.Error; +using Neo.SmartContract; +using Neo.SmartContract.Manifest; +using Neo.SmartContract.Native; +using System.Net.Mime; + +namespace Neo.Plugins.RestServer.Controllers.v1 +{ + [Route("/api/v{version:apiVersion}/contracts")] + [Produces(MediaTypeNames.Application.Json)] + [Consumes(MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(ErrorModel))] + [ApiVersion("1.0")] + [ApiController] + public class ContractsController : ControllerBase + { + private readonly NeoSystem _neosystem; + + public ContractsController() + { + _neosystem = RestServerPlugin.NeoSystem ?? throw new NodeNetworkException(); + } + + /// + /// Get all the smart contracts from the blockchain. + /// + /// Page + /// Page Size + /// An array of Contract object. + /// No more pages. + /// Successful + /// An error occurred. See Response for details. + [HttpGet(Name = "GetContracts")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ContractState[]))] + public IActionResult Get( + [FromQuery(Name = "page")] + int skip = 1, + [FromQuery(Name = "size")] + int take = 1) + { + if (skip < 1 || take < 1 || take > RestServerSettings.Current.MaxPageSize) + throw new InvalidParameterRangeException(); + var contracts = NativeContract.ContractManagement.ListContracts(_neosystem.StoreView); + if (contracts.Any() == false) + return NoContent(); + var contractRequestList = contracts.OrderBy(o => o.Manifest.Name).Skip((skip - 1) * take).Take(take); + if (contractRequestList.Any() == false) + return NoContent(); + return Ok(contractRequestList); + } + + /// + /// Gets count of total smart contracts on blockchain. + /// + /// Count Object + /// Successful + /// An error occurred. See Response for details. + [HttpGet("count", Name = "GetContractCount")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CountModel))] + public IActionResult GetCount() + { + var contracts = NativeContract.ContractManagement.ListContracts(_neosystem.StoreView); + return Ok(new CountModel() { Count = contracts.Count() }); + } + + /// + /// Get a smart contract's storage. + /// + /// ScriptHash + /// An array of the Key (Base64) Value (Base64) Pairs objects. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("{hash:required}/storage", Name = "GetContractStorage")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(KeyValuePair, ReadOnlyMemory>[]))] + public IActionResult GetContractStorage( + [FromRoute(Name = "hash")] + UInt160 scripthash) + { + if (NativeContract.IsNative(scripthash)) + return NoContent(); + var contract = NativeContract.ContractManagement.GetContract(_neosystem.StoreView, scripthash); + if (contract == null) + throw new ContractNotFoundException(scripthash); + var contractStorage = contract.GetStorage(_neosystem.StoreView); + return Ok(contractStorage.Select(s => new KeyValuePair, ReadOnlyMemory>(s.key.Key, s.value.Value))); + } + + /// + /// Get a smart contract. + /// + /// ScriptHash + /// Contract Object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("{hash:required}", Name = "GetContract")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ContractState))] + public IActionResult GetByScriptHash( + [FromRoute(Name = "hash")] + UInt160 scripthash) + { + var contracts = NativeContract.ContractManagement.GetContract(_neosystem.StoreView, scripthash); + if (contracts == null) + throw new ContractNotFoundException(scripthash); + return Ok(contracts); + } + + /// + /// Get abi of a smart contract. + /// + /// ScriptHash + /// Contract Abi Object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("{hash:required}/abi", Name = "GetContractAbi")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ContractAbi))] + public IActionResult GetContractAbi( + [FromRoute(Name = "hash")] + UInt160 scripthash) + { + var contracts = NativeContract.ContractManagement.GetContract(_neosystem.StoreView, scripthash); + if (contracts == null) + throw new ContractNotFoundException(scripthash); + return Ok(contracts.Manifest.Abi); + } + /// + /// Get manifest of a smart contract. + /// + /// ScriptHash + /// Contract Manifest object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("{hash:required}/manifest", Name = "GetContractManifest")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ContractManifest))] + public IActionResult GetContractManifest( + [FromRoute(Name = "hash")] + UInt160 scripthash) + { + var contracts = NativeContract.ContractManagement.GetContract(_neosystem.StoreView, scripthash); + if (contracts == null) + throw new ContractNotFoundException(scripthash); + return Ok(contracts.Manifest); + } + /// + /// Get nef of a smart contract. + /// + /// ScriptHash + /// Contract Nef object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("{hash:required}/nef", Name = "GetContractNefFile")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(NefFile))] + public IActionResult GetContractNef( + [FromRoute(Name = "hash")] + UInt160 scripthash) + { + var contracts = NativeContract.ContractManagement.GetContract(_neosystem.StoreView, scripthash); + if (contracts == null) + throw new ContractNotFoundException(scripthash); + return Ok(contracts.Nef); + } + + /// + /// Invoke a method as ReadOnly Flag on a smart contract. + /// + /// ScriptHash + /// method name + /// JArray of the contract parameters. + /// Execution Engine object. + /// Successful + /// An error occurred. See Response for details. + [HttpPost("{hash:required}/invoke", Name = "InvokeContractMethod")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ExecutionEngineModel))] + public IActionResult InvokeContract( + [FromRoute(Name = "hash")] + UInt160 scripthash, + [FromQuery(Name = "method")] + string method, + [FromBody] + ContractParameter[] contractParameters) + { + var contracts = NativeContract.ContractManagement.GetContract(_neosystem.StoreView, scripthash); + if (contracts == null) + throw new ContractNotFoundException(scripthash); + if (string.IsNullOrEmpty(method)) + throw new QueryParameterNotFoundException(nameof(method)); + try + { + var engine = ScriptHelper.InvokeMethod(_neosystem.Settings, _neosystem.StoreView, contracts.Hash, method, contractParameters, out var script); + return Ok(engine.ToModel()); + } + catch (Exception ex) + { + throw ex?.InnerException ?? ex; + } + } + } +} diff --git a/src/RestServer/Controllers/v1/LedgerController.cs b/src/RestServer/Controllers/v1/LedgerController.cs new file mode 100644 index 000000000..31d669f74 --- /dev/null +++ b/src/RestServer/Controllers/v1/LedgerController.cs @@ -0,0 +1,389 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Neo.Network.P2P.Payloads; +using Neo.Plugins.RestServer.Exceptions; +using Neo.Plugins.RestServer.Extensions; +using Neo.Plugins.RestServer.Models.Blockchain; +using Neo.Plugins.RestServer.Models.Error; +using Neo.Plugins.RestServer.Models.Ledger; +using Neo.SmartContract.Native; +using System.Net.Mime; + +namespace Neo.Plugins.RestServer.Controllers.v1 +{ + [Route("/api/v{version:apiVersion}/ledger")] + [Produces(MediaTypeNames.Application.Json)] + [Consumes(MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(ErrorModel))] + [ApiVersion("1.0")] + [ApiController] + public class LedgerController : ControllerBase + { + private readonly NeoSystem _neosystem; + + public LedgerController() + { + _neosystem = RestServerPlugin.NeoSystem ?? throw new NodeNetworkException(); + } + + #region Accounts + + /// + /// Gets all the accounts that hold gas on the blockchain. + /// + /// An array of account details object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("gas/accounts", Name = "GetGasAccounts")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(AccountDetails[]))] + public IActionResult ShowGasAccounts() + { + var accounts = NativeContract.GAS.ListAccounts(_neosystem.StoreView, _neosystem.Settings); + return Ok(accounts.OrderByDescending(o => o.Balance)); + } + + /// + /// Get all the accounts that hold neo on the blockchain. + /// + /// An array of account details object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("neo/accounts", Name = "GetNeoAccounts")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(AccountDetails[]))] + public IActionResult ShowNeoAccounts() + { + var accounts = NativeContract.NEO.ListAccounts(_neosystem.StoreView, _neosystem.Settings); + return Ok(accounts.OrderByDescending(o => o.Balance)); + } + + #endregion + + #region Blocks + + /// + /// Get blocks from the blockchain. + /// + /// Page + /// Page Size + /// An array of Block Header Objects + /// No more pages. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("blocks", Name = "GetBlocks")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Header[]))] + public IActionResult GetBlocks( + [FromQuery(Name = "page")] + uint skip = 1, + [FromQuery(Name = "size")] + uint take = 1) + { + if (skip < 1 || take < 1 || take > RestServerSettings.Current.MaxPageSize) + throw new InvalidParameterRangeException(); + //var start = (skip - 1) * take + startIndex; + //var end = start + take; + var start = NativeContract.Ledger.CurrentIndex(_neosystem.StoreView) - (skip - 1) * take; + var end = start - take; + var lstOfBlocks = new List
(); + for (uint i = start; i > end; i--) + { + var block = NativeContract.Ledger.GetBlock(_neosystem.StoreView, i); + if (block == null) + break; + lstOfBlocks.Add(block.Header); + } + if (lstOfBlocks.Any() == false) + return NoContent(); + return Ok(lstOfBlocks); + } + + /// + /// Gets the current block height of the connected node. + /// + /// Full Block Object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("blocks/height", Name = "GetBlockHeight")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Block))] + public IActionResult GetCurrentBlock() + { + var currentIndex = NativeContract.Ledger.CurrentIndex(_neosystem.StoreView); + var block = NativeContract.Ledger.GetHeader(_neosystem.StoreView, currentIndex); + return Ok(block); + } + + /// + /// Gets a block by an its index. + /// + /// Block Index + /// Full Block Object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("blocks/{index:min(0)}", Name = "GetBlock")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Block))] + public IActionResult GetBlock( + [FromRoute(Name = "index")] + uint blockIndex) + { + var block = NativeContract.Ledger.GetBlock(_neosystem.StoreView, blockIndex); + if (block == null) + throw new BlockNotFoundException(blockIndex); + return Ok(block); + } + + /// + /// Gets a block header by block index. + /// + /// Blocks index. + /// Block Header Object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("blocks/{index:min(0)}/header", Name = "GetBlockHeader")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Header))] + public IActionResult GetBlockHeader( + [FromRoute(Name = "index")] + uint blockIndex) + { + var block = NativeContract.Ledger.GetBlock(_neosystem.StoreView, blockIndex); + if (block == null) + throw new BlockNotFoundException(blockIndex); + return Ok(block.Header); + } + + /// + /// Gets the witness of the block + /// + /// Block Index. + /// Witness Object + /// Successful + /// An error occurred. See Response for details. + [HttpGet("blocks/{index:min(0)}/witness", Name = "GetBlockWitness")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Witness))] + public IActionResult GetBlockWitness( + [FromRoute(Name = "index")] + uint blockIndex) + { + var block = NativeContract.Ledger.GetBlock(_neosystem.StoreView, blockIndex); + if (block == null) + throw new BlockNotFoundException(blockIndex); + return Ok(block.Witness); + } + + /// + /// Gets the transactions of the block. + /// + /// Block Index. + /// Page + /// Page Size + /// An array of transaction object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("blocks/{index:min(0)}/transactions", Name = "GetBlockTransactions")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Transaction[]))] + public IActionResult GetBlockTransactions( + [FromRoute(Name = "index")] + uint blockIndex, + [FromQuery(Name = "page")] + int skip = 1, + [FromQuery(Name = "size")] + int take = 1) + { + if (skip < 1 || take < 1 || take > RestServerSettings.Current.MaxPageSize) + throw new InvalidParameterRangeException(); + var block = NativeContract.Ledger.GetBlock(_neosystem.StoreView, blockIndex); + if (block == null) + throw new BlockNotFoundException(blockIndex); + if (block.Transactions == null || block.Transactions.Length == 0) + return NoContent(); + return Ok(block.Transactions.Skip((skip - 1) * take).Take(take)); + } + + #endregion + + #region Transactions + + /// + /// Gets a transaction + /// + /// Hash256 + /// Transaction object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("transactions/{hash:required}", Name = "GetTransaction")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Transaction))] + public IActionResult GetTransaction( + [FromRoute( Name = "hash")] + UInt256 hash) + { + if (NativeContract.Ledger.ContainsTransaction(_neosystem.StoreView, hash) == false) + return NotFound(); + var txst = NativeContract.Ledger.GetTransaction(_neosystem.StoreView, hash); + if (txst == null) + throw new TransactionNotFoundException(hash); + return Ok(txst); + } + + /// + /// Gets the witness of a transaction. + /// + /// Hash256 + /// An array of witness object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("transactions/{hash:required}/witnesses", Name = "GetTransactionWitnesses")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Witness[]))] + public IActionResult GetTransactionWitnesses( + [FromRoute( Name = "hash")] + UInt256 hash) + { + if (NativeContract.Ledger.ContainsTransaction(_neosystem.StoreView, hash) == false) + throw new TransactionNotFoundException(hash); + var tx = NativeContract.Ledger.GetTransaction(_neosystem.StoreView, hash); + return Ok(tx.Witnesses); + } + + /// + /// Gets the signers of a transaction. + /// + /// Hash256 + /// An array of Signer object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("transactions/{hash:required}/signers", Name = "GetTransactionSigners")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Signer[]))] + public IActionResult GetTransactionSigners( + [FromRoute( Name = "hash")] + UInt256 hash) + { + if (NativeContract.Ledger.ContainsTransaction(_neosystem.StoreView, hash) == false) + throw new TransactionNotFoundException(hash); + var tx = NativeContract.Ledger.GetTransaction(_neosystem.StoreView, hash); + return Ok(tx.Signers); + } + + /// + /// Gets the transaction attributes of a transaction. + /// + /// Hash256 + /// An array of the transaction attributes object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("transactions/{hash:required}/attributes", Name = "GetTransactionAttributes")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(TransactionAttribute[]))] + public IActionResult GetTransactionAttributes( + [FromRoute( Name = "hash")] + UInt256 hash) + { + if (NativeContract.Ledger.ContainsTransaction(_neosystem.StoreView, hash) == false) + throw new TransactionNotFoundException(hash); + var tx = NativeContract.Ledger.GetTransaction(_neosystem.StoreView, hash); + return Ok(tx.Attributes); + } + + #endregion + + #region Memory Pool + + /// + /// Gets memory pool. + /// + /// Page + /// Page Size. + /// An array of the Transaction object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("memorypool", Name = "GetMemoryPoolTransactions")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Transaction[]))] + public IActionResult GetMemoryPool( + [FromQuery(Name = "page")] + int skip = 1, + [FromQuery(Name = "size")] + int take = 1) + { + if (skip < 0 || take < 0 || take > RestServerSettings.Current.MaxPageSize) + throw new InvalidParameterRangeException(); + return Ok(_neosystem.MemPool.Skip((skip - 1) * take).Take(take)); + } + + /// + /// Gets the count of the memory pool. + /// + /// Memory Pool Count Object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("memorypool/count", Name = "GetMemoryPoolCount")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(MemoryPoolCountModel))] + public IActionResult GetMemoryPoolCount() => + Ok(new MemoryPoolCountModel() + { + Count = _neosystem.MemPool.Count, + UnVerifiedCount = _neosystem.MemPool.UnVerifiedCount, + VerifiedCount = _neosystem.MemPool.VerifiedCount, + }); + + /// + /// Gets verified memory pool. + /// + /// Page + /// Page Size. + /// An array of the Transaction object. + /// No more pages. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("memorypool/verified", Name = "GetMemoryPoolVeridiedTransactions")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Transaction[]))] + public IActionResult GetMemoryPoolVerified( + [FromQuery(Name = "page")] + int skip = 1, + [FromQuery(Name = "size")] + int take = 1) + { + if (skip < 0 || take < 0 || take > RestServerSettings.Current.MaxPageSize) + throw new InvalidParameterRangeException(); + if (_neosystem.MemPool.Any() == false) + return NoContent(); + var vTx = _neosystem.MemPool.GetVerifiedTransactions(); + return Ok(vTx.Skip((skip - 1) * take).Take(take)); + } + + /// + /// Gets unverified memory pool. + /// + /// Page + /// Page Size. + /// An array of the Transaction object. + /// No more pages. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("memorypool/unverified", Name = "GetMemoryPoolUnveridiedTransactions")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Transaction[]))] + public IActionResult GetMemoryPoolUnVerified( + [FromQuery(Name = "page")] + int skip = 1, + [FromQuery(Name = "size")] + int take = 1) + { + if (skip < 0 || take < 0 || take > RestServerSettings.Current.MaxPageSize) + throw new InvalidParameterRangeException(); + if (_neosystem.MemPool.Any() == false) + return NoContent(); + _neosystem.MemPool.GetVerifiedAndUnverifiedTransactions(out _, out var unVerifiedTransactions); + return Ok(unVerifiedTransactions.Skip((skip - 1) * take).Take(take)); + } + + #endregion + } +} diff --git a/src/RestServer/Controllers/v1/NodeController.cs b/src/RestServer/Controllers/v1/NodeController.cs new file mode 100644 index 000000000..2bde367cc --- /dev/null +++ b/src/RestServer/Controllers/v1/NodeController.cs @@ -0,0 +1,86 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Neo.IO; +using Neo.Network.P2P; +using Neo.Plugins.RestServer.Exceptions; +using Neo.Plugins.RestServer.Extensions; +using Neo.Plugins.RestServer.Models.Error; +using Neo.Plugins.RestServer.Models.Node; +using System.Net.Mime; + +namespace Neo.Plugins.RestServer.Controllers.v1 +{ + [Route("/api/v{version:apiVersion}/node")] + [Produces(MediaTypeNames.Application.Json)] + [Consumes(MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(ErrorModel))] + [ApiVersion("1.0")] + [ApiController] + public class NodeController : ControllerBase + { + private readonly LocalNode _neolocalnode; + private readonly NeoSystem _neosystem; + + public NodeController() + { + _neolocalnode = RestServerPlugin.LocalNode; + _neosystem = RestServerPlugin.NeoSystem ?? throw new NodeNetworkException(); + } + + /// + /// Gets the connected remote nodes. + /// + /// An array of the Remote Node Objects. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("peers", Name = "GetNodeRemotePeers")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(RemoteNodeModel[]))] + public IActionResult GetPeers() + { + var rNodes = _neolocalnode + .GetRemoteNodes() + .OrderByDescending(o => o.LastBlockIndex) + .ToArray(); + + return Ok(rNodes.Select(s => s.ToModel())); + } + + /// + /// Gets all the loaded plugins of the current connected node. + /// + /// An array of the Plugin objects. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("plugins", Name = "GetNodePlugins")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(PluginModel[]))] + public IActionResult GetPlugins() => + Ok(Plugin.Plugins.Select(s => + new PluginModel() + { + Name = s.Name, + Version = s.Version.ToString(3), + Description = s.Description, + })); + + /// + /// Gets the ProtocolSettings of the currently connected node. + /// + /// Protocol Settings Object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("settings", Name = "GetNodeProtocolSettings")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ProtocolSettingsModel))] + public IActionResult GetSettings() => + Ok(_neosystem.Settings.ToModel()); + } +} diff --git a/src/RestServer/Controllers/v1/TokensController.cs b/src/RestServer/Controllers/v1/TokensController.cs new file mode 100644 index 000000000..a947d78cd --- /dev/null +++ b/src/RestServer/Controllers/v1/TokensController.cs @@ -0,0 +1,304 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Neo.Plugins.RestServer.Exceptions; +using Neo.Plugins.RestServer.Extensions; +using Neo.Plugins.RestServer.Helpers; +using Neo.Plugins.RestServer.Models; +using Neo.Plugins.RestServer.Models.Error; +using Neo.Plugins.RestServer.Models.Token; +using Neo.Plugins.RestServer.Tokens; +using Neo.SmartContract.Native; +using System.Net.Mime; + +namespace Neo.Plugins.RestServer.Controllers.v1 +{ + [Route("/api/v{version:apiVersion}/tokens")] + [Produces(MediaTypeNames.Application.Json)] + [Consumes(MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(ErrorModel))] + [ApiVersion("1.0")] + [ApiController] + public class TokensController : ControllerBase + { + private readonly NeoSystem _neosystem; + + public TokensController() + { + _neosystem = RestServerPlugin.NeoSystem ?? throw new NodeNetworkException(); + } + + #region NEP-17 + + /// + /// Gets all Nep-17 valid contracts from the blockchain. + /// + /// Page + /// Page Size + /// An array of the Nep-17 Token Object. + /// No more pages. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("nep-17", Name = "GetNep17Tokens")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(NEP17TokenModel[]))] + public IActionResult GetNEP17( + [FromQuery(Name = "page")] + int skip = 1, + [FromQuery(Name = "size")] + int take = 1) + { + if (skip < 1 || take < 1 || take > RestServerSettings.Current.MaxPageSize) + throw new InvalidParameterRangeException(); + var tokenList = NativeContract.ContractManagement.ListContracts(_neosystem.StoreView); + var vaildContracts = tokenList + .Where(w => ContractHelper.IsNep17Supported(w)) + .OrderBy(o => o.Manifest.Name) + .Skip((skip - 1) * take) + .Take(take); + if (vaildContracts.Any() == false) + return NoContent(); + var listResults = new List(); + foreach (var contract in vaildContracts) + { + try + { + var token = new NEP17Token(_neosystem, contract.Hash); + listResults.Add(token.ToModel()); + } + catch + { + } + } + if (listResults.Any() == false) + return NoContent(); + return Ok(listResults); + } + + /// + /// The count of how many Nep-17 contracts are on the blockchain. + /// + /// Count Object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("nep-17/count", Name = "GetNep17TokenCount")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CountModel))] + public IActionResult GetNEP17Count() + { + return Ok(new CountModel() + { + Count = NativeContract.ContractManagement.ListContracts(_neosystem.StoreView).Count(c => ContractHelper.IsNep17Supported(c)) + }); + } + + /// + /// Gets the balance of the Nep-17 contract by an address. + /// + /// Nep-17 ScriptHash + /// Neo Address ScriptHash + /// Token Balance Object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("nep-17/{scripthash:required}/balanceof/{address:required}", Name = "GetNep17TokenBalanceOf")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(TokenBalanceModel))] + public IActionResult GetNEP17( + [FromRoute(Name = "scripthash")] + UInt160 tokenAddessOrScripthash, + [FromRoute(Name = "address")] + UInt160 lookupAddressOrScripthash) + { + var contract = NativeContract.ContractManagement.GetContract(_neosystem.StoreView, tokenAddessOrScripthash); + if (contract == null) + throw new ContractNotFoundException(tokenAddessOrScripthash); + if (ContractHelper.IsNep17Supported(contract) == false) + throw new Nep17NotSupportedException(tokenAddessOrScripthash); + try + { + var token = new NEP17Token(_neosystem, tokenAddessOrScripthash); + return Ok(new TokenBalanceModel() + { + Name = token.Name, + ScriptHash = token.ScriptHash, + Symbol = token.Symbol, + Decimals = token.Decimals, + Balance = token.BalanceOf(lookupAddressOrScripthash).Value, + TotalSupply = token.TotalSupply().Value, + }); + } + catch + { + throw new Nep17NotSupportedException(tokenAddessOrScripthash); + } + } + + #endregion + + #region NEP-11 + + /// + /// Gets all the Nep-11 valid contracts on from the blockchain. + /// + /// Page + /// Page Size + /// Nep-11 Token Object. + /// No more pages. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("nep-11", Name = "GetNep11Tokens")] + [ProducesResponseType(StatusCodes.Status204NoContent)] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(NEP11TokenModel[]))] + public IActionResult GetNEP11( + [FromQuery(Name = "page")] + int skip = 1, + [FromQuery(Name = "size")] + int take = 1) + { + if (skip < 1 || take < 1 || take > RestServerSettings.Current.MaxPageSize) + throw new InvalidParameterRangeException(); + var tokenList = NativeContract.ContractManagement.ListContracts(_neosystem.StoreView); + var vaildContracts = tokenList + .Where(ContractHelper.IsNep11Supported) + .OrderBy(o => o.Manifest.Name) + .Skip((skip - 1) * take) + .Take(take); + if (vaildContracts.Any() == false) + return NoContent(); + var listResults = new List(); + foreach (var contract in vaildContracts) + { + try + { + var token = new NEP11Token(_neosystem, contract.Hash); + listResults.Add(token.ToModel()); + } + catch + { + } + } + if (listResults.Any() == false) + return NoContent(); + return Ok(listResults); + } + + /// + /// The count of how many Nep-11 contracts are on the blockchain. + /// + /// Count Object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("nep-11/count", Name = "GetNep11TokenCount")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CountModel))] + public IActionResult GetNEP11Count() + { + return Ok(new CountModel() { Count = NativeContract.ContractManagement.ListContracts(_neosystem.StoreView).Count(c => ContractHelper.IsNep11Supported(c)) }); + } + + /// + /// Gets the balance of the Nep-11 contract by an address. + /// + /// Nep-11 ScriptHash + /// Neo Address ScriptHash + /// Token Balance Object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("nep-11/{scripthash:required}/balanceof/{address:required}", Name = "GetNep11TokenBalanceOf")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(TokenBalanceModel))] + public IActionResult GetNEP11( + [FromRoute(Name = "scripthash")] + UInt160 sAddressHash, + [FromRoute(Name = "address")] + UInt160 addressHash) + { + var contract = NativeContract.ContractManagement.GetContract(_neosystem.StoreView, sAddressHash); + if (contract == null) + throw new ContractNotFoundException(sAddressHash); + if (ContractHelper.IsNep11Supported(contract) == false) + throw new Nep11NotSupportedException(sAddressHash); + try + { + var token = new NEP11Token(_neosystem, sAddressHash); + return Ok(new TokenBalanceModel() + { + Name = token.Name, + ScriptHash = token.ScriptHash, + Symbol = token.Symbol, + Decimals = token.Decimals, + Balance = token.BalanceOf(addressHash).Value, + TotalSupply = token.TotalSupply().Value, + }); + } + catch + { + throw new Nep11NotSupportedException(sAddressHash); + } + } + + #endregion + + /// + /// Gets every single NEP17/NEP11 on the blockchain's balance by ScriptHash + /// + /// + /// Token Balance Object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("balanceof/{address:required}", Name = "GetAllTokensBalanceOf")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(TokenBalanceModel))] + public IActionResult GetBalances( + [FromRoute(Name = "address")] + UInt160 addressOrScripthash) + { + var tokenList = NativeContract.ContractManagement.ListContracts(_neosystem.StoreView); + var validContracts = tokenList + .Where(w => ContractHelper.IsNep17Supported(w) || ContractHelper.IsNep11Supported(w)) + .OrderBy(o => o.Manifest.Name); + var listResults = new List(); + foreach (var contract in validContracts) + { + try + { + var token = new NEP17Token(_neosystem, contract.Hash); + var balance = token.BalanceOf(addressOrScripthash).Value; + if (balance == 0) + continue; + listResults.Add(new() + { + Name = token.Name, + ScriptHash = token.ScriptHash, + Symbol = token.Symbol, + Decimals = token.Decimals, + Balance = balance, + TotalSupply = token.TotalSupply().Value, + }); + + var nft = new NEP11Token(_neosystem, contract.Hash); + balance = nft.BalanceOf(addressOrScripthash).Value; + if (balance == 0) + continue; + listResults.Add(new() + { + Name = nft.Name, + ScriptHash = nft.ScriptHash, + Symbol = nft.Symbol, + Balance = balance, + Decimals = nft.Decimals, + TotalSupply = nft.TotalSupply().Value, + }); + } + catch (NotSupportedException) + { + } + } + return Ok(listResults); + } + } +} diff --git a/src/RestServer/Controllers/v1/UtilsController.cs b/src/RestServer/Controllers/v1/UtilsController.cs new file mode 100644 index 000000000..ad3f54342 --- /dev/null +++ b/src/RestServer/Controllers/v1/UtilsController.cs @@ -0,0 +1,106 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Neo.Plugins.RestServer.Exceptions; +using Neo.Plugins.RestServer.Models.Error; +using Neo.Plugins.RestServer.Models.Utils; +using Neo.Wallets; +using System.Net.Mime; + +namespace Neo.Plugins.RestServer.Controllers.v1 +{ + [Route("/api/v{version:apiVersion}/utils")] + [Produces(MediaTypeNames.Application.Json)] + [Consumes(MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(ErrorModel))] + [ApiVersion("1.0")] + [ApiController] + public class UtilsController : ControllerBase + { + private readonly NeoSystem _neosystem; + + public UtilsController() + { + _neosystem = RestServerPlugin.NeoSystem ?? throw new NodeNetworkException(); + } + + #region Validation + + /// + /// Converts script to Neo address. + /// + /// ScriptHash + /// Util Address Object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("{hash:required}/address", Name = "GetAddressByScripthash")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(UtilsAddressModel))] + public IActionResult ScriptHashToWalletAddress( + [FromRoute(Name = "hash")] + UInt160 ScriptHash) + { + try + { + return Ok(new UtilsAddressModel() { Address = ScriptHash.ToAddress(_neosystem.Settings.AddressVersion) }); + } + catch (FormatException) + { + throw new ScriptHashFormatException(); + } + } + + /// + /// Converts Neo address to ScriptHash + /// + /// Neo Address + /// Util ScriptHash Object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("{address:required}/scripthash", Name = "GetScripthashByAddress")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(UtilsScriptHashModel))] + public IActionResult WalletAddressToScriptHash( + [FromRoute(Name = "address")] + string address) + { + try + { + return Ok(new UtilsScriptHashModel() { ScriptHash = address.ToScriptHash(_neosystem.Settings.AddressVersion) }); + } + catch (FormatException) + { + throw new AddressFormatException(); + } + } + + /// + /// Get whether or not a Neo address or ScriptHash is valid. + /// + /// + /// Util Address Valid Object. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("{address:required}/validate", Name = "IsValidAddressOrScriptHash")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(UtilsAddressIsValidModel))] + public IActionResult ValidateAddress( + [FromRoute(Name = "address")] + string AddressOrScriptHash) + { + return Ok(new UtilsAddressIsValidModel() + { + Address = AddressOrScriptHash, + IsValid = RestServerUtility.TryConvertToScriptHash(AddressOrScriptHash, _neosystem.Settings, out _), + }); + } + + #endregion + } +} diff --git a/src/RestServer/Controllers/v1/WalletController.cs b/src/RestServer/Controllers/v1/WalletController.cs new file mode 100644 index 000000000..56760825c --- /dev/null +++ b/src/RestServer/Controllers/v1/WalletController.cs @@ -0,0 +1,646 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 Akka.Actor; +using Microsoft.AspNetCore.Cors; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Neo.Network.P2P.Payloads; +using Neo.Plugins.RestServer.Exceptions; +using Neo.Plugins.RestServer.Helpers; +using Neo.Plugins.RestServer.Models.Error; +using Neo.Plugins.RestServer.Models.Wallet; +using Neo.SmartContract; +using Neo.SmartContract.Native; +using Neo.Wallets; +using Neo.Wallets.NEP6; +using System.Net.Mime; +using System.Numerics; + +namespace Neo.Plugins.RestServer.Controllers.v1 +{ + /// + /// Wallet API + /// + [Route("/api/v{version:apiVersion}/wallet")] + [DisableCors] + [Produces(MediaTypeNames.Application.Json)] + [Consumes(MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(ErrorModel))] + [ApiVersion("1.0")] + [ApiController] + public class WalletController : ControllerBase + { + internal static WalletSessionManager WalletSessions { get; } = new(); + + private readonly NeoSystem _neosystem; + + /// + /// CTOR + /// + /// Node network doesn't match plugins network. + public WalletController() + { + _neosystem = RestServerPlugin.NeoSystem ?? throw new NodeNetworkException(); + } + + /// + /// Opens a wallet. + /// + /// + /// A newly created wallet session object. + /// Returns newly create wallet session object. + /// An error occurred. See Response for details. + [HttpPost("open", Name = "WalletOpen")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletSessionModel))] + public IActionResult WalletOpen( + [FromBody] + WalletOpenModel model) + { + if (new FileInfo(model.Path).DirectoryName.StartsWith(AppContext.BaseDirectory, StringComparison.InvariantCultureIgnoreCase) == false) + throw new UnauthorizedAccessException(model.Path); + if (System.IO.File.Exists(model.Path) == false) + throw new FileNotFoundException(null, model.Path); + var wallet = Wallet.Open(model.Path, model.Password, _neosystem.Settings); + if (wallet == null) + throw new WalletOpenException($"File '{model.Path}' could not be opened."); + var sessionId = Guid.NewGuid(); + WalletSessions[sessionId] = new WalletSession(wallet); + return Ok(new WalletSessionModel() + { + SessionId = sessionId, + }); + } + + /// + /// Closes a wallet session. + /// + /// Session Id of the open/created wallet. + /// Empty response body, if successful. + /// Successfully closed the wallet session. + /// An error occurred. See Response for details. + [HttpGet("{session:required}/close", Name = "WalletClose")] + [ProducesResponseType(StatusCodes.Status200OK)] + public IActionResult WalletClose( + [FromRoute(Name = "session")] + Guid sessionId) + { + if (WalletSessions.ContainsKey(sessionId) == false) + throw new KeyNotFoundException(sessionId.ToString("n")); + if (WalletSessions.TryRemove(sessionId, out _) == false) + throw new WalletSessionException("Failed to remove session."); + return Ok(); + } + + /// + /// Get all the keys of the wallet from each account. + /// + /// Session Id of the open/created wallet. + /// A list of export key objects. + /// Successfully exported the keys. + /// An error occurred. See Response for details. + [HttpGet("{session:required}/export", Name = "WalletExportKeys")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletExportKeyModel[]))] + public IActionResult WalletExport( + [FromRoute(Name = "session")] + Guid sessionId) + { + if (WalletSessions.ContainsKey(sessionId) == false) + throw new KeyNotFoundException(sessionId.ToString("n")); + var session = WalletSessions[sessionId]; + session.ResetExpiration(); + var wallet = session.Wallet; + var keys = wallet.GetAccounts().Where(p => p.HasKey) + .Select(s => new WalletExportKeyModel() + { + ScriptHash = s.ScriptHash, + Address = s.Address, + Wif = s.GetKey().Export() + }).ToArray(); + return Ok(keys); + } + + /// + /// Get a key of the wallet by a specific account. + /// + /// Session Id of the open/created wallet. + /// ScriptHash of the wallet address. + /// A export key object. + /// Successfully exported the key. + /// An error occurred. See Response for details. + [HttpGet("{session:required}/export/{address:required}", Name = "WalletExportKeysByAddressOrScripthash")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletExportKeyModel))] + public IActionResult WalletExportKey( + [FromRoute(Name = "session")] + Guid sessionId, + [FromRoute(Name = "address")] + UInt160 scriptHash) + { + if (WalletSessions.ContainsKey(sessionId) == false) + throw new KeyNotFoundException(sessionId.ToString("n")); + var session = WalletSessions[sessionId]; + session.ResetExpiration(); + var wallet = session.Wallet; + var account = wallet.GetAccount(scriptHash); + if (account == null) + throw new WalletException($"Account {scriptHash} doesn\'t exist."); + var key = account.GetKey(); + return Ok(new WalletExportKeyModel + { + ScriptHash = account.ScriptHash, + Address = account.Address, + Wif = key.Export(), + }); + } + + /// + /// Create a new address in the wallet with an optional private key. + /// + /// Session Id of the open/created wallet. + /// + /// Wallet address object. + /// Successfully created address. + /// An error occurred. See Response for details. + [HttpPost("{session:required}/address/create", Name = "WalletCreateAddress")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletAddressModel))] + public IActionResult WalletCreateNewAddress( + [FromRoute(Name = "session")] + Guid sessionId, + [FromBody] + WalletCreateAccountModel model) + { + if (WalletSessions.ContainsKey(sessionId) == false) + throw new KeyNotFoundException(sessionId.ToString("n")); + var session = WalletSessions[sessionId]; + session.ResetExpiration(); + var wallet = session.Wallet; + var account = model.PrivateKey == null || model.PrivateKey.Length == 0 ? + wallet.CreateAccount() : + wallet.CreateAccount(model.PrivateKey); + if (account == null) + throw new WalletException("Account couldn't be created."); + if (wallet is NEP6Wallet nep6) + nep6.Save(); + return Ok(new WalletAddressModel() + { + Address = account.Address, + ScriptHash = account.ScriptHash, + Publickey = account.GetKey().PublicKey, + HasKey = account.HasKey, + Label = account.Label, + WatchOnly = account.WatchOnly, + }); + } + + /// + /// Get the wallet balance of a specific asset. + /// + /// Session Id of the open/created wallet. + /// ScriptHash of the wallet address. + /// Account balance object of all the accounts in the wallet. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("{session:required}/balance/{asset:required}", Name = "WalletBalanceOf")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletAccountBalanceModel))] + public IActionResult WalletBalance( + [FromRoute(Name = "session")] + Guid sessionId, + [FromRoute(Name = "asset")] + UInt160 scriptHash) + { + if (WalletSessions.ContainsKey(sessionId) == false) + throw new KeyNotFoundException(sessionId.ToString("n")); + var session = WalletSessions[sessionId]; + session.ResetExpiration(); + var wallet = session.Wallet; + var balance = wallet.GetAvailable(_neosystem.StoreView, scriptHash); + return Ok(new WalletAccountBalanceModel() + { + Balance = balance.Value, + }); + } + + /// + /// Get unclaimed gas of the wallet for all accounts total. + /// + /// Session Id of the open/created wallet. + /// Account balance object + /// Successful + /// An error occurred. See Response for details. + [HttpGet("{session:required}/gas/unclaimed", Name = "GetUnClaimedGas")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletAccountBalanceModel))] + public IActionResult WalletUnClaimedGas( + [FromRoute(Name = "session")] + Guid sessionId) + { + if (WalletSessions.ContainsKey(sessionId) == false) + throw new KeyNotFoundException(sessionId.ToString("n")); + var session = WalletSessions[sessionId]; + session.ResetExpiration(); + var wallet = session.Wallet; + using var snapshot = _neosystem.GetSnapshot(); + uint height = NativeContract.Ledger.CurrentIndex(snapshot) + 1; + BigInteger gas = BigInteger.Zero; + foreach (var account in wallet.GetAccounts().Select(s => s.ScriptHash)) + gas += NativeContract.NEO.UnclaimedGas(snapshot, account, height); + return Ok(new WalletAccountBalanceModel + { + Balance = gas, + }); + } + + /// + /// import a private key into the wallet. + /// + /// Session Id of the open/created wallet. + /// + /// New wallet address object. + /// Successful + /// An error occurred. See Response for details. + [HttpPost("{session:required}/import", Name = "WalletImportByWif")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletAddressModel))] + public IActionResult WalletImportPrivateKey( + [FromRoute(Name = "session")] + Guid sessionId, + [FromBody] + WalletImportKey model) + { + if (WalletSessions.ContainsKey(sessionId) == false) + throw new KeyNotFoundException(sessionId.ToString("n")); + var session = WalletSessions[sessionId]; + session.ResetExpiration(); + var wallet = session.Wallet; + var account = wallet.Import(model.Wif); + if (account == null) + throw new WalletException("Account couldn\'t be imported."); + if (wallet is NEP6Wallet nep6) + nep6.Save(); + return Ok(new WalletAddressModel() + { + Address = account.Address, + ScriptHash = account.ScriptHash, + Publickey = account.GetKey().PublicKey, + HasKey = account.HasKey, + Label = account.Label, + WatchOnly = account.WatchOnly, + }); + } + + /// + /// List all the addresses in the wallet. + /// + /// Session Id of the open/created wallet. + /// An array of wallet address objects. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("{session:required}/address/list", Name = "GetWalletListAddress")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletAddressModel[]))] + public IActionResult WalletListAddresses( + [FromRoute(Name = "session")] + Guid sessionId) + { + if (WalletSessions.ContainsKey(sessionId) == false) + throw new KeyNotFoundException(sessionId.ToString("n")); + var session = WalletSessions[sessionId]; + session.ResetExpiration(); + var wallet = session.Wallet; + var accounts = new List(); + foreach (var account in wallet.GetAccounts()) + accounts.Add(new WalletAddressModel() + { + Address = account.Address, + ScriptHash = account.ScriptHash, + Publickey = account.GetKey().PublicKey, + HasKey = account.HasKey, + Label = account.Label, + WatchOnly = account.WatchOnly, + }); + return Ok(accounts); + } + + /// + /// Deletes an account from the wallet. + /// + /// Session Id of the open/created wallet. + /// ScriptHash of the wallet address. + /// Empty body response. + /// No backups are made. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("{session:required}/delete/{account:required}", Name = "WalletDeleteAccountByAddressOrScriptHash")] + [ProducesResponseType(StatusCodes.Status200OK)] + public IActionResult WalletDeleteAccount( + [FromRoute(Name = "session")] + Guid sessionId, + [FromRoute(Name = "account")] + UInt160 scriptHash) + { + if (WalletSessions.ContainsKey(sessionId) == false) + throw new KeyNotFoundException(sessionId.ToString("n")); + var session = WalletSessions[sessionId]; + session.ResetExpiration(); + var wallet = session.Wallet; + if (wallet.DeleteAccount(scriptHash) == false) + throw new WalletException($"Could not delete '{scriptHash}' account."); + else + { + if (wallet is NEP6Wallet wallet6) + wallet6.Save(); + return Ok(); + } + } + + /// + /// Trasnsfer assets from one wallet address to another address on the blockchain. + /// + /// Session Id of the open/created wallet. + /// + /// Transaction object + /// Successful + /// An error occurred. See Response for details. + [HttpPost("{session:required}/transfer", Name = "WalletTransferAssets")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Transaction))] + public IActionResult WalletTransferAssets( + [FromRoute(Name = "session")] + Guid sessionId, + [FromBody] + WalletSendModel model) + { + if (WalletSessions.ContainsKey(sessionId) == false) + throw new KeyNotFoundException(sessionId.ToString("n")); + var session = WalletSessions[sessionId]; + session.ResetExpiration(); + var wallet = session.Wallet; + using var snapshot = _neosystem.GetSnapshot(); + try + { + var descriptor = new AssetDescriptor(snapshot, _neosystem.Settings, model.AssetId); + var amount = new BigDecimal(model.Amount, descriptor.Decimals); + if (amount.Sign <= 0) + throw new WalletException($"Invalid Amount."); + var signers = model.Signers?.Select(s => new Signer() { Scopes = WitnessScope.CalledByEntry, Account = s }).ToArray(); + var tx = wallet.MakeTransaction(snapshot, + new[] + { + new TransferOutput() + { + AssetId = model.AssetId, + Value = amount, + ScriptHash = model.To, + Data = model.Data, + }, + }, + model.From, signers); + if (tx == null) + throw new WalletInsufficientFundsException(); + var totalFees = new BigDecimal((BigInteger)(tx.SystemFee + tx.NetworkFee), NativeContract.GAS.Decimals); + if (totalFees.Value > RestServerSettings.Current.MaxTransactionFee) + throw new WalletException("The transaction fees are to much."); + var context = new ContractParametersContext(snapshot, tx, _neosystem.Settings.Network); + wallet.Sign(context); + if (context.Completed == false) + throw new WalletException("Transaction could not be completed at this time."); + tx.Witnesses = context.GetWitnesses(); + _neosystem.Blockchain.Tell(tx); + return Ok(tx); + } + catch (Exception ex) + { + throw ex.InnerException ?? ex; + } + } + + /// + /// Create a wallet. + /// + /// + /// A wallet session object. + /// Successful + /// An error occurred. See Response for details. + [HttpPost("create", Name = "WalletCreate")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletSessionModel))] + public IActionResult WalletCreate( + [FromBody] + WalletCreateModel model) + { + if (new FileInfo(model.Path).DirectoryName.StartsWith(AppContext.BaseDirectory, StringComparison.InvariantCultureIgnoreCase) == false) + throw new UnauthorizedAccessException(model.Path); + var wallet = Wallet.Create(model.Name, model.Path, model.Password, _neosystem.Settings); + if (wallet == null) + throw new WalletException("Wallet files in that format are not supported, please use a .json or .db3 file extension."); + if (string.IsNullOrEmpty(model.Wif) == false) + wallet.Import(model.Wif); + if (wallet is NEP6Wallet nep6) + nep6.Save(); + var sessionId = Guid.NewGuid(); + WalletSessions[sessionId] = new WalletSession(wallet); + return Ok(new WalletSessionModel() + { + SessionId = sessionId, + }); + } + + /// + /// Import multi-signature addresss into the wallet. + /// + /// Session Id of the open/created wallet. + /// + /// + /// Successful + /// An error occurred. See Response for details. + [HttpPost("{session:required}/import/multisigaddress", Name = "WalletImportMultiSigAddress")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletMultiSignContractModel))] + public IActionResult WalletImportMultiSigAddress( + [FromRoute(Name = "session")] + Guid sessionId, + [FromBody] + WalletImportMultiSigAddressModel model) + { + if (WalletSessions.ContainsKey(sessionId) == false) + throw new KeyNotFoundException(sessionId.ToString("n")); + if (model.PublicKeys == null || model.PublicKeys.Length == 0) + throw new WalletException($"{nameof(model.PublicKeys)} is invalid."); + var session = WalletSessions[sessionId]; + var wallet = session.Wallet; + session.ResetExpiration(); + + int n = model.PublicKeys.Length; + + if (model.RequiredSignatures < 1 || model.RequiredSignatures > n || n > 1024) + throw new WalletException($"{nameof(model.RequiredSignatures)} and {nameof(model.PublicKeys)} is invalid."); + + Contract multiSignContract = Contract.CreateMultiSigContract(model.RequiredSignatures, model.PublicKeys); + KeyPair keyPair = wallet.GetAccounts().FirstOrDefault(p => p.HasKey && model.PublicKeys.Contains(p.GetKey().PublicKey))?.GetKey(); + if (keyPair == null) + throw new WalletException("Couldn\'t get key pair."); + var account = wallet.CreateAccount(multiSignContract, keyPair); + if (account == null) + throw new WalletException("Account couldn\'t be created."); + if (wallet is NEP6Wallet nep6) + nep6.Save(); + return Ok(new WalletMultiSignContractModel + { + Address = multiSignContract.ScriptHash.ToAddress(_neosystem.Settings.AddressVersion), + ScriptHash = multiSignContract.ScriptHash, + Script = multiSignContract.Script, + }); + } + + /// + /// List assets of the wallet. + /// + /// Session Id of the open/created wallet. + /// An array of wallet asset objects. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("{session:required}/asset/list", Name = "GetWalletAssetList")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletAssetModel[]))] + public IActionResult WalletListAsset( + [FromRoute(Name = "session")] + Guid sessionId) + { + if (WalletSessions.ContainsKey(sessionId) == false) + throw new KeyNotFoundException(sessionId.ToString("n")); + var session = WalletSessions[sessionId]; + var wallet = session.Wallet; + session.ResetExpiration(); + var assets = new List(); + foreach (var account in wallet.GetAccounts()) + assets.Add(new() + { + Address = account.Address, + ScriptHash = account.ScriptHash, + PublicKey = account.GetKey().PublicKey, + Neo = wallet.GetBalance(_neosystem.StoreView, NativeContract.NEO.Hash, account.ScriptHash).Value, + NeoHash = NativeContract.NEO.Hash, + Gas = wallet.GetBalance(_neosystem.StoreView, NativeContract.GAS.Hash, account.ScriptHash).Value, + GasHash = NativeContract.GAS.Hash, + }); + return Ok(assets); + } + + /// + /// List all account keys in the wallet. + /// + /// Session Id of the open/created wallet. + /// An array of wallet key objects. + /// Successful + /// An error occurred. See Response for details. + [HttpGet("{session:required}/key/list", Name = "GetWalletKeyList")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletKeyModel[]))] + public IActionResult WalletListKeys( + [FromRoute(Name = "session")] + Guid sessionId) + { + if (WalletSessions.ContainsKey(sessionId) == false) + throw new KeyNotFoundException(sessionId.ToString("n")); + var session = WalletSessions[sessionId]; + var wallet = session.Wallet; + session.ResetExpiration(); + var keys = new List(); + foreach (var account in wallet.GetAccounts().Where(w => w.HasKey)) + keys.Add(new() + { + Address = account.Address, + ScriptHash = account.ScriptHash, + PublicKey = account.GetKey().PublicKey, + }); + return Ok(keys); + } + + /// + /// Change wallet password. + /// + /// Session Id of the open/created wallet. + /// + /// Empty body response. + /// Successful + /// An error occurred. See Response for details. + [HttpPost("{session:required}/changepassword", Name = "WalletChangePassword")] + [ProducesResponseType(StatusCodes.Status200OK)] + public IActionResult WalletChangePassword( + [FromRoute(Name = "session")] + Guid sessionId, + [FromBody] + WalletChangePasswordModel model) + { + if (WalletSessions.ContainsKey(sessionId) == false) + throw new KeyNotFoundException(sessionId.ToString("n")); + if (model.OldPassword == model.NewPassword) + throw new WalletException($"{nameof(model.OldPassword)} is the same as {nameof(model.NewPassword)}."); + var session = WalletSessions[sessionId]; + var wallet = session.Wallet; + session.ResetExpiration(); + if (wallet.VerifyPassword(model.OldPassword) == false) + throw new WalletException("Invalid password! Session terminated!"); + if (model.CreateBackupFile && wallet is NEP6Wallet) + { + var bakFile = wallet.Path + $".{sessionId:n}.bak"; + if (System.IO.File.Exists(wallet.Path) == false) + throw new WalletException("Create wallet backup failed. Wallet file doesn\'t exist."); + if (System.IO.File.Exists(bakFile) && model.OverwriteIfBackupFileExists == false) + throw new WalletException("Backup File already exists for this session."); + System.IO.File.Copy(wallet.Path, bakFile, true); + } + if (wallet.ChangePassword(model.OldPassword, model.NewPassword) == false) + throw new WalletException("Failed to change password!"); + if (wallet is NEP6Wallet nep6) + nep6.Save(); + return Ok(); + } + + /// + /// Create a transaction with a script. + /// + /// Session Id of the open/created wallet. + /// + /// Transaction object. + /// Successful + /// An error occurred. See Response for details. + [HttpPost("{session:required}/transaction/script", Name = "WalletTransactionWithScript")] + [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Transaction))] + public IActionResult WalletTransactionWithScript( + [FromRoute(Name = "session")] + Guid sessionId, + [FromBody] + WalletTransactionScriptModel model) + { + if (WalletSessions.ContainsKey(sessionId) == false) + throw new KeyNotFoundException(sessionId.ToString("n")); + if (model.Script == null || model.Script.Length == 0) + throw new JsonPropertyNullOrEmptyException(nameof(model.Script)); + var session = WalletSessions[sessionId]; + session.ResetExpiration(); + var wallet = session.Wallet; + var signers = model.Signers?.Select(s => new Signer() { Scopes = WitnessScope.CalledByEntry, Account = s }).ToArray(); + var appEngine = ScriptHelper.InvokeScript(model.Script, signers); + if (appEngine.State != VM.VMState.HALT) + throw new ApplicationEngineException(appEngine.FaultException?.InnerException?.Message ?? appEngine.FaultException?.Message ?? string.Empty); + var tx = wallet.MakeTransaction(_neosystem.StoreView, model.Script, model.From, signers, maxGas: RestServerSettings.Current.MaxGasInvoke); + try + { + var context = new ContractParametersContext(_neosystem.StoreView, tx, _neosystem.Settings.Network); + wallet.Sign(context); + if (context.Completed == false) + throw new WalletException($"Incomplete signature: {context}"); + else + { + tx.Witnesses = context.GetWitnesses(); + _neosystem.Blockchain.Tell(tx); + return Ok(tx); + } + } + catch (Exception ex) + { + throw ex.InnerException ?? ex; + } + } + } +} diff --git a/src/RestServer/Exceptions/AddressFormatException.cs b/src/RestServer/Exceptions/AddressFormatException.cs new file mode 100644 index 000000000..e2249ac36 --- /dev/null +++ b/src/RestServer/Exceptions/AddressFormatException.cs @@ -0,0 +1,18 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Exceptions +{ + internal class AddressFormatException : Exception + { + public AddressFormatException() : base() { } + public AddressFormatException(string message) : base(message) { } + } +} diff --git a/src/RestServer/Exceptions/ApplicationEngineException.cs b/src/RestServer/Exceptions/ApplicationEngineException.cs new file mode 100644 index 000000000..37030f7e6 --- /dev/null +++ b/src/RestServer/Exceptions/ApplicationEngineException.cs @@ -0,0 +1,18 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Exceptions +{ + internal class ApplicationEngineException : Exception + { + public ApplicationEngineException() : base() { } + public ApplicationEngineException(string message) : base(message) { } + } +} diff --git a/src/RestServer/Exceptions/BlockNotFoundException.cs b/src/RestServer/Exceptions/BlockNotFoundException.cs new file mode 100644 index 000000000..c669afcf5 --- /dev/null +++ b/src/RestServer/Exceptions/BlockNotFoundException.cs @@ -0,0 +1,18 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Exceptions +{ + internal class BlockNotFoundException : Exception + { + public BlockNotFoundException() { } + public BlockNotFoundException(uint index) : base($"block '{index}' as not found.") { } + } +} diff --git a/src/RestServer/Exceptions/ContractNotFoundException.cs b/src/RestServer/Exceptions/ContractNotFoundException.cs new file mode 100644 index 000000000..f363c467e --- /dev/null +++ b/src/RestServer/Exceptions/ContractNotFoundException.cs @@ -0,0 +1,18 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Exceptions +{ + internal class ContractNotFoundException : Exception + { + public ContractNotFoundException() : base() { } + public ContractNotFoundException(UInt160 scriptHash) : base($"Contract '{scriptHash}' was not found.") { } + } +} diff --git a/src/RestServer/Exceptions/InvalidParameterRangeException.cs b/src/RestServer/Exceptions/InvalidParameterRangeException.cs new file mode 100644 index 000000000..021e40cf5 --- /dev/null +++ b/src/RestServer/Exceptions/InvalidParameterRangeException.cs @@ -0,0 +1,18 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Exceptions +{ + internal class InvalidParameterRangeException : Exception + { + public InvalidParameterRangeException() : base() { } + public InvalidParameterRangeException(string message) : base(message) { } + } +} diff --git a/src/RestServer/Exceptions/JsonPropertyNullOrEmptyException.cs b/src/RestServer/Exceptions/JsonPropertyNullOrEmptyException.cs new file mode 100644 index 000000000..6afe08e79 --- /dev/null +++ b/src/RestServer/Exceptions/JsonPropertyNullOrEmptyException.cs @@ -0,0 +1,19 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Exceptions +{ + internal class JsonPropertyNullOrEmptyException : Exception + { + public JsonPropertyNullOrEmptyException() : base() { } + + public JsonPropertyNullOrEmptyException(string paramName) : base($"Value cannot be null or empty. (Parameter '{paramName}')") { } + } +} diff --git a/src/RestServer/Exceptions/Nep11NotSupportedException.cs b/src/RestServer/Exceptions/Nep11NotSupportedException.cs new file mode 100644 index 000000000..5382dbdef --- /dev/null +++ b/src/RestServer/Exceptions/Nep11NotSupportedException.cs @@ -0,0 +1,18 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Exceptions +{ + internal class Nep11NotSupportedException : Exception + { + public Nep11NotSupportedException() { } + public Nep11NotSupportedException(UInt160 scriptHash) : base($"Contract '{scriptHash}' does not support NEP-11.") { } + } +} diff --git a/src/RestServer/Exceptions/Nep17NotSupportedException.cs b/src/RestServer/Exceptions/Nep17NotSupportedException.cs new file mode 100644 index 000000000..00e672a1f --- /dev/null +++ b/src/RestServer/Exceptions/Nep17NotSupportedException.cs @@ -0,0 +1,18 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Exceptions +{ + internal class Nep17NotSupportedException : Exception + { + public Nep17NotSupportedException() { } + public Nep17NotSupportedException(UInt160 scriptHash) : base($"Contract '{scriptHash}' does not support NEP-17.") { } + } +} diff --git a/src/RestServer/Exceptions/NodeException.cs b/src/RestServer/Exceptions/NodeException.cs new file mode 100644 index 000000000..f59ec669d --- /dev/null +++ b/src/RestServer/Exceptions/NodeException.cs @@ -0,0 +1,18 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Exceptions +{ + internal class NodeException : Exception + { + public NodeException() : base() { } + public NodeException(string message) : base(message) { } + } +} diff --git a/src/RestServer/Exceptions/NodeNetworkException.cs b/src/RestServer/Exceptions/NodeNetworkException.cs new file mode 100644 index 000000000..da45244b2 --- /dev/null +++ b/src/RestServer/Exceptions/NodeNetworkException.cs @@ -0,0 +1,18 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Exceptions +{ + internal class NodeNetworkException : Exception + { + public NodeNetworkException() : base("Network does not match config file's.") { } + public NodeNetworkException(string message) : base(message) { } + } +} diff --git a/src/RestServer/Exceptions/QueryParameterNotFoundException.cs b/src/RestServer/Exceptions/QueryParameterNotFoundException.cs new file mode 100644 index 000000000..8be1af0eb --- /dev/null +++ b/src/RestServer/Exceptions/QueryParameterNotFoundException.cs @@ -0,0 +1,18 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Exceptions +{ + internal class QueryParameterNotFoundException : Exception + { + public QueryParameterNotFoundException() { } + public QueryParameterNotFoundException(string parameterName) : base($"Query parameter '{parameterName}' was not found.") { } + } +} diff --git a/src/RestServer/Exceptions/RestErrorCodes.cs b/src/RestServer/Exceptions/RestErrorCodes.cs new file mode 100644 index 000000000..2fb434106 --- /dev/null +++ b/src/RestServer/Exceptions/RestErrorCodes.cs @@ -0,0 +1,19 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Exceptions +{ + internal static class RestErrorCodes + { + //=========================Rest Codes========================= + public const int GenericException = 1000; + public const int ParameterFormatException = 1001; + } +} diff --git a/src/RestServer/Exceptions/ScriptHashFormatException.cs b/src/RestServer/Exceptions/ScriptHashFormatException.cs new file mode 100644 index 000000000..dcfe04f87 --- /dev/null +++ b/src/RestServer/Exceptions/ScriptHashFormatException.cs @@ -0,0 +1,18 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Exceptions +{ + internal class ScriptHashFormatException : Exception + { + public ScriptHashFormatException() : base() { } + public ScriptHashFormatException(string message) : base(message) { } + } +} diff --git a/src/RestServer/Exceptions/TransactionNotFoundException.cs b/src/RestServer/Exceptions/TransactionNotFoundException.cs new file mode 100644 index 000000000..e27e810cc --- /dev/null +++ b/src/RestServer/Exceptions/TransactionNotFoundException.cs @@ -0,0 +1,18 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Exceptions +{ + internal class TransactionNotFoundException : Exception + { + public TransactionNotFoundException() { } + public TransactionNotFoundException(UInt256 txhash) : base($"Transaction '{txhash}' was not found.") { } + } +} diff --git a/src/RestServer/Exceptions/UInt256FormatException.cs b/src/RestServer/Exceptions/UInt256FormatException.cs new file mode 100644 index 000000000..9d77cf295 --- /dev/null +++ b/src/RestServer/Exceptions/UInt256FormatException.cs @@ -0,0 +1,18 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Exceptions +{ + internal class UInt256FormatException : Exception + { + public UInt256FormatException() { } + public UInt256FormatException(string message) : base(message) { } + } +} diff --git a/src/RestServer/Exceptions/WalletException.cs b/src/RestServer/Exceptions/WalletException.cs new file mode 100644 index 000000000..47861b083 --- /dev/null +++ b/src/RestServer/Exceptions/WalletException.cs @@ -0,0 +1,18 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Exceptions +{ + internal class WalletException : Exception + { + public WalletException() : base() { } + public WalletException(string message) : base(message) { } + } +} diff --git a/src/RestServer/Exceptions/WalletInsufficientFundsException.cs b/src/RestServer/Exceptions/WalletInsufficientFundsException.cs new file mode 100644 index 000000000..9b061c590 --- /dev/null +++ b/src/RestServer/Exceptions/WalletInsufficientFundsException.cs @@ -0,0 +1,18 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Exceptions +{ + internal class WalletInsufficientFundsException : Exception + { + public WalletInsufficientFundsException() : base("Wallet has insufficient funds.") { } + public WalletInsufficientFundsException(string message) : base(message) { } + } +} diff --git a/src/RestServer/Exceptions/WalletOpenException.cs b/src/RestServer/Exceptions/WalletOpenException.cs new file mode 100644 index 000000000..bcdfa3317 --- /dev/null +++ b/src/RestServer/Exceptions/WalletOpenException.cs @@ -0,0 +1,19 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Exceptions +{ + internal class WalletOpenException : Exception + { + public WalletOpenException() : base() { } + + public WalletOpenException(string message) : base(message) { } + } +} diff --git a/src/RestServer/Exceptions/WalletSessionException.cs b/src/RestServer/Exceptions/WalletSessionException.cs new file mode 100644 index 000000000..b6db9bea7 --- /dev/null +++ b/src/RestServer/Exceptions/WalletSessionException.cs @@ -0,0 +1,18 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Exceptions +{ + internal class WalletSessionException : Exception + { + public WalletSessionException() : base() { } + public WalletSessionException(string message) : base(message) { } + } +} diff --git a/src/RestServer/Extensions/LedgerContractExtensions.cs b/src/RestServer/Extensions/LedgerContractExtensions.cs new file mode 100644 index 000000000..7a86db8f8 --- /dev/null +++ b/src/RestServer/Extensions/LedgerContractExtensions.cs @@ -0,0 +1,142 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.IO; +using Neo.Persistence; +using Neo.Plugins.RestServer.Models.Blockchain; +using Neo.SmartContract; +using Neo.SmartContract.Native; +using Neo.Wallets; + +#pragma warning disable IDE0060 + +namespace Neo.Plugins.RestServer.Extensions +{ + internal static class LedgerContractExtensions + { + private const byte _prefix_block = 5; + private const byte _prefix_transaction = 11; + private const byte _prefix_account = 20; + private const byte _prefix_totalsupply = 11; + + public static IEnumerable<(StorageKey key, StorageItem value)> GetStorageByPrefix(this ContractState contractState, DataCache snapshot, byte[] prefix) + { + ArgumentNullException.ThrowIfNull(nameof(contractState)); + ArgumentNullException.ThrowIfNull(nameof(snapshot)); + if (prefix?.Length == 0) + throw new ArgumentNullException(nameof(prefix)); + foreach (var (key, value) in snapshot.Find(StorageKey.CreateSearchPrefix(contractState.Id, prefix))) + yield return (key, value); + } + + public static StorageItem GetStorageByKey(this ContractState contractState, DataCache snapshot, byte[] storageKey) + { + ArgumentNullException.ThrowIfNull(nameof(contractState)); + ArgumentNullException.ThrowIfNull(nameof(snapshot)); + if (storageKey?.Length == 0) + throw new ArgumentNullException(nameof(storageKey)); + foreach (var (key, value) in snapshot.Find(StorageKey.CreateSearchPrefix(contractState.Id, storageKey))) + if (key.Key.Span.SequenceEqual(storageKey)) + return value; + return default; + } + + public static IEnumerable<(StorageKey key, StorageItem value)> GetStorage(this ContractState contractState, DataCache snapshot) + { + ArgumentNullException.ThrowIfNull(nameof(contractState)); + ArgumentNullException.ThrowIfNull(nameof(snapshot)); + return ListContractStorage(null, snapshot, contractState.Id); + } + + public static IEnumerable<(StorageKey key, StorageItem value)> ListContractStorage(this ContractManagement contractManagement, DataCache snapshot, int contractId) + { + ArgumentNullException.ThrowIfNull(nameof(snapshot)); + if (contractId < 0) + throw new ArgumentOutOfRangeException(nameof(contractId)); + foreach (var (key, value) in snapshot.Find(StorageKey.CreateSearchPrefix(contractId, ReadOnlySpan.Empty))) + yield return (key, value); + } + + public static IEnumerable ListBlocks(this LedgerContract ledger, DataCache snapshot) + { + ArgumentNullException.ThrowIfNull(nameof(snapshot)); + var kb = new KeyBuilder(NativeContract.Ledger.Id, _prefix_block); + var prefixKey = kb.ToArray(); + foreach (var (key, value) in snapshot.Seek(prefixKey, SeekDirection.Forward)) + if (key.ToArray().AsSpan().StartsWith(prefixKey)) + yield return value.Value.AsSerializable(); + else + yield break; + } + + public static IEnumerable ListTransactions(this LedgerContract ledger, DataCache snapshot, uint page, uint pageSize) + { + ArgumentNullException.ThrowIfNull(nameof(snapshot)); + var kb = new KeyBuilder(NativeContract.Ledger.Id, _prefix_transaction); + var prefixKey = kb.ToArray(); + uint index = 1; + foreach (var (key, value) in snapshot.Seek(prefixKey, SeekDirection.Forward)) + { + if (key.ToArray().AsSpan().StartsWith(prefixKey)) + { + if (index >= page && index < (pageSize + page)) + yield return value.GetInteroperable(); + index++; + } + else + yield break; + } + } + + public static IEnumerable ListAccounts(this GasToken gasToken, DataCache snapshot, ProtocolSettings protocolSettings) + { + ArgumentNullException.ThrowIfNull(nameof(snapshot)); + var kb = new KeyBuilder(gasToken.Id, _prefix_account); + var prefixKey = kb.ToArray(); + foreach (var (key, value) in snapshot.Seek(prefixKey, SeekDirection.Forward)) + { + if (key.ToArray().AsSpan().StartsWith(prefixKey)) + { + var addressHash = new UInt160(key.ToArray().AsSpan(5)); + yield return new AccountDetails() + { + ScriptHash = addressHash, + Address = addressHash.ToAddress(protocolSettings.AddressVersion), + Balance = value.GetInteroperable().Balance, + }; + } + else + yield break; + } + } + + public static IEnumerable ListAccounts(this NeoToken neoToken, DataCache snapshot, ProtocolSettings protocolSettings) + { + ArgumentNullException.ThrowIfNull(nameof(snapshot)); + var kb = new KeyBuilder(neoToken.Id, _prefix_account); + var prefixKey = kb.ToArray(); + foreach (var (key, value) in snapshot.Seek(prefixKey, SeekDirection.Forward)) + { + if (key.ToArray().AsSpan().StartsWith(prefixKey)) + { + var addressHash = new UInt160(key.ToArray().AsSpan(5)); + yield return new AccountDetails() + { + ScriptHash = addressHash, + Address = addressHash.ToAddress(protocolSettings.AddressVersion), + Balance = value.GetInteroperable().Balance, + }; + } + else + yield break; + } + } + } +} diff --git a/src/RestServer/Extensions/ModelExtensions.cs b/src/RestServer/Extensions/ModelExtensions.cs new file mode 100644 index 000000000..027b559c5 --- /dev/null +++ b/src/RestServer/Extensions/ModelExtensions.cs @@ -0,0 +1,99 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Network.P2P; +using Neo.Plugins.RestServer.Models; +using Neo.Plugins.RestServer.Models.Error; +using Neo.Plugins.RestServer.Models.Node; +using Neo.Plugins.RestServer.Models.Token; +using Neo.Plugins.RestServer.Tokens; +using Neo.SmartContract; + +namespace Neo.Plugins.RestServer.Extensions +{ + internal static class ModelExtensions + { + public static ExecutionEngineModel ToModel(this ApplicationEngine ae) => + new() + { + GasConsumed = ae.GasConsumed, + State = ae.State, + Notifications = ae.Notifications.Select(s => + new BlockchainEventModel() + { + ScriptHash = s.ScriptHash, + EventName = s.EventName, + State = s.State.ToArray(), + }).ToArray(), + ResultStack = ae.ResultStack.ToArray(), + FaultException = ae.FaultException == null ? + null : + new ErrorModel() + { + Code = ae.FaultException?.InnerException?.HResult ?? ae.FaultException.HResult, + Name = ae.FaultException?.InnerException?.GetType().Name ?? ae.FaultException?.GetType().Name, + Message = ae.FaultException?.InnerException?.Message ?? ae.FaultException?.Message, + }, + }; + + public static NEP17TokenModel ToModel(this NEP17Token token) => + new() + { + Name = token.Name, + Symbol = token.Symbol, + ScriptHash = token.ScriptHash, + Decimals = token.Decimals, + TotalSupply = token.TotalSupply().Value, + }; + + public static NEP11TokenModel ToModel(this NEP11Token nep11) => + new() + { + Name = nep11.Name, + ScriptHash = nep11.ScriptHash, + Symbol = nep11.Symbol, + Decimals = nep11.Decimals, + TotalSupply = nep11.TotalSupply().Value, + Tokens = nep11.Tokens().Select(s => new + { + Key = s, + Value = nep11.Properties(s), + }).ToDictionary(key => Convert.ToHexString(key.Key), value => value.Value), + }; + + public static ProtocolSettingsModel ToModel(this ProtocolSettings protocolSettings) => + new() + { + Network = protocolSettings.Network, + AddressVersion = protocolSettings.AddressVersion, + ValidatorsCount = protocolSettings.ValidatorsCount, + MillisecondsPerBlock = protocolSettings.MillisecondsPerBlock, + MaxValidUntilBlockIncrement = protocolSettings.MaxValidUntilBlockIncrement, + MaxTransactionsPerBlock = protocolSettings.MaxTransactionsPerBlock, + MemoryPoolMaxTransactions = protocolSettings.MemoryPoolMaxTransactions, + MaxTraceableBlocks = protocolSettings.MaxTraceableBlocks, + InitialGasDistribution = protocolSettings.InitialGasDistribution, + SeedList = protocolSettings.SeedList, + NativeUpdateHistory = protocolSettings.NativeUpdateHistory, + Hardforks = protocolSettings.Hardforks, + StandbyValidators = protocolSettings.StandbyValidators, + StandbyCommittee = protocolSettings.StandbyCommittee, + }; + + public static RemoteNodeModel ToModel(this RemoteNode remoteNode) => + new() + { + RemoteAddress = remoteNode.Remote.Address.ToString(), + RemotePort = remoteNode.Remote.Port, + ListenTcpPort = remoteNode.ListenerTcpPort, + LastBlockIndex = remoteNode.LastBlockIndex, + }; + } +} diff --git a/src/RestServer/Extensions/UInt160Extensions.cs b/src/RestServer/Extensions/UInt160Extensions.cs new file mode 100644 index 000000000..472948257 --- /dev/null +++ b/src/RestServer/Extensions/UInt160Extensions.cs @@ -0,0 +1,27 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Plugins.RestServer.Helpers; +using Neo.SmartContract.Native; + +namespace Neo.Plugins.RestServer.Extensions +{ + internal static class UInt160Extensions + { + public static bool IsValidNep17(this UInt160 scriptHash) + { + var contractState = NativeContract.ContractManagement.GetContract(RestServerPlugin.NeoSystem.StoreView, scriptHash); + return ContractHelper.IsNep17Supported(contractState); + } + + public static bool IsValidContract(this UInt160 scriptHash) => + NativeContract.ContractManagement.GetContract(RestServerPlugin.NeoSystem.StoreView, scriptHash) != null; + } +} diff --git a/src/RestServer/Helpers/ContractHelper.cs b/src/RestServer/Helpers/ContractHelper.cs new file mode 100644 index 000000000..f2f7bcda0 --- /dev/null +++ b/src/RestServer/Helpers/ContractHelper.cs @@ -0,0 +1,58 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Persistence; +using Neo.SmartContract; +using Neo.SmartContract.Manifest; +using Neo.SmartContract.Native; + +namespace Neo.Plugins.RestServer.Helpers +{ + public static class ContractHelper + { + public static ContractParameterDefinition[] GetAbiEventParams(DataCache snapshot, UInt160 scriptHash, string eventName) + { + var contractState = NativeContract.ContractManagement.GetContract(snapshot, scriptHash); + if (contractState == null) + return Array.Empty(); + return contractState.Manifest.Abi.Events.SingleOrDefault(s => s.Name.Equals(eventName, StringComparison.OrdinalIgnoreCase))?.Parameters; + } + + public static bool IsNep17Supported(DataCache snapshot, UInt160 scriptHash) + { + var contractState = NativeContract.ContractManagement.GetContract(snapshot, scriptHash); + if (contractState == null) + return false; + return IsNep17Supported(contractState); + } + + public static bool IsNep11Supported(DataCache snapshot, UInt160 scriptHash) + { + var contractState = NativeContract.ContractManagement.GetContract(snapshot, scriptHash); + if (contractState == null) + return false; + return IsNep11Supported(contractState); + } + + public static bool IsNep17Supported(ContractState contractState) => + contractState.Manifest.SupportedStandards.Any(a => a.Equals("NEP-17")); + + public static bool IsNep11Supported(ContractState contractState) => + contractState.Manifest.SupportedStandards.Any(a => a.Equals("NEP-11")); + + public static ContractMethodDescriptor GetContractMethod(DataCache snapshot, UInt160 scriptHash, string method, int pCount) + { + var contractState = NativeContract.ContractManagement.GetContract(snapshot, scriptHash); + if (contractState == null) + return null; + return contractState.Manifest.Abi.GetMethod(method, pCount); + } + } +} diff --git a/src/RestServer/Helpers/ScriptHelper.cs b/src/RestServer/Helpers/ScriptHelper.cs new file mode 100644 index 000000000..092fdcc84 --- /dev/null +++ b/src/RestServer/Helpers/ScriptHelper.cs @@ -0,0 +1,59 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Network.P2P.Payloads; +using Neo.Persistence; +using Neo.SmartContract; +using Neo.SmartContract.Native; +using Neo.VM; +using Neo.VM.Types; +using Array = System.Array; + +namespace Neo.Plugins.RestServer.Helpers +{ + internal static class ScriptHelper + { + public static bool InvokeMethod(ProtocolSettings protocolSettings, DataCache snapshot, UInt160 scriptHash, string method, out StackItem[] results, params object[] args) + { + using var scriptBuilder = new ScriptBuilder(); + scriptBuilder.EmitDynamicCall(scriptHash, method, CallFlags.ReadOnly, args); + byte[] script = scriptBuilder.ToArray(); + using var engine = ApplicationEngine.Run(script, snapshot, settings: protocolSettings, gas: RestServerSettings.Current.MaxGasInvoke); + results = engine.State == VMState.FAULT ? Array.Empty() : engine.ResultStack.ToArray(); + return engine.State == VMState.HALT; + } + + public static ApplicationEngine InvokeMethod(ProtocolSettings protocolSettings, DataCache snapshot, UInt160 scriptHash, string method, ContractParameter[] args, out byte[] script) + { + using var scriptBuilder = new ScriptBuilder(); + scriptBuilder.EmitDynamicCall(scriptHash, method, CallFlags.ReadOnly, args); + script = scriptBuilder.ToArray(); + using var engine = ApplicationEngine.Run(script, snapshot, settings: protocolSettings, gas: RestServerSettings.Current.MaxGasInvoke); + return engine; + } + + public static ApplicationEngine InvokeScript(ReadOnlyMemory script, Signer[] signers = null, Witness[] witnesses = null) + { + var neosystem = RestServerPlugin.NeoSystem; + var snapshot = neosystem.GetSnapshot(); + Transaction tx = signers == null ? null : new Transaction + { + Version = 0, + Nonce = (uint)Random.Shared.Next(), + ValidUntilBlock = NativeContract.Ledger.CurrentIndex(snapshot) + neosystem.Settings.MaxValidUntilBlockIncrement, + Signers = signers, + Attributes = Array.Empty(), + Script = script, + Witnesses = witnesses + }; + return ApplicationEngine.Run(script, snapshot, tx, settings: neosystem.Settings, gas: RestServerSettings.Current.MaxGasInvoke); + } + } +} diff --git a/src/RestServer/Middleware/RestServerMiddleware.cs b/src/RestServer/Middleware/RestServerMiddleware.cs new file mode 100644 index 000000000..fe9a18c9d --- /dev/null +++ b/src/RestServer/Middleware/RestServerMiddleware.cs @@ -0,0 +1,43 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 Microsoft.AspNetCore.Http; +using System.Reflection; + +namespace Neo.Plugins.RestServer.Middleware +{ + internal class RestServerMiddleware + { + private readonly RequestDelegate _next; + + public RestServerMiddleware(RequestDelegate next) + { + _next = next; + } + + public async Task InvokeAsync(HttpContext context) + { + var request = context.Request; + var response = context.Response; + + SetServerInfomationHeader(response); + + await _next(context); + } + + public static void SetServerInfomationHeader(HttpResponse response) + { + var neoCliAsm = Assembly.GetEntryAssembly().GetName(); + var restServerAsm = Assembly.GetExecutingAssembly().GetName(); + + response.Headers.Server = $"{neoCliAsm.Name}/{neoCliAsm.Version.ToString(3)} {restServerAsm.Name}/{restServerAsm.Version.ToString(3)}"; + } + } +} diff --git a/src/RestServer/Models/Blockchain/AccountDetails.cs b/src/RestServer/Models/Blockchain/AccountDetails.cs new file mode 100644 index 000000000..5acb0ceec --- /dev/null +++ b/src/RestServer/Models/Blockchain/AccountDetails.cs @@ -0,0 +1,33 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 System.Numerics; + +namespace Neo.Plugins.RestServer.Models.Blockchain +{ + internal class AccountDetails + { + /// + /// Scripthash + /// + /// 0xed7cc6f5f2dd842d384f254bc0c2d58fb69a4761 + public UInt160 ScriptHash { get; set; } + /// + /// Wallet address. + /// + /// NNLi44dJNXtDNSBkofB48aTVYtb1zZrNEs + public string Address { get; set; } + /// + /// Balance of the account. + /// + /// 10000000 + public BigInteger Balance { get; set; } + } +} diff --git a/src/RestServer/Models/CountModel.cs b/src/RestServer/Models/CountModel.cs new file mode 100644 index 000000000..afbf09145 --- /dev/null +++ b/src/RestServer/Models/CountModel.cs @@ -0,0 +1,21 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Models +{ + internal class CountModel + { + /// + /// The count of how many objects. + /// + /// 378 + public int Count { get; set; } + } +} diff --git a/src/RestServer/Models/Error/ErrorModel.cs b/src/RestServer/Models/Error/ErrorModel.cs new file mode 100644 index 000000000..bc35543fa --- /dev/null +++ b/src/RestServer/Models/Error/ErrorModel.cs @@ -0,0 +1,32 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Models.Error +{ + internal class ErrorModel + { + /// + /// Error's HResult Code. + /// + /// 1000 + public int Code { get; init; } = 1000; + /// + /// Error's name of the type. + /// + /// GeneralException + public string Name { get; init; } = "GeneralException"; + /// + /// Error's exception message. + /// + /// An error occurred. + /// Could be InnerException message as well, If exists. + public string Message { get; init; } = "An error occurred."; + } +} diff --git a/src/RestServer/Models/Error/ParameterFormatExceptionModel.cs b/src/RestServer/Models/Error/ParameterFormatExceptionModel.cs new file mode 100644 index 000000000..b842123da --- /dev/null +++ b/src/RestServer/Models/Error/ParameterFormatExceptionModel.cs @@ -0,0 +1,28 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Plugins.RestServer.Exceptions; + +namespace Neo.Plugins.RestServer.Models.Error +{ + internal class ParameterFormatExceptionModel : ErrorModel + { + public ParameterFormatExceptionModel() + { + Code = RestErrorCodes.ParameterFormatException; + Name = nameof(RestErrorCodes.ParameterFormatException); + } + + public ParameterFormatExceptionModel(string message) : this() + { + Message = message; + } + } +} diff --git a/src/RestServer/Models/ExecutionEngineModel.cs b/src/RestServer/Models/ExecutionEngineModel.cs new file mode 100644 index 000000000..5710e550f --- /dev/null +++ b/src/RestServer/Models/ExecutionEngineModel.cs @@ -0,0 +1,49 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Plugins.RestServer.Models.Error; +using Neo.SmartContract; +using Neo.VM; +using Neo.VM.Types; + +namespace Neo.Plugins.RestServer.Models +{ + internal class ExecutionEngineModel + { + public long GasConsumed { get; set; } = 0L; + public VMState State { get; set; } = VMState.NONE; + public BlockchainEventModel[] Notifications { get; set; } = System.Array.Empty(); + public StackItem[] ResultStack { get; set; } = System.Array.Empty(); + public ErrorModel FaultException { get; set; } + } + + internal class BlockchainEventModel + { + public UInt160 ScriptHash { get; set; } = new(); + public string EventName { get; set; } = string.Empty; + public StackItem[] State { get; set; } = System.Array.Empty(); + + public static BlockchainEventModel Create(UInt160 scriptHash, string eventName, StackItem[] state) => + new() + { + ScriptHash = scriptHash, + EventName = eventName ?? string.Empty, + State = state, + }; + + public static BlockchainEventModel Create(NotifyEventArgs notifyEventArgs, StackItem[] state) => + new() + { + ScriptHash = notifyEventArgs.ScriptHash, + EventName = notifyEventArgs.EventName, + State = state, + }; + } +} diff --git a/src/RestServer/Models/Ledger/MemoryPoolCountModel.cs b/src/RestServer/Models/Ledger/MemoryPoolCountModel.cs new file mode 100644 index 000000000..d411f0eac --- /dev/null +++ b/src/RestServer/Models/Ledger/MemoryPoolCountModel.cs @@ -0,0 +1,31 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Models.Ledger +{ + internal class MemoryPoolCountModel + { + /// + /// Total count all transactions. + /// + /// 110 + public int Count { get; set; } + /// + /// Count of unverified transactions + /// + /// 10 + public int UnVerifiedCount { get; set; } + /// + /// Count of verified transactions. + /// + /// 100 + public int VerifiedCount { get; set; } + } +} diff --git a/src/RestServer/Models/Node/PluginModel.cs b/src/RestServer/Models/Node/PluginModel.cs new file mode 100644 index 000000000..36d388d17 --- /dev/null +++ b/src/RestServer/Models/Node/PluginModel.cs @@ -0,0 +1,31 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Models.Node +{ + internal class PluginModel + { + /// + /// Name + /// + /// RestServer + public string Name { get; set; } + /// + /// Version + /// + /// 3.5.0 + public string Version { get; set; } + /// + /// Description + /// + /// Enables REST Web Sevices for the node + public string Description { get; set; } + } +} diff --git a/src/RestServer/Models/Node/ProtocolSettingsModel.cs b/src/RestServer/Models/Node/ProtocolSettingsModel.cs new file mode 100644 index 000000000..590ad7f04 --- /dev/null +++ b/src/RestServer/Models/Node/ProtocolSettingsModel.cs @@ -0,0 +1,40 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Cryptography.ECC; + +namespace Neo.Plugins.RestServer.Models.Node +{ + internal class ProtocolSettingsModel + { + /// + /// Network + /// + /// 860833102 + public uint Network { get; set; } + /// + /// AddressVersion + /// + /// 53 + public byte AddressVersion { get; set; } + public int ValidatorsCount { get; set; } + public uint MillisecondsPerBlock { get; set; } + public uint MaxValidUntilBlockIncrement { get; set; } + public uint MaxTransactionsPerBlock { get; set; } + public int MemoryPoolMaxTransactions { get; set; } + public uint MaxTraceableBlocks { get; set; } + public ulong InitialGasDistribution { get; set; } + public IReadOnlyCollection SeedList { get; set; } + public IReadOnlyDictionary NativeUpdateHistory { get; set; } + public IReadOnlyDictionary Hardforks { get; set; } + public IReadOnlyList StandbyValidators { get; set; } + public IReadOnlyList StandbyCommittee { get; set; } + } +} diff --git a/src/RestServer/Models/Node/RemoteNodeModel.cs b/src/RestServer/Models/Node/RemoteNodeModel.cs new file mode 100644 index 000000000..647ec5e79 --- /dev/null +++ b/src/RestServer/Models/Node/RemoteNodeModel.cs @@ -0,0 +1,36 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Models.Node +{ + public class RemoteNodeModel + { + /// + /// Remote peer's ip address. + /// + /// 10.0.0.100 + public string RemoteAddress { get; set; } + /// + /// Remote peer's port number. + /// + /// 20333 + public int RemotePort { get; set; } + /// + /// Remote peer's listening tcp port. + /// + /// 20333 + public int ListenTcpPort { get; set; } + /// + /// Remote peer's last synced block height. + /// + /// 2584158 + public uint LastBlockIndex { get; set; } + } +} diff --git a/src/RestServer/Models/Token/NEP11TokenModel.cs b/src/RestServer/Models/Token/NEP11TokenModel.cs new file mode 100644 index 000000000..a454646ea --- /dev/null +++ b/src/RestServer/Models/Token/NEP11TokenModel.cs @@ -0,0 +1,19 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.VM.Types; + +namespace Neo.Plugins.RestServer.Models.Token +{ + internal class NEP11TokenModel : NEP17TokenModel + { + public IReadOnlyDictionary> Tokens { get; set; } + } +} diff --git a/src/RestServer/Models/Token/NEP17TokenModel.cs b/src/RestServer/Models/Token/NEP17TokenModel.cs new file mode 100644 index 000000000..b769a3eed --- /dev/null +++ b/src/RestServer/Models/Token/NEP17TokenModel.cs @@ -0,0 +1,23 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 System.Numerics; + +namespace Neo.Plugins.RestServer.Models.Token +{ + internal class NEP17TokenModel + { + public string Name { get; set; } + public UInt160 ScriptHash { get; set; } + public string Symbol { get; set; } + public byte Decimals { get; set; } + public BigInteger TotalSupply { get; set; } + } +} diff --git a/src/RestServer/Models/Token/TokenBalanceModel.cs b/src/RestServer/Models/Token/TokenBalanceModel.cs new file mode 100644 index 000000000..a3a10e7d0 --- /dev/null +++ b/src/RestServer/Models/Token/TokenBalanceModel.cs @@ -0,0 +1,24 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 System.Numerics; + +namespace Neo.Plugins.RestServer.Models.Token +{ + public class TokenBalanceModel + { + public string Name { get; set; } + public UInt160 ScriptHash { get; set; } + public string Symbol { get; set; } + public byte Decimals { get; set; } + public BigInteger Balance { get; set; } + public BigInteger TotalSupply { get; set; } + } +} diff --git a/src/RestServer/Models/Utils/UtilsAddressIsValidModel.cs b/src/RestServer/Models/Utils/UtilsAddressIsValidModel.cs new file mode 100644 index 000000000..7295f9a13 --- /dev/null +++ b/src/RestServer/Models/Utils/UtilsAddressIsValidModel.cs @@ -0,0 +1,11 @@ +namespace Neo.Plugins.RestServer.Models.Utils +{ + internal class UtilsAddressIsValidModel : UtilsAddressModel + { + /// + /// Indicates if address can be converted to ScriptHash or Neo Address. + /// + /// true + public bool IsValid { get; set; } + } +} diff --git a/src/RestServer/Models/Utils/UtilsAddressModel.cs b/src/RestServer/Models/Utils/UtilsAddressModel.cs new file mode 100644 index 000000000..9b9694159 --- /dev/null +++ b/src/RestServer/Models/Utils/UtilsAddressModel.cs @@ -0,0 +1,21 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Models.Utils +{ + internal class UtilsAddressModel + { + /// + /// Wallet address that was exported. + /// + /// NNLi44dJNXtDNSBkofB48aTVYtb1zZrNEs + public virtual string Address { get; set; } + } +} diff --git a/src/RestServer/Models/Utils/UtilsScriptHashModel.cs b/src/RestServer/Models/Utils/UtilsScriptHashModel.cs new file mode 100644 index 000000000..5a24603ba --- /dev/null +++ b/src/RestServer/Models/Utils/UtilsScriptHashModel.cs @@ -0,0 +1,21 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Models.Utils +{ + internal class UtilsScriptHashModel + { + /// + /// Scripthash of the wallet account exported. + /// + /// 0xed7cc6f5f2dd842d384f254bc0c2d58fb69a4761 + public UInt160 ScriptHash { get; set; } + } +} diff --git a/src/RestServer/Models/Wallet/WalletAccountBalanceModel.cs b/src/RestServer/Models/Wallet/WalletAccountBalanceModel.cs new file mode 100644 index 000000000..b920c8466 --- /dev/null +++ b/src/RestServer/Models/Wallet/WalletAccountBalanceModel.cs @@ -0,0 +1,26 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 System.Numerics; + +namespace Neo.Plugins.RestServer.Models.Wallet +{ + /// + /// Wallet account balance object. + /// + internal class WalletAccountBalanceModel + { + /// + /// Balance of the account. + /// + /// 10000000 + public BigInteger Balance { get; set; } + } +} diff --git a/src/RestServer/Models/Wallet/WalletAddressModel.cs b/src/RestServer/Models/Wallet/WalletAddressModel.cs new file mode 100644 index 000000000..d2d0184bd --- /dev/null +++ b/src/RestServer/Models/Wallet/WalletAddressModel.cs @@ -0,0 +1,51 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Cryptography.ECC; + +namespace Neo.Plugins.RestServer.Models.Wallet +{ + /// + /// Wallet address object. + /// + public class WalletAddressModel + { + /// + /// Wallet address that was exported. + /// + /// NNLi44dJNXtDNSBkofB48aTVYtb1zZrNEs + public string Address { get; set; } + /// + /// Scripthash of the wallet account exported. + /// + /// 0xed7cc6f5f2dd842d384f254bc0c2d58fb69a4761 + public UInt160 ScriptHash { get; set; } + /// + /// Public key of the wallet address. + /// + /// 03cdb067d930fd5adaa6c68545016044aaddec64ba39e548250eaea551172e535c + public ECPoint Publickey { get; set; } + /// + /// has a private key or not. + /// + /// true + public bool HasKey { get; set; } + /// + /// The display name for the address. + /// + /// Default Account + public string Label { get; set; } + /// + /// is the address a WatchOnly address. + /// + /// false + public bool WatchOnly { get; set; } + } +} diff --git a/src/RestServer/Models/Wallet/WalletAssetModel.cs b/src/RestServer/Models/Wallet/WalletAssetModel.cs new file mode 100644 index 000000000..9d0766e2a --- /dev/null +++ b/src/RestServer/Models/Wallet/WalletAssetModel.cs @@ -0,0 +1,54 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Cryptography.ECC; +using System.Numerics; + +namespace Neo.Plugins.RestServer.Models.Wallet +{ + public class WalletAssetModel + { + /// + /// Wallet address that was exported. + /// + /// NNLi44dJNXtDNSBkofB48aTVYtb1zZrNEs + public string Address { get; set; } + /// + /// Scripthash of the wallet account exported. + /// + /// 0xed7cc6f5f2dd842d384f254bc0c2d58fb69a4761 + public UInt160 ScriptHash { get; set; } + /// + /// Public key of the wallet address. + /// + /// 03cdb067d930fd5adaa6c68545016044aaddec64ba39e548250eaea551172e535c + public ECPoint PublicKey { get; set; } + /// + /// Neo amount. + /// + /// 1 + public BigInteger Neo { get; set; } + /// + /// Neo ScriptHash Address. + /// + /// 0xef4073a0f2b305a38ec4050e4d3d28bc40ea63f5 + public UInt160 NeoHash { get; set; } + /// + /// Gas amount. + /// + /// 10000000 + public BigInteger Gas { get; set; } + /// + /// Gas ScriptHash Address. + /// + /// 0xd2a4cff31913016155e38e474a2c06d08be276cf + public UInt160 GasHash { get; set; } + } +} diff --git a/src/RestServer/Models/Wallet/WalletChangePasswordModel.cs b/src/RestServer/Models/Wallet/WalletChangePasswordModel.cs new file mode 100644 index 000000000..d0aa6b034 --- /dev/null +++ b/src/RestServer/Models/Wallet/WalletChangePasswordModel.cs @@ -0,0 +1,40 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 System.ComponentModel.DataAnnotations; + +namespace Neo.Plugins.RestServer.Models.Wallet +{ + public class WalletChangePasswordModel + { + /// + /// Current password. + /// + /// Password1! + [Required(AllowEmptyStrings = false)] + public string OldPassword { get; set; } + /// + /// New Password. + /// + /// HelloWorld1! + [Required(AllowEmptyStrings = false)] + public string NewPassword { get; set; } + /// + /// Should create a backup file. + /// + /// false + public bool CreateBackupFile { get; set; } + /// + /// if backup file exists overwrite it. + /// + /// false + public bool OverwriteIfBackupFileExists { get; set; } + } +} diff --git a/src/RestServer/Models/Wallet/WalletCreateAccountModel.cs b/src/RestServer/Models/Wallet/WalletCreateAccountModel.cs new file mode 100644 index 000000000..5e3f1f36b --- /dev/null +++ b/src/RestServer/Models/Wallet/WalletCreateAccountModel.cs @@ -0,0 +1,24 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Models.Wallet +{ + /// + /// Create account object. + /// + public class WalletCreateAccountModel + { + /// + /// Private key of the address you want to create. Can be null or empty. + /// + /// CHeABTw3Q5SkjWharPAhgE+p+rGVN9FhlO4hXoJZQqA= + public byte[] PrivateKey { get; set; } + } +} diff --git a/src/RestServer/Models/Wallet/WalletCreateModel.cs b/src/RestServer/Models/Wallet/WalletCreateModel.cs new file mode 100644 index 000000000..82c0cdebd --- /dev/null +++ b/src/RestServer/Models/Wallet/WalletCreateModel.cs @@ -0,0 +1,45 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 System.ComponentModel.DataAnnotations; + +namespace Neo.Plugins.RestServer.Models.Wallet +{ + /// + /// Wallet create object. + /// + public class WalletCreateModel + { + /// + /// Account display name + /// + /// Default Account + /// Can be null. + public string Name { get; set; } + /// + /// Path of the wallet file relative to the neo-cli path. + /// + /// ./wallets/mywallet.json + [Required(AllowEmptyStrings = false)] + public string Path { get; set; } + /// + /// Representation of the private. + /// + /// L3tgppXLgdaeqSGSFw1Go3skBiy8vQAM7YMXvTHsKQtE16PBncSU + /// Can be null or empty. + public string Wif { get; set; } + /// + /// Password to open the wallet file. + /// + /// Password1! + [Required(AllowEmptyStrings = false)] + public string Password { get; set; } + } +} diff --git a/src/RestServer/Models/Wallet/WalletExportKeyModel.cs b/src/RestServer/Models/Wallet/WalletExportKeyModel.cs new file mode 100644 index 000000000..8d18e88b7 --- /dev/null +++ b/src/RestServer/Models/Wallet/WalletExportKeyModel.cs @@ -0,0 +1,34 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Models.Wallet +{ + /// + /// Export key wallet object + /// + internal class WalletExportKeyModel + { + /// + /// Scripthash of the wallet account exported. + /// + /// 0xed7cc6f5f2dd842d384f254bc0c2d58fb69a4761 + public UInt160 ScriptHash { get; set; } + /// + /// Wallet address that was exported. + /// + /// NNLi44dJNXtDNSBkofB48aTVYtb1zZrNEs + public string Address { get; set; } + /// + /// Representation of the private. + /// + /// L3tgppXLgdaeqSGSFw1Go3skBiy8vQAM7YMXvTHsKQtE16PBncSU + public string Wif { get; set; } + } +} diff --git a/src/RestServer/Models/Wallet/WalletImportKey.cs b/src/RestServer/Models/Wallet/WalletImportKey.cs new file mode 100644 index 000000000..2dfe03c84 --- /dev/null +++ b/src/RestServer/Models/Wallet/WalletImportKey.cs @@ -0,0 +1,27 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 System.ComponentModel.DataAnnotations; + +namespace Neo.Plugins.RestServer.Models.Wallet +{ + /// + /// Wallet import key object. + /// + public class WalletImportKey + { + /// + /// Representation of the private. + /// + /// L3tgppXLgdaeqSGSFw1Go3skBiy8vQAM7YMXvTHsKQtE16PBncSU + [Required(AllowEmptyStrings = false)] + public string Wif { get; set; } + } +} diff --git a/src/RestServer/Models/Wallet/WalletImportMultiSigAddressModel.cs b/src/RestServer/Models/Wallet/WalletImportMultiSigAddressModel.cs new file mode 100644 index 000000000..e22fe944c --- /dev/null +++ b/src/RestServer/Models/Wallet/WalletImportMultiSigAddressModel.cs @@ -0,0 +1,32 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Cryptography.ECC; +using System.ComponentModel.DataAnnotations; + +namespace Neo.Plugins.RestServer.Models.Wallet +{ + /// + /// Import Multi-Signature Address Object. + /// + public class WalletImportMultiSigAddressModel + { + /// + /// Minimum required signatures to sign. + /// + /// 2 + public ushort RequiredSignatures { get; set; } + /// + /// Array of public keys of the addresses. + /// + [Required] + public ECPoint[] PublicKeys { get; set; } + } +} diff --git a/src/RestServer/Models/Wallet/WalletKeyModel.cs b/src/RestServer/Models/Wallet/WalletKeyModel.cs new file mode 100644 index 000000000..3d8f1f176 --- /dev/null +++ b/src/RestServer/Models/Wallet/WalletKeyModel.cs @@ -0,0 +1,33 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Cryptography.ECC; + +namespace Neo.Plugins.RestServer.Models.Wallet +{ + public class WalletKeyModel + { + /// + /// Wallet address that was exported. + /// + /// NNLi44dJNXtDNSBkofB48aTVYtb1zZrNEs + public string Address { get; set; } + /// + /// Scripthash of the wallet account exported. + /// + /// 0xed7cc6f5f2dd842d384f254bc0c2d58fb69a4761 + public UInt160 ScriptHash { get; set; } + /// + /// Public key of the wallet address. + /// + /// 03cdb067d930fd5adaa6c68545016044aaddec64ba39e548250eaea551172e535c + public ECPoint PublicKey { get; set; } + } +} diff --git a/src/RestServer/Models/Wallet/WalletMultiSignContractModel.cs b/src/RestServer/Models/Wallet/WalletMultiSignContractModel.cs new file mode 100644 index 000000000..d04606de0 --- /dev/null +++ b/src/RestServer/Models/Wallet/WalletMultiSignContractModel.cs @@ -0,0 +1,34 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Models.Wallet +{ + /// + /// Multi-Signature Contract Object. + /// + internal class WalletMultiSignContractModel + { + /// + /// Wallet address that was exported. + /// + /// NNLi44dJNXtDNSBkofB48aTVYtb1zZrNEs + public string Address { get; set; } + /// + /// Scripthash of the wallet account exported. + /// + /// 0xed7cc6f5f2dd842d384f254bc0c2d58fb69a4761 + public UInt160 ScriptHash { get; set; } + /// + /// Script that used to create the address + /// + /// CHeABTw3Q5SkjWharPAhgE+p+rGVN9FhlO4hXoJZQqA= + public byte[] Script { get; set; } + } +} diff --git a/src/RestServer/Models/Wallet/WalletOpenModel.cs b/src/RestServer/Models/Wallet/WalletOpenModel.cs new file mode 100644 index 000000000..34ebe6bbc --- /dev/null +++ b/src/RestServer/Models/Wallet/WalletOpenModel.cs @@ -0,0 +1,33 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 System.ComponentModel.DataAnnotations; + +namespace Neo.Plugins.RestServer.Models.Wallet +{ + /// + /// Open wallet request object. + /// + public class WalletOpenModel + { + /// + /// Path of the wallet file relative to the neo-cli path. + /// + /// ./wallets/mywallet.json + [Required(AllowEmptyStrings = false)] + public string Path { get; set; } + /// + /// Password to open the wallet file. + /// + /// Password1! + [Required(AllowEmptyStrings = false)] + public string Password { get; set; } + } +} diff --git a/src/RestServer/Models/Wallet/WalletSendModel.cs b/src/RestServer/Models/Wallet/WalletSendModel.cs new file mode 100644 index 000000000..d2c031520 --- /dev/null +++ b/src/RestServer/Models/Wallet/WalletSendModel.cs @@ -0,0 +1,58 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 System.ComponentModel.DataAnnotations; +using System.Numerics; + +namespace Neo.Plugins.RestServer.Models.Wallet +{ + /// + /// Wallet send object. + /// + public class WalletSendModel + { + /// + /// Asset Id + /// + /// 0xef4073a0f2b305a38ec4050e4d3d28bc40ea63f5 + [Required] + public UInt160 AssetId { get; set; } + /// + /// ScriptHash of the address in the wallet to send from. + /// + /// 0xed7cc6f5f2dd842d384f254bc0c2d58fb69a4761 + [Required] + public UInt160 From { get; set; } + /// + /// ScriptHash of the address in the wallet to send too. + /// + /// 0xed7cc6f5f2dd842d384f254bc0c2d58fb69a4761 + [Required] + public UInt160 To { get; set; } + /// + /// Amount + /// + /// 1 + /// Not user representation. + [Required] + public BigInteger Amount { get; set; } + /// + /// Data you would like to send. + /// + /// can be null or empty. + /// SGVsbG8gV29ybGQ= + public byte[] Data { get; set; } + /// + /// An array of the signer that will be signing the transaction. + /// + /// Can be null + public UInt160[] Signers { get; set; } + } +} diff --git a/src/RestServer/Models/Wallet/WalletSessionModel.cs b/src/RestServer/Models/Wallet/WalletSessionModel.cs new file mode 100644 index 000000000..ef226f8d4 --- /dev/null +++ b/src/RestServer/Models/Wallet/WalletSessionModel.cs @@ -0,0 +1,24 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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. + +namespace Neo.Plugins.RestServer.Models.Wallet +{ + /// + /// Open/Created wallet session object. + /// + public class WalletSessionModel + { + /// + /// Session id for an open/created wallet. + /// + /// 066843daf5ce45aba803587780998cdb + public Guid SessionId { get; set; } + } +} diff --git a/src/RestServer/Models/Wallet/WalletTransactionScriptModel.cs b/src/RestServer/Models/Wallet/WalletTransactionScriptModel.cs new file mode 100644 index 000000000..833563cb6 --- /dev/null +++ b/src/RestServer/Models/Wallet/WalletTransactionScriptModel.cs @@ -0,0 +1,35 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 System.ComponentModel.DataAnnotations; + +namespace Neo.Plugins.RestServer.Models.Wallet +{ + public class WalletTransactionScriptModel + { + /// + /// Script to use. + /// + /// CHeABTw3Q5SkjWharPAhgE+p+rGVN9FhlO4hXoJZQqA= + [Required] + public byte[] Script { get; set; } + /// + /// ScriptHash of the address in the wallet to send from. + /// + /// 0xed7cc6f5f2dd842d384f254bc0c2d58fb69a4761 + [Required] + public UInt160 From { get; set; } + /// + /// An array of the signer that will be signing the transaction. + /// + /// Can be null + public UInt160[] Signers { get; set; } + } +} diff --git a/src/RestServer/Newtonsoft/Json/BigDecimalJsonConverter.cs b/src/RestServer/Newtonsoft/Json/BigDecimalJsonConverter.cs new file mode 100644 index 000000000..20d8be78a --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/BigDecimalJsonConverter.cs @@ -0,0 +1,48 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System.Numerics; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json +{ + public class BigDecimalJsonConverter : JsonConverter + { + public override bool CanRead => true; + public override bool CanWrite => true; + + public override BigDecimal ReadJson(JsonReader reader, Type objectType, BigDecimal existingValue, bool hasExistingValue, JsonSerializer serializer) + { + var token = JToken.ReadFrom(reader); + if (token.Type == JTokenType.Object) + { + var valueProp = ((JObject)token).Properties().SingleOrDefault(p => p.Name.Equals("value", StringComparison.InvariantCultureIgnoreCase)); + var decimalsProp = ((JObject)token).Properties().SingleOrDefault(p => p.Name.Equals("decimals", StringComparison.InvariantCultureIgnoreCase)); + + if (valueProp != null && decimalsProp != null) + { + return new BigDecimal(valueProp.ToObject(), decimalsProp.ToObject()); + } + } + throw new FormatException(); + } + + public override void WriteJson(JsonWriter writer, BigDecimal value, JsonSerializer serializer) + { + var o = JToken.FromObject(new + { + value.Value, + value.Decimals, + }, serializer); + o.WriteTo(writer); + } + } +} diff --git a/src/RestServer/Newtonsoft/Json/BlockHeaderJsonConverter.cs b/src/RestServer/Newtonsoft/Json/BlockHeaderJsonConverter.cs new file mode 100644 index 000000000..5d30b5efe --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/BlockHeaderJsonConverter.cs @@ -0,0 +1,32 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Network.P2P.Payloads; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json +{ + public class BlockHeaderJsonConverter : JsonConverter
+ { + public override bool CanRead => false; + public override bool CanWrite => true; + + public override Header ReadJson(JsonReader reader, Type objectType, Header existingValue, bool hasExistingValue, JsonSerializer serializer) + { + throw new NotImplementedException(); + } + + public override void WriteJson(JsonWriter writer, Header value, JsonSerializer serializer) + { + var j = RestServerUtility.BlockHeaderToJToken(value, serializer); + j.WriteTo(writer); + } + } +} diff --git a/src/RestServer/Newtonsoft/Json/BlockJsonConverter.cs b/src/RestServer/Newtonsoft/Json/BlockJsonConverter.cs new file mode 100644 index 000000000..113053af7 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/BlockJsonConverter.cs @@ -0,0 +1,30 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Network.P2P.Payloads; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json; + +public class BlockJsonConverter : JsonConverter +{ + public override bool CanRead => false; + + public override bool CanWrite => true; + + public override Block ReadJson(JsonReader reader, Type objectType, Block existingValue, bool hasExistingValue, JsonSerializer serializer) => + throw new NotImplementedException(); + + public override void WriteJson(JsonWriter writer, Block value, JsonSerializer serializer) + { + var j = RestServerUtility.BlockToJToken(value, serializer); + j.WriteTo(writer); + } +} diff --git a/src/RestServer/Newtonsoft/Json/ContractAbiJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractAbiJsonConverter.cs new file mode 100644 index 000000000..47ba189df --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/ContractAbiJsonConverter.cs @@ -0,0 +1,28 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.SmartContract.Manifest; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json; + +public class ContractAbiJsonConverter : JsonConverter +{ + public override bool CanRead => false; + + public override bool CanWrite => true; + + public override ContractAbi ReadJson(JsonReader reader, Type objectType, ContractAbi existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); + public override void WriteJson(JsonWriter writer, ContractAbi value, JsonSerializer serializer) + { + var j = RestServerUtility.ContractAbiToJToken(value, serializer); + j.WriteTo(writer); + } +} diff --git a/src/RestServer/Newtonsoft/Json/ContractEventDescriptorJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractEventDescriptorJsonConverter.cs new file mode 100644 index 000000000..510664275 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/ContractEventDescriptorJsonConverter.cs @@ -0,0 +1,28 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.SmartContract.Manifest; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json; + +public class ContractEventDescriptorJsonConverter : JsonConverter +{ + public override bool CanRead => false; + + public override bool CanWrite => true; + + public override ContractEventDescriptor ReadJson(JsonReader reader, Type objectType, ContractEventDescriptor existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); + public override void WriteJson(JsonWriter writer, ContractEventDescriptor value, JsonSerializer serializer) + { + var j = RestServerUtility.ContractEventToJToken(value, serializer); + j.WriteTo(writer); + } +} diff --git a/src/RestServer/Newtonsoft/Json/ContractGroupJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractGroupJsonConverter.cs new file mode 100644 index 000000000..0e58fa010 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/ContractGroupJsonConverter.cs @@ -0,0 +1,28 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.SmartContract.Manifest; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json; + +public class ContractGroupJsonConverter : JsonConverter +{ + public override bool CanRead => false; + + public override bool CanWrite => true; + + public override ContractGroup ReadJson(JsonReader reader, Type objectType, ContractGroup existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); + public override void WriteJson(JsonWriter writer, ContractGroup value, JsonSerializer serializer) + { + var j = RestServerUtility.ContractGroupToJToken(value, serializer); + j.WriteTo(writer); + } +} diff --git a/src/RestServer/Newtonsoft/Json/ContractJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractJsonConverter.cs new file mode 100644 index 000000000..0a55e26d7 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/ContractJsonConverter.cs @@ -0,0 +1,28 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.SmartContract; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json; + +public class ContractJsonConverter : JsonConverter +{ + public override bool CanRead => false; + + public override bool CanWrite => true; + + public override ContractState ReadJson(JsonReader reader, Type objectType, ContractState existingValue, bool hasExistingValue, global::Newtonsoft.Json.JsonSerializer serializer) => throw new NotImplementedException(); + public override void WriteJson(JsonWriter writer, ContractState value, global::Newtonsoft.Json.JsonSerializer serializer) + { + var j = RestServerUtility.ContractStateToJToken(value, serializer); + j.WriteTo(writer); + } +} diff --git a/src/RestServer/Newtonsoft/Json/ContractManifestJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractManifestJsonConverter.cs new file mode 100644 index 000000000..ae602e755 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/ContractManifestJsonConverter.cs @@ -0,0 +1,28 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.SmartContract.Manifest; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json; + +public class ContractManifestJsonConverter : JsonConverter +{ + public override bool CanRead => false; + + public override bool CanWrite => true; + + public override ContractManifest ReadJson(JsonReader reader, Type objectType, ContractManifest existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); + public override void WriteJson(JsonWriter writer, ContractManifest value, JsonSerializer serializer) + { + var j = RestServerUtility.ContractManifestToJToken(value, serializer); + j.WriteTo(writer); + } +} diff --git a/src/RestServer/Newtonsoft/Json/ContractMethodJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractMethodJsonConverter.cs new file mode 100644 index 000000000..2d7155b0d --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/ContractMethodJsonConverter.cs @@ -0,0 +1,28 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.SmartContract.Manifest; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json; + +public class ContractMethodJsonConverter : JsonConverter +{ + public override bool CanRead => false; + + public override bool CanWrite => true; + + public override ContractMethodDescriptor ReadJson(JsonReader reader, Type objectType, ContractMethodDescriptor existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); + public override void WriteJson(JsonWriter writer, ContractMethodDescriptor value, JsonSerializer serializer) + { + var j = RestServerUtility.ContractMethodToJToken(value, serializer); + j.WriteTo(writer); + } +} diff --git a/src/RestServer/Newtonsoft/Json/ContractMethodParametersJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractMethodParametersJsonConverter.cs new file mode 100644 index 000000000..3b80a30c0 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/ContractMethodParametersJsonConverter.cs @@ -0,0 +1,27 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.SmartContract.Manifest; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json; +public class ContractMethodParametersJsonConverter : JsonConverter +{ + public override bool CanRead => base.CanRead; + + public override bool CanWrite => base.CanWrite; + + public override ContractParameterDefinition ReadJson(JsonReader reader, Type objectType, ContractParameterDefinition existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); + public override void WriteJson(JsonWriter writer, ContractParameterDefinition value, JsonSerializer serializer) + { + var j = RestServerUtility.ContractMethodParameterToJToken(value, serializer); + j.WriteTo(writer); + } +} diff --git a/src/RestServer/Newtonsoft/Json/ContractParameterDefinitionJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractParameterDefinitionJsonConverter.cs new file mode 100644 index 000000000..5a99c9812 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/ContractParameterDefinitionJsonConverter.cs @@ -0,0 +1,28 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.SmartContract.Manifest; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json; + +public class ContractParameterDefinitionJsonConverter : JsonConverter +{ + public override bool CanRead => false; + + public override bool CanWrite => true; + + public override ContractParameterDefinition ReadJson(JsonReader reader, Type objectType, ContractParameterDefinition existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); + public override void WriteJson(JsonWriter writer, ContractParameterDefinition value, JsonSerializer serializer) + { + var j = RestServerUtility.ContractParameterDefinitionToJToken(value, serializer); + j.WriteTo(writer); + } +} diff --git a/src/RestServer/Newtonsoft/Json/ContractParameterJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractParameterJsonConverter.cs new file mode 100644 index 000000000..d32b45242 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/ContractParameterJsonConverter.cs @@ -0,0 +1,33 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.SmartContract; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json +{ + public class ContractParameterJsonConverter : JsonConverter + { + public override bool CanRead => true; + public override bool CanWrite => false; + + public override ContractParameter ReadJson(JsonReader reader, Type objectType, ContractParameter existingValue, bool hasExistingValue, global::Newtonsoft.Json.JsonSerializer serializer) + { + var token = JToken.ReadFrom(reader); + return RestServerUtility.ContractParameterFromJToken(token); + } + + public override void WriteJson(JsonWriter writer, ContractParameter value, global::Newtonsoft.Json.JsonSerializer serializer) + { + throw new NotImplementedException(); + } + } +} diff --git a/src/RestServer/Newtonsoft/Json/ContractPermissionDescriptorJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractPermissionDescriptorJsonConverter.cs new file mode 100644 index 000000000..8c85ee764 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/ContractPermissionDescriptorJsonConverter.cs @@ -0,0 +1,28 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.SmartContract.Manifest; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json; + +public class ContractPermissionDescriptorJsonConverter : JsonConverter +{ + public override bool CanRead => false; + + public override bool CanWrite => true; + + public override ContractPermissionDescriptor ReadJson(JsonReader reader, Type objectType, ContractPermissionDescriptor existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); + public override void WriteJson(JsonWriter writer, ContractPermissionDescriptor value, JsonSerializer serializer) + { + var j = RestServerUtility.ContractPermissionDescriptorToJToken(value, serializer); + j.WriteTo(writer); + } +} diff --git a/src/RestServer/Newtonsoft/Json/ContractPermissionJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractPermissionJsonConverter.cs new file mode 100644 index 000000000..c4747f065 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/ContractPermissionJsonConverter.cs @@ -0,0 +1,28 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.SmartContract.Manifest; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json; + +internal class ContractPermissionJsonConverter : JsonConverter +{ + public override bool CanRead => false; + + public override bool CanWrite => true; + + public override ContractPermission ReadJson(JsonReader reader, Type objectType, ContractPermission existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); + public override void WriteJson(JsonWriter writer, ContractPermission value, JsonSerializer serializer) + { + var j = RestServerUtility.ContractPermissionToJToken(value, serializer); + j.WriteTo(writer); + } +} diff --git a/src/RestServer/Newtonsoft/Json/ECPointJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ECPointJsonConverter.cs new file mode 100644 index 000000000..99b514b13 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/ECPointJsonConverter.cs @@ -0,0 +1,37 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Cryptography.ECC; +using Neo.Plugins.RestServer.Exceptions; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json +{ + public class ECPointJsonConverter : JsonConverter + { + public override ECPoint ReadJson(JsonReader reader, Type objectType, ECPoint existingValue, bool hasExistingValue, JsonSerializer serializer) + { + var value = reader?.Value.ToString(); + try + { + return ECPoint.Parse(value, ECCurve.Secp256r1); + } + catch (FormatException) + { + throw new UInt256FormatException($"{value} is invalid."); + } + } + + public override void WriteJson(JsonWriter writer, ECPoint value, JsonSerializer serializer) + { + writer.WriteValue(value.ToString()); + } + } +} diff --git a/src/RestServer/Newtonsoft/Json/GuidJsonConverter.cs b/src/RestServer/Newtonsoft/Json/GuidJsonConverter.cs new file mode 100644 index 000000000..024a00f77 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/GuidJsonConverter.cs @@ -0,0 +1,27 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json +{ + internal class GuidJsonConverter : JsonConverter + { + public override Guid ReadJson(JsonReader reader, Type objectType, Guid existingValue, bool hasExistingValue, JsonSerializer serializer) + { + return Guid.Parse(reader.Value?.ToString()); + } + + public override void WriteJson(JsonWriter writer, Guid value, JsonSerializer serializer) + { + writer.WriteValue(value.ToString("n")); + } + } +} diff --git a/src/RestServer/Newtonsoft/Json/InteropInterfaceJsonConverter.cs b/src/RestServer/Newtonsoft/Json/InteropInterfaceJsonConverter.cs new file mode 100644 index 000000000..8727577fc --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/InteropInterfaceJsonConverter.cs @@ -0,0 +1,31 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.VM.Types; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json +{ + public class InteropInterfaceJsonConverter : JsonConverter + { + public override InteropInterface ReadJson(JsonReader reader, Type objectType, InteropInterface existingValue, bool hasExistingValue, JsonSerializer serializer) + { + var t = JToken.Load(reader); + return RestServerUtility.StackItemFromJToken(t) as InteropInterface; + } + + public override void WriteJson(JsonWriter writer, InteropInterface value, JsonSerializer serializer) + { + var t = RestServerUtility.StackItemToJToken(value, null, serializer); + t.WriteTo(writer); + } + } +} diff --git a/src/RestServer/Newtonsoft/Json/MethodTokenJsonConverter.cs b/src/RestServer/Newtonsoft/Json/MethodTokenJsonConverter.cs new file mode 100644 index 000000000..7503d3a67 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/MethodTokenJsonConverter.cs @@ -0,0 +1,28 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.SmartContract; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json; + +public class MethodTokenJsonConverter : JsonConverter +{ + public override bool CanRead => false; + + public override bool CanWrite => true; + + public override MethodToken ReadJson(JsonReader reader, Type objectType, MethodToken existingValue, bool hasExistingValue, global::Newtonsoft.Json.JsonSerializer serializer) => throw new NotImplementedException(); + public override void WriteJson(JsonWriter writer, MethodToken value, global::Newtonsoft.Json.JsonSerializer serializer) + { + var j = RestServerUtility.MethodTokenToJToken(value, serializer); + j.WriteTo(writer); + } +} diff --git a/src/RestServer/Newtonsoft/Json/NefFileJsonConverter.cs b/src/RestServer/Newtonsoft/Json/NefFileJsonConverter.cs new file mode 100644 index 000000000..d4e254d7e --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/NefFileJsonConverter.cs @@ -0,0 +1,24 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.SmartContract; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json; + +public class NefFileJsonConverter : JsonConverter +{ + public override NefFile ReadJson(JsonReader reader, Type objectType, NefFile existingValue, bool hasExistingValue, global::Newtonsoft.Json.JsonSerializer serializer) => throw new NotImplementedException(); + public override void WriteJson(JsonWriter writer, NefFile value, global::Newtonsoft.Json.JsonSerializer serializer) + { + var j = RestServerUtility.ContractNefFileToJToken(value, serializer); + j.WriteTo(writer); + } +} diff --git a/src/RestServer/Newtonsoft/Json/ReadOnlyMemoryBytesJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ReadOnlyMemoryBytesJsonConverter.cs new file mode 100644 index 000000000..99ea3d132 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/ReadOnlyMemoryBytesJsonConverter.cs @@ -0,0 +1,29 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json +{ + public class ReadOnlyMemoryBytesJsonConverter : JsonConverter> + { + public override ReadOnlyMemory ReadJson(JsonReader reader, Type objectType, ReadOnlyMemory existingValue, bool hasExistingValue, JsonSerializer serializer) + { + var o = JToken.Load(reader); + return Convert.FromBase64String(o.ToObject()); + } + + public override void WriteJson(JsonWriter writer, ReadOnlyMemory value, JsonSerializer serializer) + { + writer.WriteValue(Convert.ToBase64String(value.Span)); + } + } +} diff --git a/src/RestServer/Newtonsoft/Json/SignerJsonConverter.cs b/src/RestServer/Newtonsoft/Json/SignerJsonConverter.cs new file mode 100644 index 000000000..50d596010 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/SignerJsonConverter.cs @@ -0,0 +1,29 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Network.P2P.Payloads; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json; + +public class SignerJsonConverter : JsonConverter +{ + public override bool CanRead => false; + + public override bool CanWrite => true; + + public override Signer ReadJson(JsonReader reader, Type objectType, Signer existingValue, bool hasExistingValue, JsonSerializer serializer) => + throw new NotImplementedException(); + + public override void WriteJson(JsonWriter writer, Signer value, JsonSerializer serializer) + { + var j = RestServerUtility.SignerToJToken(value, serializer); + j.WriteTo(writer); + } +} diff --git a/src/RestServer/Newtonsoft/Json/StackItemJsonConverter.cs b/src/RestServer/Newtonsoft/Json/StackItemJsonConverter.cs new file mode 100644 index 000000000..dae151cb8 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/StackItemJsonConverter.cs @@ -0,0 +1,33 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.VM.Types; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json +{ + public class StackItemJsonConverter : JsonConverter + { + public override StackItem ReadJson(JsonReader reader, Type objectType, StackItem existingValue, bool hasExistingValue, JsonSerializer serializer) + { + var t = JObject.Load(reader); + return RestServerUtility.StackItemFromJToken(t); + } + + public override void WriteJson(JsonWriter writer, StackItem value, JsonSerializer serializer) + { + var t = RestServerUtility.StackItemToJToken(value, null, serializer); + t.WriteTo(writer); + } + + + } +} diff --git a/src/RestServer/Newtonsoft/Json/TransactionAttributeJsonConverter.cs b/src/RestServer/Newtonsoft/Json/TransactionAttributeJsonConverter.cs new file mode 100644 index 000000000..4bc950fc9 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/TransactionAttributeJsonConverter.cs @@ -0,0 +1,28 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Network.P2P.Payloads; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json; + +public class TransactionAttributeJsonConverter : JsonConverter +{ + public override bool CanRead => false; + + public override bool CanWrite => true; + + public override TransactionAttribute ReadJson(JsonReader reader, Type objectType, TransactionAttribute existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); + public override void WriteJson(JsonWriter writer, TransactionAttribute value, JsonSerializer serializer) + { + var j = RestServerUtility.TransactionAttributeToJToken(value, serializer); + j.WriteTo(writer); + } +} diff --git a/src/RestServer/Newtonsoft/Json/TransactionJsonConverter.cs b/src/RestServer/Newtonsoft/Json/TransactionJsonConverter.cs new file mode 100644 index 000000000..18080fe6a --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/TransactionJsonConverter.cs @@ -0,0 +1,28 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Network.P2P.Payloads; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json; + +public class TransactionJsonConverter : JsonConverter +{ + public override bool CanRead => false; + + public override bool CanWrite => true; + + public override Transaction ReadJson(JsonReader reader, Type objectType, Transaction existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); + public override void WriteJson(JsonWriter writer, Transaction value, JsonSerializer serializer) + { + var j = RestServerUtility.TransactionToJToken(value, serializer); + j.WriteTo(writer); + } +} diff --git a/src/RestServer/Newtonsoft/Json/UInt160JsonConverter.cs b/src/RestServer/Newtonsoft/Json/UInt160JsonConverter.cs new file mode 100644 index 000000000..581258efd --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/UInt160JsonConverter.cs @@ -0,0 +1,39 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Plugins.RestServer.Exceptions; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json +{ + public class UInt160JsonConverter : JsonConverter + { + public override bool CanRead => true; + public override bool CanWrite => true; + + public override UInt160 ReadJson(JsonReader reader, Type objectType, UInt160 existingValue, bool hasExistingValue, JsonSerializer serializer) + { + var value = reader.Value?.ToString(); + try + { + return RestServerUtility.ConvertToScriptHash(value, RestServerPlugin.NeoSystem.Settings); + } + catch (FormatException) + { + throw new ScriptHashFormatException($"{value} is invalid."); + } + } + + public override void WriteJson(JsonWriter writer, UInt160 value, JsonSerializer serializer) + { + writer.WriteValue(value.ToString()); + } + } +} diff --git a/src/RestServer/Newtonsoft/Json/UInt256JsonConverter.cs b/src/RestServer/Newtonsoft/Json/UInt256JsonConverter.cs new file mode 100644 index 000000000..b53814f01 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/UInt256JsonConverter.cs @@ -0,0 +1,36 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Plugins.RestServer.Exceptions; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json +{ + public class UInt256JsonConverter : JsonConverter + { + public override UInt256 ReadJson(JsonReader reader, Type objectType, UInt256 existingValue, bool hasExistingValue, JsonSerializer serializer) + { + var value = reader.Value?.ToString(); + try + { + return UInt256.Parse(value); + } + catch (FormatException) + { + throw new UInt256FormatException($"{value} is invalid."); + } + } + + public override void WriteJson(JsonWriter writer, UInt256 value, JsonSerializer serializer) + { + writer.WriteValue(value.ToString()); + } + } +} diff --git a/src/RestServer/Newtonsoft/Json/VmArrayJsonConverter.cs b/src/RestServer/Newtonsoft/Json/VmArrayJsonConverter.cs new file mode 100644 index 000000000..350e65a07 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/VmArrayJsonConverter.cs @@ -0,0 +1,31 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Array = Neo.VM.Types.Array; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json +{ + public class VmArrayJsonConverter : JsonConverter + { + public override Array ReadJson(JsonReader reader, Type objectType, Array existingValue, bool hasExistingValue, JsonSerializer serializer) + { + var t = JToken.Load(reader); + return RestServerUtility.StackItemFromJToken(t) as Array; + } + + public override void WriteJson(JsonWriter writer, Array value, JsonSerializer serializer) + { + var t = RestServerUtility.StackItemToJToken(value, null, serializer); + t.WriteTo(writer); + } + } +} diff --git a/src/RestServer/Newtonsoft/Json/VmBooleanJsonConverter.cs b/src/RestServer/Newtonsoft/Json/VmBooleanJsonConverter.cs new file mode 100644 index 000000000..662af037f --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/VmBooleanJsonConverter.cs @@ -0,0 +1,31 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Boolean = Neo.VM.Types.Boolean; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json +{ + public class VmBooleanJsonConverter : JsonConverter + { + public override Boolean ReadJson(JsonReader reader, Type objectType, Boolean existingValue, bool hasExistingValue, JsonSerializer serializer) + { + var t = JToken.ReadFrom(reader); + return RestServerUtility.StackItemFromJToken(t) as Boolean; + } + + public override void WriteJson(JsonWriter writer, Boolean value, JsonSerializer serializer) + { + var t = RestServerUtility.StackItemToJToken(value, null, serializer); + t.WriteTo(writer); + } + } +} diff --git a/src/RestServer/Newtonsoft/Json/VmBufferJsonConverter.cs b/src/RestServer/Newtonsoft/Json/VmBufferJsonConverter.cs new file mode 100644 index 000000000..628489d6d --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/VmBufferJsonConverter.cs @@ -0,0 +1,31 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Buffer = Neo.VM.Types.Buffer; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json +{ + public class VmBufferJsonConverter : JsonConverter + { + public override Buffer ReadJson(JsonReader reader, Type objectType, Buffer existingValue, bool hasExistingValue, JsonSerializer serializer) + { + var t = JToken.ReadFrom(reader); + return RestServerUtility.StackItemFromJToken(t) as Buffer; + } + + public override void WriteJson(JsonWriter writer, Buffer value, JsonSerializer serializer) + { + var t = RestServerUtility.StackItemToJToken(value, null, serializer); + t.WriteTo(writer); + } + } +} diff --git a/src/RestServer/Newtonsoft/Json/VmByteStringJsonConverter.cs b/src/RestServer/Newtonsoft/Json/VmByteStringJsonConverter.cs new file mode 100644 index 000000000..869484d3f --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/VmByteStringJsonConverter.cs @@ -0,0 +1,31 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.VM.Types; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json +{ + public class VmByteStringJsonConverter : JsonConverter + { + public override ByteString ReadJson(JsonReader reader, Type objectType, ByteString existingValue, bool hasExistingValue, JsonSerializer serializer) + { + var t = JToken.ReadFrom(reader); + return RestServerUtility.StackItemFromJToken(t) as ByteString; + } + + public override void WriteJson(JsonWriter writer, ByteString value, JsonSerializer serializer) + { + var t = RestServerUtility.StackItemToJToken(value, null, serializer); + t.WriteTo(writer); + } + } +} diff --git a/src/RestServer/Newtonsoft/Json/VmIntegerJsonConverter.cs b/src/RestServer/Newtonsoft/Json/VmIntegerJsonConverter.cs new file mode 100644 index 000000000..e30b22a38 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/VmIntegerJsonConverter.cs @@ -0,0 +1,31 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Integer = Neo.VM.Types.Integer; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json +{ + public class VmIntegerJsonConverter : JsonConverter + { + public override Integer ReadJson(JsonReader reader, Type objectType, Integer existingValue, bool hasExistingValue, JsonSerializer serializer) + { + var t = JToken.ReadFrom(reader); + return RestServerUtility.StackItemFromJToken(t) as Integer; + } + + public override void WriteJson(JsonWriter writer, Integer value, JsonSerializer serializer) + { + var t = RestServerUtility.StackItemToJToken(value, null, serializer); + t.WriteTo(writer); + } + } +} diff --git a/src/RestServer/Newtonsoft/Json/VmMapJsonConverter.cs b/src/RestServer/Newtonsoft/Json/VmMapJsonConverter.cs new file mode 100644 index 000000000..ce467347c --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/VmMapJsonConverter.cs @@ -0,0 +1,31 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.VM.Types; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json +{ + public class VmMapJsonConverter : JsonConverter + { + public override Map ReadJson(JsonReader reader, Type objectType, Map existingValue, bool hasExistingValue, JsonSerializer serializer) + { + var t = JToken.Load(reader); + return RestServerUtility.StackItemFromJToken(t) as Map; + } + + public override void WriteJson(JsonWriter writer, Map value, JsonSerializer serializer) + { + var t = RestServerUtility.StackItemToJToken(value, null, serializer); + t.WriteTo(writer); + } + } +} diff --git a/src/RestServer/Newtonsoft/Json/VmNullJsonConverter.cs b/src/RestServer/Newtonsoft/Json/VmNullJsonConverter.cs new file mode 100644 index 000000000..2bafeaf52 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/VmNullJsonConverter.cs @@ -0,0 +1,31 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.VM.Types; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json +{ + public class VmNullJsonConverter : JsonConverter + { + public override Null ReadJson(JsonReader reader, Type objectType, Null existingValue, bool hasExistingValue, JsonSerializer serializer) + { + var t = JToken.ReadFrom(reader); + return RestServerUtility.StackItemFromJToken(t) as Null; + } + + public override void WriteJson(JsonWriter writer, Null value, JsonSerializer serializer) + { + var t = RestServerUtility.StackItemToJToken(value, null, serializer); + t.WriteTo(writer); + } + } +} diff --git a/src/RestServer/Newtonsoft/Json/VmPointerJsonConverter.cs b/src/RestServer/Newtonsoft/Json/VmPointerJsonConverter.cs new file mode 100644 index 000000000..ba1da6bec --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/VmPointerJsonConverter.cs @@ -0,0 +1,31 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.VM.Types; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json +{ + public class VmPointerJsonConverter : JsonConverter + { + public override Pointer ReadJson(JsonReader reader, Type objectType, Pointer existingValue, bool hasExistingValue, JsonSerializer serializer) + { + var t = JToken.ReadFrom(reader); + return RestServerUtility.StackItemFromJToken(t) as Pointer; + } + + public override void WriteJson(JsonWriter writer, Pointer value, JsonSerializer serializer) + { + var t = RestServerUtility.StackItemToJToken(value, null, serializer); + t.WriteTo(writer); + } + } +} diff --git a/src/RestServer/Newtonsoft/Json/VmStructJsonConverter.cs b/src/RestServer/Newtonsoft/Json/VmStructJsonConverter.cs new file mode 100644 index 000000000..05af0dd90 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/VmStructJsonConverter.cs @@ -0,0 +1,31 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.VM.Types; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json +{ + public class VmStructJsonConverter : JsonConverter + { + public override Struct ReadJson(JsonReader reader, Type objectType, Struct existingValue, bool hasExistingValue, JsonSerializer serializer) + { + var t = JToken.Load(reader); + return RestServerUtility.StackItemFromJToken(t) as Struct; + } + + public override void WriteJson(JsonWriter writer, Struct value, JsonSerializer serializer) + { + var t = RestServerUtility.StackItemToJToken(value, null, serializer); + t.WriteTo(writer); + } + } +} diff --git a/src/RestServer/Newtonsoft/Json/WitnessConditionJsonConverter.cs b/src/RestServer/Newtonsoft/Json/WitnessConditionJsonConverter.cs new file mode 100644 index 000000000..342a37654 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/WitnessConditionJsonConverter.cs @@ -0,0 +1,95 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Cryptography.ECC; +using Neo.Network.P2P.Payloads.Conditions; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json +{ + public sealed class WitnessConditionJsonConverter : JsonConverter + { + public override bool CanWrite => true; + public override bool CanRead => true; + + public override WitnessCondition ReadJson(JsonReader reader, Type objectType, WitnessCondition existingValue, bool hasExistingValue, JsonSerializer serializer) + { + var token = JToken.ReadFrom(reader); + if (token.Type == JTokenType.Object) + return FromJson((JObject)token); + throw new NotSupportedException($"{nameof(WitnessCondition)} Type({token.Type}) is not supported from JSON."); + } + + public override void WriteJson(JsonWriter writer, WitnessCondition value, JsonSerializer serializer) + { + var j = RestServerUtility.WitnessConditionToJToken(value, serializer); + j.WriteTo(writer); + } + + public static WitnessCondition FromJson(JObject o) + { + ArgumentNullException.ThrowIfNull(o, nameof(o)); + + var typeProp = o.Properties().Single(s => EqualsIgnoreCase(s.Name, "type")); + var type = Enum.Parse(typeProp.Value()); + try + { + switch (type) + { + case WitnessConditionType.Boolean: + var valueProp = o.Properties().Single(s => EqualsIgnoreCase(s.Name, "expression")); + return new BooleanCondition() { Expression = valueProp.Value() }; + case WitnessConditionType.Not: + valueProp = o.Properties().Single(s => EqualsIgnoreCase(s.Name, "expression")); + return new NotCondition() { Expression = FromJson((JObject)valueProp.Value) }; + case WitnessConditionType.And: + valueProp = o.Properties().Single(s => EqualsIgnoreCase(s.Name, "expressions")); + if (valueProp.Type == JTokenType.Array) + { + var array = (JArray)valueProp.Value; + return new AndCondition() { Expressions = array.Select(s => FromJson((JObject)s)).ToArray() }; + } + break; + case WitnessConditionType.Or: + valueProp = o.Properties().Single(s => EqualsIgnoreCase(s.Name, "expressions")); + if (valueProp.Type == JTokenType.Array) + { + var array = (JArray)valueProp.Value; + return new OrCondition() { Expressions = array.Select(s => FromJson((JObject)s)).ToArray() }; + } + break; + case WitnessConditionType.ScriptHash: + valueProp = o.Properties().Single(s => EqualsIgnoreCase(s.Name, "hash")); + return new ScriptHashCondition() { Hash = UInt160.Parse(valueProp.Value()) }; + case WitnessConditionType.Group: + valueProp = o.Properties().Single(s => EqualsIgnoreCase(s.Name, "group")); + return new GroupCondition() { Group = ECPoint.Parse(valueProp.Value(), ECCurve.Secp256r1) }; + case WitnessConditionType.CalledByEntry: + return new CalledByEntryCondition(); + case WitnessConditionType.CalledByContract: + valueProp = o.Properties().Single(s => EqualsIgnoreCase(s.Name, "hash")); + return new CalledByContractCondition() { Hash = UInt160.Parse(valueProp.Value()) }; + case WitnessConditionType.CalledByGroup: + valueProp = o.Properties().Single(s => EqualsIgnoreCase(s.Name, "group")); + return new CalledByGroupCondition() { Group = ECPoint.Parse(valueProp.Value(), ECCurve.Secp256r1) }; + } + } + catch (ArgumentNullException ex) + { + throw new NotSupportedException($"{ex.ParamName} is not supported from JSON."); + } + throw new NotSupportedException($"WitnessConditionType({type}) is not supported from JSON."); + } + + private static bool EqualsIgnoreCase(string left, string right) => + left.Equals(right, StringComparison.InvariantCultureIgnoreCase); + } +} diff --git a/src/RestServer/Newtonsoft/Json/WitnessJsonConverter.cs b/src/RestServer/Newtonsoft/Json/WitnessJsonConverter.cs new file mode 100644 index 000000000..0ef8842c1 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/WitnessJsonConverter.cs @@ -0,0 +1,32 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Network.P2P.Payloads; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json; + +public class WitnessJsonConverter : JsonConverter +{ + public override bool CanRead => false; + + public override bool CanWrite => true; + + public override Witness ReadJson(JsonReader reader, Type objectType, Witness existingValue, bool hasExistingValue, JsonSerializer serializer) + { + throw new NotImplementedException(); + } + + public override void WriteJson(JsonWriter writer, Witness value, JsonSerializer serializer) + { + var j = RestServerUtility.WitnessToJToken(value, serializer); + j.WriteTo(writer); + } +} diff --git a/src/RestServer/Newtonsoft/Json/WitnessRuleJsonConverter.cs b/src/RestServer/Newtonsoft/Json/WitnessRuleJsonConverter.cs new file mode 100644 index 000000000..f39590647 --- /dev/null +++ b/src/RestServer/Newtonsoft/Json/WitnessRuleJsonConverter.cs @@ -0,0 +1,24 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Network.P2P.Payloads; +using Newtonsoft.Json; + +namespace Neo.Plugins.RestServer.Newtonsoft.Json; + +public class WitnessRuleJsonConverter : JsonConverter +{ + public override WitnessRule ReadJson(JsonReader reader, Type objectType, WitnessRule existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); + public override void WriteJson(JsonWriter writer, WitnessRule value, JsonSerializer serializer) + { + var j = RestServerUtility.WitnessRuleToJToken(value, serializer); + j.WriteTo(writer); + } +} diff --git a/src/RestServer/Providers/BlackListControllerFeatureProvider.cs b/src/RestServer/Providers/BlackListControllerFeatureProvider.cs new file mode 100644 index 000000000..44926ff80 --- /dev/null +++ b/src/RestServer/Providers/BlackListControllerFeatureProvider.cs @@ -0,0 +1,35 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Controllers; +using System.Reflection; + +namespace Neo.Plugins.RestServer.Providers +{ + internal class BlackListControllerFeatureProvider : ControllerFeatureProvider + { + private readonly RestServerSettings _settings; + + public BlackListControllerFeatureProvider() + { + _settings = RestServerSettings.Current; + } + + protected override bool IsController(TypeInfo typeInfo) + { + if (typeInfo.IsDefined(typeof(ApiControllerAttribute)) == false) // Rest API + return false; + if (_settings.DisableControllers.Any(a => a.Equals(typeInfo.Name, StringComparison.OrdinalIgnoreCase))) // BlackList + return false; + return base.IsController(typeInfo); // Default check + } + } +} diff --git a/src/RestServer/RestServer.csproj b/src/RestServer/RestServer.csproj new file mode 100644 index 000000000..e07ffa4e6 --- /dev/null +++ b/src/RestServer/RestServer.csproj @@ -0,0 +1,25 @@ + + + + Neo.Plugins.RestServer + Neo.Plugins.RestServer + net7.0 + enable + disable + true + $(NoWarn);1591 + + + + + + + + + + + + + + + diff --git a/src/RestServer/RestServerPlugin.Console.cs b/src/RestServer/RestServerPlugin.Console.cs new file mode 100644 index 000000000..667a153ae --- /dev/null +++ b/src/RestServer/RestServerPlugin.Console.cs @@ -0,0 +1,131 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Plugins.RestServer.Controllers.v1; +using System.Text; + +namespace Neo.Plugins.RestServer +{ + public partial class RestServerPlugin + { + [ConsoleCommand("rest sessions", Category = "RestServer Commands", Description = "Shows all active wallet sessions.")] + private void OnShowWalletSessions() + { + + if (WalletController.WalletSessions.Any()) + ConsoleHelper.Info("---------", "Sessions", "---------"); + + foreach (var (key, value) in WalletController.WalletSessions) + { + TimeSpan expires = value.Expires.Subtract(DateTime.Now); + var wallet = value.Wallet; + ConsoleHelper.Info(" Name: ", wallet.Name ?? "\"\""); + ConsoleHelper.Info(" Path: ", wallet.Path); + ConsoleHelper.Info("Version: ", wallet.Version.ToString()); + ConsoleHelper.Info("Session: ", key.ToString("n")); + ConsoleHelper.Info("Expires: ", Math.Round(expires.TotalSeconds, 0).ToString(), " second(s)."); + + if (WalletController.WalletSessions.Count > 1) + ConsoleHelper.Info(); + } + + if (WalletController.WalletSessions.Any()) + ConsoleHelper.Info("--------------------------"); + + ConsoleHelper.Info(" Total: ", WalletController.WalletSessions.Count.ToString(), " session(s)."); + } + + [ConsoleCommand("rest kill", Category = "RestServer Commands", Description = "Kills an active wallet session.")] + private void OnKillWalletSession(string sessionId) + { + if (Guid.TryParse(sessionId, out var session) == false) + { + ConsoleHelper.Warning("Invalid session id."); + return; + } + + ConsoleHelper.Info($"You are about to kill ", session.ToString("n"), " session!"); + var answer = ReadUserInput($"Are you sure?"); + if (answer.Equals("yes", StringComparison.InvariantCultureIgnoreCase) || answer.Equals("y", StringComparison.InvariantCultureIgnoreCase)) + { + if (WalletController.WalletSessions.TryRemove(session, out _)) + ConsoleHelper.Info("Session ", session.ToString("n"), " has terminated."); + else + ConsoleHelper.Error($"Session {session:n} could not be terminated. Try again later."); + } + } + + [ConsoleCommand("rest killall", Category = "RestServer Commands", Description = "Kills all active wallet sessions.")] + public void OnKillallWalletSessions() + { + if (WalletController.WalletSessions.Any() == false) + { + ConsoleHelper.Info("No ", "active", " sessions."); + return; + } + + var answer = ReadUserInput($"Kill all active wallet sessions?"); + if (answer.Equals("yes", StringComparison.InvariantCultureIgnoreCase) || answer.Equals("y", StringComparison.InvariantCultureIgnoreCase)) + { + foreach (var (session, _) in WalletController.WalletSessions) + { + if (WalletController.WalletSessions.TryRemove(session, out _)) + ConsoleHelper.Info("Session ", session.ToString("n"), " has terminated."); + else + ConsoleHelper.Error($"Session {session:n} could not be terminated. Try again later."); + } + } + } + + private string ReadUserInput(string prompt, bool password = false) + { + const string t = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; + var sb = new StringBuilder(); + + if (!string.IsNullOrEmpty(prompt)) + { + Console.Write(prompt + ": "); + } + + var prevForeground = Console.ForegroundColor; + Console.ForegroundColor = ConsoleColor.Yellow; + + if (Console.IsInputRedirected) + { + // neo-gui Console require it + sb.Append(Console.ReadLine()); + } + else + { + ConsoleKeyInfo key; + do + { + key = Console.ReadKey(true); + + if (t.IndexOf(key.KeyChar) != -1) + { + sb.Append(key.KeyChar); + Console.Write(password ? '*' : key.KeyChar); + } + else if (key.Key == ConsoleKey.Backspace && sb.Length > 0) + { + sb.Length--; + Console.Write("\b \b"); + } + } while (key.Key != ConsoleKey.Enter); + } + + Console.ForegroundColor = prevForeground; + Console.WriteLine(); + return sb.ToString(); + } + } +} diff --git a/src/RestServer/RestServerPlugin.cs b/src/RestServer/RestServerPlugin.cs new file mode 100644 index 000000000..cbab7d4e4 --- /dev/null +++ b/src/RestServer/RestServerPlugin.cs @@ -0,0 +1,62 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 Akka.Actor; +using Neo.ConsoleService; +using Neo.Network.P2P; + +namespace Neo.Plugins.RestServer +{ + public partial class RestServerPlugin : Plugin + { + public override string Name => "RestServer"; + public override string Description => "Enables REST Web Sevices for the node"; + + #region Globals + + private RestServerSettings _settings; + private RestWebServer _server; + + #endregion + + #region Static Globals + + internal static NeoSystem NeoSystem { get; private set; } + internal static LocalNode LocalNode { get; private set; } + + #endregion + + protected override void Configure() + { + RestServerSettings.Load(GetConfiguration()); + _settings = RestServerSettings.Current; + } + + protected override void OnSystemLoaded(NeoSystem system) + { + if (_settings.EnableCors && _settings.EnableBasicAuthentication && _settings.AllowOrigins.Length == 0) + { + ConsoleHelper.Warning("RestServer: CORS is misconfigured!"); + ConsoleHelper.Info($"You have {nameof(_settings.EnableCors)} and {nameof(_settings.EnableBasicAuthentication)} enabled but"); + ConsoleHelper.Info($"{nameof(_settings.AllowOrigins)} is empty in config.json for RestServer."); + ConsoleHelper.Info("You must add url origins to the list to have CORS work from"); + ConsoleHelper.Info($"browser with basic authentication enabled."); + ConsoleHelper.Info($"Example: \"AllowOrigins\": [\"http://{_settings.BindAddress}:{_settings.Port}\"]"); + } + if (system.Settings.Network == _settings.Network) + { + NeoSystem = system; + LocalNode = system.LocalNode.Ask(new LocalNode.GetInstance()).Result; + } + _server = new RestWebServer(); + _server.Start(); + } + } +} diff --git a/src/RestServer/RestServerSettings.cs b/src/RestServer/RestServerSettings.cs new file mode 100644 index 000000000..188abfeb9 --- /dev/null +++ b/src/RestServer/RestServerSettings.cs @@ -0,0 +1,162 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 Microsoft.Extensions.Configuration; +using Neo.Plugins.RestServer.Newtonsoft.Json; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Serialization; +using System.IO.Compression; +using System.Net; + +namespace Neo.Plugins.RestServer +{ + public class RestServerSettings + { + #region Settings + + public uint Network { get; init; } + public IPAddress BindAddress { get; init; } + public uint Port { get; init; } + public uint KeepAliveTimeout { get; init; } + public string SslCertFile { get; init; } + public string SslCertPassword { get; init; } + public string[] TrustedAuthorities { get; init; } + public bool EnableBasicAuthentication { get; init; } + public string RestUser { get; init; } + public string RestPass { get; init; } + public bool EnableCors { get; init; } + public string[] AllowOrigins { get; init; } + public string[] DisableControllers { get; init; } + public bool EnableCompression { get; init; } + public CompressionLevel CompressionLevel { get; init; } + public bool EnableForwardedHeaders { get; init; } + public bool EnableSwagger { get; init; } + public uint MaxPageSize { get; init; } + public long MaxConcurrentConnections { get; init; } + public long MaxTransactionFee { get; init; } + public long MaxGasInvoke { get; init; } + public uint MaxTransactionSize { get; init; } + public uint WalletSessionTimeout { get; init; } + public JsonSerializerSettings JsonSerializerSettings { get; init; } + + #endregion + + #region Static Functions + + public static RestServerSettings Current { get; private set; } + public static RestServerSettings Default { get; } = new() + { + Network = 860833102u, + BindAddress = IPAddress.Loopback, + Port = 10339u, + KeepAliveTimeout = 120u, + SslCertFile = "", + SslCertPassword = "", + TrustedAuthorities = Array.Empty(), + EnableBasicAuthentication = false, + RestUser = string.Empty, + RestPass = string.Empty, + EnableCors = false, + AllowOrigins = Array.Empty(), + DisableControllers = Array.Empty(), + EnableCompression = false, + CompressionLevel = CompressionLevel.SmallestSize, + EnableForwardedHeaders = false, + EnableSwagger = false, + MaxPageSize = 50u, + MaxConcurrentConnections = 40L, + MaxTransactionFee = 0_10000000L, + MaxGasInvoke = 0_20000000L, + MaxTransactionSize = 1024u, + WalletSessionTimeout = 120u, + JsonSerializerSettings = new JsonSerializerSettings() + { + ContractResolver = new CamelCasePropertyNamesContractResolver(), + MissingMemberHandling = MissingMemberHandling.Error, + NullValueHandling = NullValueHandling.Include, + Formatting = Formatting.None, + Converters = new JsonConverter[] + { + new StringEnumConverter(), + new BigDecimalJsonConverter(), + new BlockHeaderJsonConverter(), + new BlockJsonConverter(), + new ContractAbiJsonConverter(), + new ContractEventDescriptorJsonConverter(), + new ContractGroupJsonConverter(), + new ContractJsonConverter(), + new ContractManifestJsonConverter(), + new ContractMethodJsonConverter(), + new ContractMethodParametersJsonConverter(), + new ContractParameterDefinitionJsonConverter(), + new ContractParameterJsonConverter(), + new ContractPermissionDescriptorJsonConverter(), + new ContractPermissionJsonConverter(), + new ECPointJsonConverter(), + new GuidJsonConverter(), + new InteropInterfaceJsonConverter(), + new MethodTokenJsonConverter(), + new NefFileJsonConverter(), + new ReadOnlyMemoryBytesJsonConverter(), + new SignerJsonConverter(), + new StackItemJsonConverter(), + new TransactionAttributeJsonConverter(), + new TransactionJsonConverter(), + new UInt160JsonConverter(), + new UInt256JsonConverter(), + new VmArrayJsonConverter(), + new VmBooleanJsonConverter(), + new VmBufferJsonConverter(), + new VmByteStringJsonConverter(), + new VmIntegerJsonConverter(), + new VmMapJsonConverter(), + new VmNullJsonConverter(), + new VmPointerJsonConverter(), + new VmStructJsonConverter(), + new WitnessConditionJsonConverter(), + new WitnessJsonConverter(), + new WitnessRuleJsonConverter(), + }, + }, + }; + + public static void Load(IConfigurationSection section) => + Current = new() + { + Network = section.GetValue(nameof(Network), Default.Network), + BindAddress = IPAddress.Parse(section.GetSection(nameof(BindAddress)).Value), + Port = section.GetValue(nameof(Port), Default.Port), + KeepAliveTimeout = section.GetValue(nameof(KeepAliveTimeout), Default.KeepAliveTimeout), + SslCertFile = section.GetValue(nameof(SslCertFile), Default.SslCertFile), + SslCertPassword = section.GetValue(nameof(SslCertPassword), Default.SslCertPassword), + TrustedAuthorities = section.GetSection(nameof(TrustedAuthorities))?.Get() ?? Default.TrustedAuthorities, + EnableBasicAuthentication = section.GetValue(nameof(EnableBasicAuthentication), Default.EnableBasicAuthentication), + RestUser = section.GetValue(nameof(RestUser), Default.RestUser), + RestPass = section.GetValue(nameof(RestPass), Default.RestPass), + EnableCors = section.GetValue(nameof(EnableCors), Default.EnableCors), + AllowOrigins = section.GetSection(nameof(AllowOrigins))?.Get() ?? Default.AllowOrigins, + DisableControllers = section.GetSection(nameof(DisableControllers))?.Get() ?? Default.DisableControllers, + EnableCompression = section.GetValue(nameof(EnableCompression), Default.EnableCompression), + CompressionLevel = section.GetValue(nameof(CompressionLevel), Default.CompressionLevel), + EnableForwardedHeaders = section.GetValue(nameof(EnableForwardedHeaders), Default.EnableForwardedHeaders), + EnableSwagger = section.GetValue(nameof(EnableSwagger), Default.EnableSwagger), + MaxPageSize = section.GetValue(nameof(MaxPageSize), Default.MaxPageSize), + MaxConcurrentConnections = section.GetValue(nameof(MaxConcurrentConnections), Default.MaxConcurrentConnections), + MaxTransactionFee = section.GetValue(nameof(MaxTransactionFee), Default.MaxTransactionFee), + MaxGasInvoke = section.GetValue(nameof(MaxGasInvoke), Default.MaxGasInvoke), + MaxTransactionSize = section.GetValue(nameof(MaxTransactionSize), Default.MaxTransactionSize), + WalletSessionTimeout = section.GetValue(nameof(WalletSessionTimeout), Default.WalletSessionTimeout), + JsonSerializerSettings = Default.JsonSerializerSettings, + }; + + #endregion + } +} diff --git a/src/RestServer/RestServerUtility.JTokens.cs b/src/RestServer/RestServerUtility.JTokens.cs new file mode 100644 index 000000000..4f1d7262c --- /dev/null +++ b/src/RestServer/RestServerUtility.JTokens.cs @@ -0,0 +1,302 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Network.P2P.Payloads; +using Neo.Network.P2P.Payloads.Conditions; +using Neo.SmartContract; +using Neo.SmartContract.Manifest; +using Newtonsoft.Json.Linq; + +namespace Neo.Plugins.RestServer +{ + public static partial class RestServerUtility + { + public static JToken BlockHeaderToJToken(Header header, global::Newtonsoft.Json.JsonSerializer serializer) => + JToken.FromObject(new + { + header.Timestamp, + header.Version, + header.PrimaryIndex, + header.Index, + header.Nonce, + header.Hash, + header.MerkleRoot, + header.PrevHash, + header.NextConsensus, + Witness = WitnessToJToken(header.Witness, serializer), + header.Size, + }, serializer); + + public static JToken WitnessToJToken(Witness witness, global::Newtonsoft.Json.JsonSerializer serializer) => + JToken.FromObject(new + { + witness.InvocationScript, + witness.VerificationScript, + witness.ScriptHash, + }, serializer); + + public static JToken BlockToJToken(Block block, global::Newtonsoft.Json.JsonSerializer serializer) => + JToken.FromObject(new + { + block.Timestamp, + block.Version, + block.PrimaryIndex, + block.Index, + block.Nonce, + block.Hash, + block.MerkleRoot, + block.PrevHash, + block.NextConsensus, + Witness = WitnessToJToken(block.Witness, serializer), + block.Size, + Transactions = block.Transactions.Select(s => TransactionToJToken(s, serializer)), + }, serializer); + + public static JToken TransactionToJToken(Transaction tx, global::Newtonsoft.Json.JsonSerializer serializer) => + JToken.FromObject(new + { + tx.Hash, + tx.Sender, + tx.Script, + tx.FeePerByte, + tx.NetworkFee, + tx.SystemFee, + tx.Size, + tx.Nonce, + tx.Version, + tx.ValidUntilBlock, + Witnesses = tx.Witnesses.Select(s => WitnessToJToken(s, serializer)), + Signers = tx.Signers.Select(s => SignerToJToken(s, serializer)), + Attributes = tx.Attributes.Select(s => TransactionAttributeToJToken(s, serializer)), + }, serializer); + + public static JToken SignerToJToken(Signer signer, global::Newtonsoft.Json.JsonSerializer serializer) => + JToken.FromObject(new + { + Rules = signer.Rules.Select(s => WitnessRuleToJToken(s, serializer)), + signer.Account, + signer.AllowedContracts, + signer.AllowedGroups, + signer.Scopes, + }, serializer); + + public static JToken TransactionAttributeToJToken(TransactionAttribute attribute, global::Newtonsoft.Json.JsonSerializer serializer) => + JToken.FromObject(new + { + attribute.Type, + attribute.AllowMultiple, + }, serializer); + + public static JToken WitnessRuleToJToken(WitnessRule rule, global::Newtonsoft.Json.JsonSerializer serializer) => + JToken.FromObject(new + { + rule.Action, + Condition = WitnessConditionToJToken(rule.Condition, serializer), + }, serializer); + + public static JToken WitnessConditionToJToken(WitnessCondition condition, global::Newtonsoft.Json.JsonSerializer serializer) + { + JToken j = JValue.CreateNull(); + switch (condition.Type) + { + case WitnessConditionType.Boolean: + var b = condition as BooleanCondition; + j = JToken.FromObject(new + { + b.Type, + b.Expression, + }, serializer); + break; + case WitnessConditionType.Not: + var n = condition as NotCondition; + j = JToken.FromObject(new + { + n.Type, + Expression = WitnessConditionToJToken(n.Expression, serializer), + }, serializer); + break; + case WitnessConditionType.And: + var a = condition as AndCondition; + j = JToken.FromObject(new + { + a.Type, + Expressions = a.Expressions.Select(s => WitnessConditionToJToken(s, serializer)), + }, serializer); + break; + case WitnessConditionType.Or: + var o = condition as OrCondition; + j = JToken.FromObject(new + { + o.Type, + Expressions = o.Expressions.Select(s => WitnessConditionToJToken(s, serializer)), + }, serializer); + break; + case WitnessConditionType.ScriptHash: + var s = condition as ScriptHashCondition; + j = JToken.FromObject(new + { + s.Type, + s.Hash, + }, serializer); + break; + case WitnessConditionType.Group: + var g = condition as GroupCondition; + j = JToken.FromObject(new + { + g.Type, + g.Group, + }, serializer); + break; + case WitnessConditionType.CalledByEntry: + var e = condition as CalledByEntryCondition; + j = JToken.FromObject(new + { + e.Type, + }, serializer); + break; + case WitnessConditionType.CalledByContract: + var c = condition as CalledByContractCondition; + j = JToken.FromObject(new + { + c.Type, + c.Hash, + }, serializer); + break; + case WitnessConditionType.CalledByGroup: + var p = condition as CalledByGroupCondition; + j = JToken.FromObject(new + { + p.Type, + p.Group, + }, serializer); + break; + default: + break; + } + return j; + } + + public static JToken ContractStateToJToken(ContractState contract, global::Newtonsoft.Json.JsonSerializer serializer) => + JToken.FromObject(new + { + contract.Id, + contract.Manifest.Name, + contract.Hash, + Manifest = ContractManifestToJToken(contract.Manifest, serializer), + NefFile = ContractNefFileToJToken(contract.Nef, serializer), + }, serializer); + + public static JToken ContractManifestToJToken(ContractManifest manifest, global::Newtonsoft.Json.JsonSerializer serializer) => + JToken.FromObject(new + { + manifest.Name, + Abi = ContractAbiToJToken(manifest.Abi, serializer), + Groups = manifest.Groups.Select(s => ContractGroupToJToken(s, serializer)), + Permissions = manifest.Permissions.Select(s => ContractPermissionToJToken(s, serializer)), + Trusts = manifest.Trusts.Select(s => ContractPermissionDescriptorToJToken(s, serializer)), + manifest.SupportedStandards, + Extra = manifest.Extra.Count > 0 ? + new JObject(manifest.Extra.Properties.Select(s => new JProperty(s.Key.ToString(), s.Value.AsString()))) : + null, + }, serializer); + + public static JToken ContractAbiToJToken(ContractAbi abi, global::Newtonsoft.Json.JsonSerializer serializer) => + JToken.FromObject(new + { + Methods = abi.Methods.Select(s => ContractMethodToJToken(s, serializer)), + Events = abi.Events.Select(s => ContractEventToJToken(s, serializer)), + }, serializer); + + public static JToken ContractMethodToJToken(ContractMethodDescriptor method, global::Newtonsoft.Json.JsonSerializer serializer) => + JToken.FromObject(new + { + method.Name, + method.Safe, + method.Offset, + Parameters = method.Parameters.Select(s => ContractMethodParameterToJToken(s, serializer)), + method.ReturnType, + }, serializer); + + public static JToken ContractMethodParameterToJToken(ContractParameterDefinition parameter, global::Newtonsoft.Json.JsonSerializer serializer) => + JToken.FromObject(new + { + parameter.Type, + parameter.Name, + }, serializer); + + public static JToken ContractGroupToJToken(ContractGroup group, global::Newtonsoft.Json.JsonSerializer serializer) => + JToken.FromObject(new + { + group.PubKey, + group.Signature, + }, serializer); + + public static JToken ContractPermissionToJToken(ContractPermission permission, global::Newtonsoft.Json.JsonSerializer serializer) => + JToken.FromObject(new + { + Contract = ContractPermissionDescriptorToJToken(permission.Contract, serializer), + Methods = permission.Methods.Count > 0 ? + permission.Methods.Select(s => s).ToArray() : + (object)"*", + }, serializer); + + public static JToken ContractPermissionDescriptorToJToken(ContractPermissionDescriptor desc, global::Newtonsoft.Json.JsonSerializer serializer) + { + JToken j = JValue.CreateNull(); + if (desc.IsWildcard) + j = JValue.CreateString("*"); + else if (desc.IsGroup) + j = JToken.FromObject(new + { + desc.Group + }, serializer); + else if (desc.IsHash) + j = JToken.FromObject(new + { + desc.Hash, + }, serializer); + return j; + } + + public static JToken ContractEventToJToken(ContractEventDescriptor desc, global::Newtonsoft.Json.JsonSerializer serializer) => + JToken.FromObject(new + { + desc.Name, + Parameters = desc.Parameters.Select(s => ContractParameterDefinitionToJToken(s, serializer)), + }, serializer); + + public static JToken ContractParameterDefinitionToJToken(ContractParameterDefinition definition, global::Newtonsoft.Json.JsonSerializer serializer) => + JToken.FromObject(new + { + definition.Type, + definition.Name, + }, serializer); + + public static JToken ContractNefFileToJToken(NefFile nef, global::Newtonsoft.Json.JsonSerializer serializer) => + JToken.FromObject(new + { + Checksum = nef.CheckSum, + nef.Compiler, + nef.Script, + nef.Source, + Tokens = nef.Tokens.Select(s => MethodTokenToJToken(s, serializer)), + }, serializer); + + public static JToken MethodTokenToJToken(MethodToken token, global::Newtonsoft.Json.JsonSerializer serializer) => + JToken.FromObject(new + { + token.Hash, + token.Method, + token.CallFlags, + token.ParametersCount, + token.HasReturnValue, + }, serializer); + } +} diff --git a/src/RestServer/RestServerUtility.cs b/src/RestServer/RestServerUtility.cs new file mode 100644 index 000000000..82c6fb39f --- /dev/null +++ b/src/RestServer/RestServerUtility.cs @@ -0,0 +1,346 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Cryptography.ECC; +using Neo.SmartContract; +using Neo.VM.Types; +using Neo.Wallets; +using Newtonsoft.Json.Linq; +using System.Numerics; +using Array = Neo.VM.Types.Array; +using Boolean = Neo.VM.Types.Boolean; +using Buffer = Neo.VM.Types.Buffer; + +namespace Neo.Plugins.RestServer +{ + public static partial class RestServerUtility + { + public static UInt160 ConvertToScriptHash(string address, ProtocolSettings settings) + { + if (UInt160.TryParse(address, out var scriptHash)) + return scriptHash; + return address?.ToScriptHash(settings.AddressVersion); + } + + public static bool TryConvertToScriptHash(string address, ProtocolSettings settings, out UInt160 scriptHash) + { + try + { + if (UInt160.TryParse(address, out scriptHash)) + return true; + scriptHash = address.ToScriptHash(settings.AddressVersion); + return true; + } + catch + { + scriptHash = UInt160.Zero; + return false; + } + } + + public static StackItem StackItemFromJToken(JToken json) + { + if (json.Type == JTokenType.Object) + { + var jsonObject = json as JObject; + var props = jsonObject.Properties(); + var typeProp = props.SingleOrDefault(s => s.Name.Equals("type", StringComparison.InvariantCultureIgnoreCase)); + var valueProp = props.SingleOrDefault(s => s.Name.Equals("value", StringComparison.InvariantCultureIgnoreCase)); + + if (typeProp != null) + { + StackItem s = StackItem.Null; + var type = Enum.Parse(typeProp.ToObject(), true); + var value = valueProp.Value; + + switch (type) + { + case StackItemType.Struct: + if (value.Type == JTokenType.Array) + { + var st = new Struct(); + foreach (var item in (JArray)value) + st.Add(StackItemFromJToken(item)); + s = st; + } + break; + case StackItemType.Array: + if (value.Type == JTokenType.Array) + { + var a = new Array(); + foreach (var item in (JArray)value) + a.Add(StackItemFromJToken(item)); + s = a; + } + break; + case StackItemType.Map: + if (value.Type == JTokenType.Array) + { + var m = new Map(); + foreach (var item in (JArray)value) + { + if (item.Type != JTokenType.Object) + continue; + var vprops = ((JObject)item).Properties(); + var keyProps = vprops.SingleOrDefault(s => s.Name.Equals("key", StringComparison.InvariantCultureIgnoreCase)); + var keyValueProps = vprops.SingleOrDefault(s => s.Name.Equals("value", StringComparison.InvariantCultureIgnoreCase)); + if (keyProps == null && keyValueProps == null) + continue; + var key = (PrimitiveType)StackItemFromJToken(keyProps?.Value); + m[key] = StackItemFromJToken(keyValueProps?.Value); + } + s = m; + } + break; + case StackItemType.Boolean: + s = value.ToObject() ? StackItem.True : StackItem.False; + break; + case StackItemType.Buffer: + s = new Buffer(Convert.FromBase64String(value.ToObject())); + break; + case StackItemType.ByteString: + s = new ByteString(Convert.FromBase64String(value.ToObject())); + break; + case StackItemType.Integer: + s = value.ToObject(); + break; + case StackItemType.InteropInterface: + s = new InteropInterface(Convert.FromBase64String(value.ToObject())); + break; + case StackItemType.Pointer: + s = new Pointer(null, value.ToObject()); + break; + default: + break; + } + return s; + } + } + throw new FormatException(); + } + + public static JToken StackItemToJToken(StackItem item, IList<(StackItem, JToken)> context, global::Newtonsoft.Json.JsonSerializer serializer) + { + JToken o = null; + switch (item) + { + case Struct @struct: + if (context is null) + context = new List<(StackItem, JToken)>(); + else + (_, o) = context.FirstOrDefault(f => ReferenceEquals(f.Item1, item)); + if (o is null) + { + context.Add((item, o)); + var a = @struct.Select(s => StackItemToJToken(s, context, serializer)); + o = JToken.FromObject(new + { + Type = StackItemType.Struct.ToString(), + Value = JArray.FromObject(a), + }, serializer); + } + break; + case Array array: + if (context is null) + context = new List<(StackItem, JToken)>(); + else + (_, o) = context.FirstOrDefault(f => ReferenceEquals(f.Item1, item)); + if (o is null) + { + context.Add((item, o)); + var a = array.Select(s => StackItemToJToken(s, context, serializer)); + o = JToken.FromObject(new + { + Type = StackItemType.Array.ToString(), + Value = JArray.FromObject(a, serializer), + }, serializer); + } + break; + case Map map: + if (context is null) + context = new List<(StackItem, JToken)>(); + else + (_, o) = context.FirstOrDefault(f => ReferenceEquals(f.Item1, item)); + if (o is null) + { + context.Add((item, o)); + var kvp = map.Select(s => + new KeyValuePair( + StackItemToJToken(s.Key, context, serializer), + StackItemToJToken(s.Value, context, serializer))); + o = JToken.FromObject(new + { + Type = StackItemType.Map.ToString(), + Value = JArray.FromObject(kvp, serializer), + }, serializer); + } + break; + case Boolean: + o = JToken.FromObject(new + { + Type = StackItemType.Boolean.ToString(), + Value = item.GetBoolean(), + }, serializer); + break; + case Buffer: + o = JToken.FromObject(new + { + Type = StackItemType.Buffer.ToString(), + Value = Convert.ToBase64String(item.GetSpan()), + }, serializer); + break; + case ByteString: + o = JToken.FromObject(new + { + Type = StackItemType.ByteString.ToString(), + Value = Convert.ToBase64String(item.GetSpan()), + }, serializer); + break; + case Integer: + o = JToken.FromObject(new + { + Type = StackItemType.Integer.ToString(), + Value = item.GetInteger(), + }, serializer); + break; + case InteropInterface: + o = JToken.FromObject(new + { + Type = StackItemType.InteropInterface.ToString(), + Value = Convert.ToBase64String(item.GetSpan()), + }); + break; + case Pointer pointer: + o = JToken.FromObject(new + { + Type = StackItemType.Pointer.ToString(), + Value = pointer.Position, + }, serializer); + break; + case Null: + case null: + o = JToken.FromObject(new + { + Type = StackItemType.Any.ToString(), + Value = JValue.CreateNull(), + }, serializer); + break; + default: + throw new NotSupportedException($"StackItemType({item.Type}) is not supported to JSON."); + } + return o; + } + + public static ContractParameter ContractParameterFromJToken(JToken token) + { + if (token.Type != JTokenType.Object) + throw new FormatException(); + + var obj = (JObject)token; + var typeProp = obj + .Properties() + .SingleOrDefault(a => a.Name.Equals("type", StringComparison.InvariantCultureIgnoreCase)); + var valueProp = obj + .Properties() + .SingleOrDefault(a => a.Name.Equals("value", StringComparison.InvariantCultureIgnoreCase)); + + if (typeProp == null || valueProp == null) + throw new FormatException(); + + var typeValue = Enum.Parse(typeProp.ToObject()); + + switch (typeValue) + { + case ContractParameterType.Any: + return new ContractParameter(ContractParameterType.Any); + case ContractParameterType.ByteArray: + return new ContractParameter() + { + Type = ContractParameterType.ByteArray, + Value = Convert.FromBase64String(valueProp.ToObject()), + }; + case ContractParameterType.Signature: + return new ContractParameter() + { + Type = ContractParameterType.Signature, + Value = Convert.FromBase64String(valueProp.ToObject()), + }; + case ContractParameterType.Boolean: + return new ContractParameter() + { + Type = ContractParameterType.Boolean, + Value = valueProp.ToObject(), + }; + case ContractParameterType.Integer: + return new ContractParameter() + { + Type = ContractParameterType.Integer, + Value = BigInteger.Parse(valueProp.ToObject()), + }; + case ContractParameterType.String: + return new ContractParameter() + { + Type = ContractParameterType.String, + Value = valueProp.ToObject(), + }; + case ContractParameterType.Hash160: + return new ContractParameter() + { + Type = ContractParameterType.Hash160, + Value = UInt160.Parse(valueProp.ToObject()), + }; + case ContractParameterType.Hash256: + return new ContractParameter() + { + Type = ContractParameterType.Hash256, + Value = UInt256.Parse(valueProp.ToObject()), + }; + case ContractParameterType.PublicKey: + return new ContractParameter() + { + Type = ContractParameterType.PublicKey, + Value = ECPoint.Parse(valueProp.ToObject(), ECCurve.Secp256r1), + }; + case ContractParameterType.Array: + if (valueProp.Value?.Type != JTokenType.Array) + throw new FormatException(); + var array = valueProp.Value as JArray; + return new ContractParameter() + { + Type = ContractParameterType.Array, + Value = array.Select(ContractParameterFromJToken).ToList(), + }; + case ContractParameterType.Map: + if (valueProp.Value?.Type != JTokenType.Array) + throw new FormatException(); + var map = valueProp.Value as JArray; + return new ContractParameter() + { + Type = ContractParameterType.Map, + Value = map.Select(s => + { + if (s.Type != JTokenType.Object) + throw new FormatException(); + var mapProp = valueProp.Value as JObject; + var keyProp = mapProp + .Properties() + .SingleOrDefault(ss => ss.Name.Equals("key", StringComparison.InvariantCultureIgnoreCase)); + var keyValueProp = mapProp + .Properties() + .SingleOrDefault(ss => ss.Name.Equals("value", StringComparison.InvariantCultureIgnoreCase)); + return new KeyValuePair(ContractParameterFromJToken(keyProp.Value), ContractParameterFromJToken(keyValueProp.Value)); + }).ToList(), + }; + default: + throw new NotSupportedException($"ContractParameterType({typeValue}) is not supported to JSON."); + } + } + } +} diff --git a/src/RestServer/RestWebServer.cs b/src/RestServer/RestWebServer.cs new file mode 100644 index 000000000..7e722b761 --- /dev/null +++ b/src/RestServer/RestWebServer.cs @@ -0,0 +1,417 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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 Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Diagnostics; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.HttpOverrides; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Abstractions; +using Microsoft.AspNetCore.Mvc.ApiExplorer; +using Microsoft.AspNetCore.Mvc.ApplicationParts; +using Microsoft.AspNetCore.Mvc.Authorization; +using Microsoft.AspNetCore.Mvc.Controllers; +using Microsoft.AspNetCore.Mvc.Versioning; +using Microsoft.AspNetCore.ResponseCompression; +using Microsoft.AspNetCore.Server.Kestrel.Https; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.OpenApi.Models; +using Neo.Cryptography.ECC; +using Neo.Network.P2P.Payloads.Conditions; +using Neo.Plugins.RestServer.Binder; +using Neo.Plugins.RestServer.Middleware; +using Neo.Plugins.RestServer.Models.Error; +using Neo.Plugins.RestServer.Providers; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using RestServer.Authentication; +using System.Net.Mime; +using System.Net.Security; +using System.Numerics; + +namespace Neo.Plugins.RestServer +{ + internal class RestWebServer + { + #region Globals + + private readonly RestServerSettings _settings; + private IWebHost _host; + + #endregion + + public static bool IsRunning { get; private set; } + + public RestWebServer() + { + _settings = RestServerSettings.Current; + } + + public void Start() + { + if (IsRunning) + return; + + IsRunning = true; + + _host = new WebHostBuilder() + .UseKestrel(options => + { + // Web server configuration + options.AddServerHeader = false; + options.Limits.MaxConcurrentConnections = _settings.MaxConcurrentConnections; + options.Limits.KeepAliveTimeout = TimeSpan.FromSeconds(_settings.KeepAliveTimeout); + options.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(15); + options.Listen(_settings.BindAddress, unchecked((int)_settings.Port), + listenOptions => + { + if (string.IsNullOrEmpty(_settings.SslCertFile)) + return; + listenOptions.UseHttps(_settings.SslCertFile, _settings.SslCertPassword, httpsOptions => + { + if (_settings.TrustedAuthorities.Length == 0) + { + httpsOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate; + httpsOptions.ClientCertificateValidation = (cert, chain, err) => + { + if (err != SslPolicyErrors.None) + return false; + var authority = chain.ChainElements[^1].Certificate; + return _settings.TrustedAuthorities.Any(a => a.Equals(authority.Thumbprint, StringComparison.OrdinalIgnoreCase)); + }; + } + }); + }); + }) + .ConfigureServices(services => + { + #region Add Basic auth + + if (_settings.EnableBasicAuthentication) + services.AddAuthentication() + .AddScheme("Basic", null); + + #endregion + + #region CORS + + // Server configuration + if (_settings.EnableCors) + { + if (_settings.AllowOrigins.Length == 0) + services.AddCors(options => + { + options.AddPolicy("All", policy => + { + policy.AllowAnyOrigin() + .AllowAnyHeader() + .WithMethods("GET", "POST"); + // The CORS specification states that setting origins to "*" (all origins) + // is invalid if the Access-Control-Allow-Credentials header is present. + //.AllowCredentials() + }); + }); + else + services.AddCors(options => + { + options.AddPolicy("All", policy => + { + policy.WithOrigins(_settings.AllowOrigins) + .AllowAnyHeader() + .AllowCredentials() + .WithMethods("GET", "POST"); + }); + }); + } + + #endregion + + services.AddRouting(options => options.LowercaseUrls = options.LowercaseQueryStrings = true); + + #region Compression Configuration + + if (_settings.EnableCompression) + services.AddResponseCompression(options => + { + options.EnableForHttps = false; + options.Providers.Add(); + options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Append(MediaTypeNames.Application.Json); + }); + + #endregion + + #region Controllers + + var controllers = services + .AddControllers(options => + { + options.EnableEndpointRouting = false; + + if (_settings.EnableBasicAuthentication) + { + var policy = new AuthorizationPolicyBuilder() + .RequireAuthenticatedUser() + .Build(); + options.Filters.Add(new AuthorizeFilter(policy)); + } + options.ModelBinderProviders.Insert(0, new NeoBinderProvider()); + }) + .ConfigureApiBehaviorOptions(options => + { + options.InvalidModelStateResponseFactory = context => + new BadRequestObjectResult( + new ParameterFormatExceptionModel(string.Join(' ', context.ModelState.Values.SelectMany(s => s.Errors).Select(s => s.ErrorMessage)))) + { + ContentTypes = + { + MediaTypeNames.Application.Json, + } + }; + }) + .ConfigureApplicationPartManager(manager => + { + var controllerFeatureProvider = manager.FeatureProviders.Single(p => p.GetType() == typeof(ControllerFeatureProvider)); + var index = manager.FeatureProviders.IndexOf(controllerFeatureProvider); + manager.FeatureProviders[index] = new BlackListControllerFeatureProvider(); + + foreach (var plugin in Plugin.Plugins) + manager.ApplicationParts.Add(new AssemblyPart(plugin.GetType().Assembly)); + }) + .AddNewtonsoftJson(options => + { + options.AllowInputFormatterExceptionMessages = true; + options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); + options.SerializerSettings.Formatting = Formatting.None; + + foreach (var converter in _settings.JsonSerializerSettings.Converters) + options.SerializerSettings.Converters.Add(converter); + }); + + #endregion + + #region API Versioning + + services.AddVersionedApiExplorer(setupAction => + { + setupAction.GroupNameFormat = "'v'VV"; + }); + + services.AddApiVersioning(options => + { + options.AssumeDefaultVersionWhenUnspecified = true; + options.DefaultApiVersion = new ApiVersion(1, 0); + options.ReportApiVersions = true; + }); + + #endregion + + #region Swagger Configuration + + if (_settings.EnableSwagger) + { + var apiVersionDescriptionProvider = services.BuildServiceProvider().GetRequiredService(); + services.AddSwaggerGen(options => + { + foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions) + { + options.SwaggerDoc(description.GroupName, new OpenApiInfo() + { + Title = "RestServer Plugin API", + Description = "RESTful Web Sevices for neo-cli.", + Version = description.ApiVersion.ToString(), + Contact = new OpenApiContact() + { + Name = "The Neo Project", + Url = new Uri("https://github.com/neo-project/neo-modules"), + Email = "dev@neo.org", + }, + License = new OpenApiLicense() + { + Name = "MIT", + Url = new Uri("http://www.opensource.org/licenses/mit-license.php"), + }, + }); + } + + #region Enable Basic Auth for Swagger + + if (_settings.EnableBasicAuthentication) + { + options.AddSecurityDefinition("basicAuth", new OpenApiSecurityScheme() + { + Type = SecuritySchemeType.Http, + Scheme = "basic", + Description = "Input your username and password to access this API.", + }); + options.AddSecurityRequirement(new OpenApiSecurityRequirement() + { + { + new OpenApiSecurityScheme() + { + Reference = new OpenApiReference() + { + Type = ReferenceType.SecurityScheme, + Id = "basicAuth", + }, + }, + new List() + } + }); + } + + #endregion + + options.DocInclusionPredicate((docmentName, apiDescription) => + { + var actionApiVersionModel = apiDescription.ActionDescriptor.GetApiVersionModel(ApiVersionMapping.Explicit | ApiVersionMapping.Implicit); + if (actionApiVersionModel == null) + return true; + if (actionApiVersionModel.DeclaredApiVersions.Any()) + return actionApiVersionModel.DeclaredApiVersions.Any(a => $"v{a}" == docmentName); + return actionApiVersionModel.ImplementedApiVersions.Any(a => $"v{a}" == docmentName); + }); + + options.UseOneOfForPolymorphism(); + options.SelectSubTypesUsing(baseType => + { + if (baseType == typeof(WitnessCondition)) + { + return new[] + { + typeof(BooleanCondition), + typeof(NotCondition), + typeof(AndCondition), + typeof(OrCondition), + typeof(ScriptHashCondition), + typeof(GroupCondition), + typeof(CalledByEntryCondition), + typeof(CalledByContractCondition), + typeof(CalledByGroupCondition), + }; + } + + return Enumerable.Empty(); + }); + options.MapType(() => new OpenApiSchema() + { + Type = "string", + Format = "hash256", + }); + options.MapType(() => new OpenApiSchema() + { + Type = "string", + Format = "hash160", + }); + options.MapType(() => new OpenApiSchema() + { + Type = "string", + Format = "hexstring", + }); + options.MapType(() => new OpenApiSchema() + { + Type = "integer", + Format = "bigint", + }); + options.MapType(() => new OpenApiSchema() + { + Type = "string", + Format = "base64", + }); + options.MapType>(() => new OpenApiSchema() + { + Type = "string", + Format = "base64", + }); + foreach (var plugin in Plugin.Plugins) + { + var assemblyName = plugin.GetType().Assembly.GetName().Name; + var xmlPathAndFilename = Path.Combine(AppContext.BaseDirectory, "Plugins", assemblyName, $"{assemblyName}.xml"); + if (File.Exists(xmlPathAndFilename)) + options.IncludeXmlComments(xmlPathAndFilename); + } + }); + services.AddSwaggerGenNewtonsoftSupport(); + } + + #endregion + + #region Forward Headers + + if (_settings.EnableForwardedHeaders) + services.Configure(options => options.ForwardedHeaders = ForwardedHeaders.All); + + #endregion + + #region Compression + + if (_settings.EnableCompression) + services.Configure(options => options.Level = _settings.CompressionLevel); + + #endregion + }) + .Configure(app => + { + app.UseMiddleware(); + + if (_settings.EnableForwardedHeaders) + app.UseForwardedHeaders(); + + app.UseRouting(); + + if (_settings.EnableCors) + app.UseCors("All"); + + if (_settings.EnableCompression) + app.UseResponseCompression(); + + if (_settings.EnableBasicAuthentication) + app.UseAuthentication(); + + app.UseExceptionHandler(config => + config.Run(async context => + { + var exception = context.Features + .Get() + .Error; + var response = new ErrorModel() + { + Code = exception.HResult, + Name = exception.GetType().Name, + Message = exception.InnerException?.Message ?? exception.Message, + }; + RestServerMiddleware.SetServerInfomationHeader(context.Response); + context.Response.StatusCode = 400; + await context.Response.WriteAsJsonAsync(response); + })); + + if (_settings.EnableSwagger) + { + app.UseSwagger(); + //app.UseSwaggerUI(options => options.DefaultModelsExpandDepth(-1)); + app.UseSwaggerUI(options => + { + var apiVersionDescriptionProvider = app.ApplicationServices.GetRequiredService(); + foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions) + { + options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant()); + } + }); + } + + app.UseMvc(); + }) + .Build(); + _host.Start(); + } + } +} diff --git a/src/RestServer/Tokens/NEP11Token.cs b/src/RestServer/Tokens/NEP11Token.cs new file mode 100644 index 000000000..5d52506c3 --- /dev/null +++ b/src/RestServer/Tokens/NEP11Token.cs @@ -0,0 +1,178 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Persistence; +using Neo.Plugins.RestServer.Helpers; +using Neo.SmartContract; +using Neo.SmartContract.Iterators; +using Neo.SmartContract.Native; +using Neo.VM; +using Neo.VM.Types; +using System.Numerics; + +namespace Neo.Plugins.RestServer.Tokens +{ + internal class NEP11Token + { + public UInt160 ScriptHash { get; private set; } + public string Name { get; private set; } + public string Symbol { get; private set; } + public byte Decimals { get; private set; } + + private readonly NeoSystem _neosystem; + private readonly DataCache _snapshot; + private readonly ContractState _contract; + + public NEP11Token( + NeoSystem neoSystem, + UInt160 scriptHash) : this(neoSystem, null, scriptHash) { } + + public NEP11Token( + NeoSystem neoSystem, + DataCache snapshot, + UInt160 scriptHash) + { + ArgumentNullException.ThrowIfNull(neoSystem, nameof(neoSystem)); + ArgumentNullException.ThrowIfNull(scriptHash, nameof(scriptHash)); + _neosystem = neoSystem; + _snapshot = snapshot ?? _neosystem.GetSnapshot(); + _contract = NativeContract.ContractManagement.GetContract(_snapshot, scriptHash) ?? throw new ArgumentException(null, nameof(scriptHash)); + if (ContractHelper.IsNep11Supported(_contract) == false) + throw new NotSupportedException(nameof(scriptHash)); + Name = _contract.Manifest.Name; + ScriptHash = scriptHash; + Initialize(); + } + + private void Initialize() + { + byte[] scriptBytes; + using var sb = new ScriptBuilder(); + sb.EmitDynamicCall(_contract.Hash, "decimals", CallFlags.ReadOnly); + sb.EmitDynamicCall(_contract.Hash, "symbol", CallFlags.ReadOnly); + scriptBytes = sb.ToArray(); + + using var appEngine = ApplicationEngine.Run(scriptBytes, _snapshot, settings: _neosystem.Settings, gas: RestServerSettings.Current.MaxGasInvoke); + if (appEngine.State != VMState.HALT) + throw new NotSupportedException(nameof(ScriptHash)); + + Symbol = appEngine.ResultStack.Pop().GetString(); + Decimals = (byte)appEngine.ResultStack.Pop().GetInteger(); + } + + public BigDecimal TotalSupply() + { + if (ContractHelper.GetContractMethod(_snapshot, ScriptHash, "totalSupply", 0) == null) + throw new NotSupportedException(nameof(ScriptHash)); + if (ScriptHelper.InvokeMethod(_neosystem.Settings, _snapshot, ScriptHash, "totalSupply", out var results)) + return new(results[0].GetInteger(), Decimals); + return new(BigInteger.Zero, Decimals); + } + + public BigDecimal BalanceOf(UInt160 owner) + { + if (ContractHelper.GetContractMethod(_snapshot, ScriptHash, "balanceOf", 1) == null) + throw new NotSupportedException(nameof(ScriptHash)); + if (ScriptHelper.InvokeMethod(_neosystem.Settings, _snapshot, ScriptHash, "balanceOf", out var results, owner)) + return new(results[0].GetInteger(), Decimals); + return new(BigInteger.Zero, Decimals); + } + + public BigDecimal BalanceOf(UInt160 owner, byte[] tokenId) + { + if (Decimals == 0) + throw new InvalidOperationException(); + if (ContractHelper.GetContractMethod(_snapshot, ScriptHash, "balanceOf", 2) == null) + throw new NotSupportedException(nameof(ScriptHash)); + ArgumentNullException.ThrowIfNull(tokenId, nameof(tokenId)); + if (tokenId.Length > 64) + throw new ArgumentOutOfRangeException(nameof(tokenId)); + if (ScriptHelper.InvokeMethod(_neosystem.Settings, _snapshot, ScriptHash, "balanceOf", out var results, owner, tokenId)) + return new(results[0].GetInteger(), Decimals); + return new(BigInteger.Zero, Decimals); + } + + public IEnumerable TokensOf(UInt160 owner) + { + if (ContractHelper.GetContractMethod(_snapshot, ScriptHash, "tokensOf", 1) == null) + throw new NotSupportedException(nameof(ScriptHash)); + if (ScriptHelper.InvokeMethod(_neosystem.Settings, _snapshot, ScriptHash, "tokensOf", out var results, owner)) + { + if (results[0].GetInterface() is IIterator iterator) + { + var refCounter = new ReferenceCounter(); + while (iterator.Next()) + yield return iterator.Value(refCounter).GetSpan().ToArray(); + } + } + } + + public UInt160[] OwnerOf(byte[] tokenId) + { + if (ContractHelper.GetContractMethod(_snapshot, ScriptHash, "ownerOf", 1) == null) + throw new NotSupportedException(nameof(ScriptHash)); + ArgumentNullException.ThrowIfNull(tokenId, nameof(tokenId)); + if (tokenId.Length > 64) + throw new ArgumentOutOfRangeException(nameof(tokenId)); + if (Decimals == 0) + { + if (ScriptHelper.InvokeMethod(_neosystem.Settings, _snapshot, ScriptHash, "ownerOf", out var results, tokenId)) + return new[] { new UInt160(results[0].GetSpan()) }; + } + else if (Decimals > 0) + { + if (ScriptHelper.InvokeMethod(_neosystem.Settings, _snapshot, ScriptHash, "ownerOf", out var results, tokenId)) + { + if (results[0].GetInterface() is IIterator iterator) + { + var refCounter = new ReferenceCounter(); + var lstOwners = new List(); + while (iterator.Next()) + lstOwners.Add(new UInt160(iterator.Value(refCounter).GetSpan())); + return lstOwners.ToArray(); + } + } + } + return System.Array.Empty(); + } + + public IEnumerable Tokens() + { + if (ContractHelper.GetContractMethod(_snapshot, ScriptHash, "tokens", 0) == null) + throw new NotImplementedException(); + if (ScriptHelper.InvokeMethod(_neosystem.Settings, _snapshot, ScriptHash, "tokens", out var results)) + { + if (results[0].GetInterface() is IIterator iterator) + { + var refCounter = new ReferenceCounter(); + while (iterator.Next()) + yield return iterator.Value(refCounter).GetSpan().ToArray(); + } + } + } + + public IReadOnlyDictionary Properties(byte[] tokenId) + { + ArgumentNullException.ThrowIfNull(tokenId, nameof(tokenId)); + if (ContractHelper.GetContractMethod(_snapshot, ScriptHash, "properties", 1) == null) + throw new NotImplementedException(); + if (tokenId.Length > 64) + throw new ArgumentOutOfRangeException(nameof(tokenId)); + if (ScriptHelper.InvokeMethod(_neosystem.Settings, _snapshot, ScriptHash, "properties", out var results, tokenId)) + { + if (results[0] is Map map) + { + return map.ToDictionary(key => key.Key.GetString(), value => value.Value); + } + } + return default; + } + } +} diff --git a/src/RestServer/Tokens/NEP17Token.cs b/src/RestServer/Tokens/NEP17Token.cs new file mode 100644 index 000000000..e0561afdc --- /dev/null +++ b/src/RestServer/Tokens/NEP17Token.cs @@ -0,0 +1,75 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Persistence; +using Neo.Plugins.RestServer.Helpers; +using Neo.SmartContract; +using Neo.SmartContract.Native; +using Neo.VM; +using System.Numerics; + +namespace Neo.Plugins.RestServer.Tokens +{ + internal class NEP17Token + { + public UInt160 ScriptHash { get; private init; } + public string Name { get; private init; } + public string Symbol { get; private init; } + public byte Decimals { get; private init; } + + private readonly NeoSystem _neosystem; + private readonly DataCache _datacache; + + public NEP17Token( + NeoSystem neoSystem, + UInt160 scriptHash, + DataCache snapshot = null) + { + _datacache = snapshot ?? neoSystem.GetSnapshot(); + var contractState = NativeContract.ContractManagement.GetContract(_datacache, scriptHash) ?? throw new ArgumentException(null, nameof(scriptHash)); + if (ContractHelper.IsNep17Supported(contractState) == false) + throw new NotSupportedException(nameof(scriptHash)); + byte[] script; + using (var sb = new ScriptBuilder()) + { + sb.EmitDynamicCall(scriptHash, "decimals", CallFlags.ReadOnly); + sb.EmitDynamicCall(scriptHash, "symbol", CallFlags.ReadOnly); + script = sb.ToArray(); + } + using var engine = ApplicationEngine.Run(script, _datacache, settings: neoSystem.Settings, gas: RestServerSettings.Current.MaxGasInvoke); + if (engine.State != VMState.HALT) + throw new NotSupportedException(nameof(scriptHash)); + + _neosystem = neoSystem; + ScriptHash = scriptHash; + Name = contractState.Manifest.Name; + Symbol = engine.ResultStack.Pop().GetString(); + Decimals = (byte)engine.ResultStack.Pop().GetInteger(); + } + + public BigDecimal BalanceOf(UInt160 address) + { + if (ContractHelper.GetContractMethod(_datacache, ScriptHash, "balanceOf", 1) == null) + throw new NotSupportedException(nameof(ScriptHash)); + if (ScriptHelper.InvokeMethod(_neosystem.Settings, _datacache, ScriptHash, "balanceOf", out var result, address)) + return new BigDecimal(result[0].GetInteger(), Decimals); + return new BigDecimal(BigInteger.Zero, Decimals); + } + + public BigDecimal TotalSupply() + { + if (ContractHelper.GetContractMethod(_datacache, ScriptHash, "totalSupply", 0) == null) + throw new NotSupportedException(nameof(ScriptHash)); + if (ScriptHelper.InvokeMethod(_neosystem.Settings, _datacache, ScriptHash, "totalSupply", out var result)) + return new BigDecimal(result[0].GetInteger(), Decimals); + return new BigDecimal(BigInteger.Zero, Decimals); + } + } +} diff --git a/src/RestServer/WalletSessionManager.cs b/src/RestServer/WalletSessionManager.cs new file mode 100644 index 000000000..967863666 --- /dev/null +++ b/src/RestServer/WalletSessionManager.cs @@ -0,0 +1,54 @@ +// Copyright (C) 2015-2023 The Neo Project. +// +// The Neo.Plugins.RestServer 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.Wallets; +using System.Collections.Concurrent; + +namespace Neo.Plugins.RestServer +{ + public class WalletSessionManager : ConcurrentDictionary + { + private readonly PeriodicTimer _timer; + + public WalletSessionManager() + { + _timer = new(TimeSpan.FromSeconds(1)); + _ = Task.Run(SessionTimeout); + } + + private async Task SessionTimeout() + { + while (await _timer.WaitForNextTickAsync()) + { + var killAll = this.Where(w => w.Value.Expires <= DateTime.Now) + .Select(s => Task.Run(() => + { + TryRemove(s); + })); + await Task.WhenAll(killAll); + } + } + } + + public class WalletSession + { + public Wallet Wallet { get; private init; } + public DateTime Expires { get; private set; } + + public WalletSession(Wallet wallet) + { + Wallet = wallet; + ResetExpiration(); + } + + public void ResetExpiration() => + Expires = DateTime.Now.AddSeconds(RestServerSettings.Current.WalletSessionTimeout); + } +} diff --git a/src/RestServer/config.json b/src/RestServer/config.json new file mode 100644 index 000000000..de8eb9599 --- /dev/null +++ b/src/RestServer/config.json @@ -0,0 +1,27 @@ +{ + "PluginConfiguration": { + "Network": 860833102, + "BindAddress": "127.0.0.1", + "Port": 10339, + "KeepAliveTimeout": 120, + "SslCertFile": "", + "SslCertPassword": "", + "TrustedAuthorities": [], // Example: "aec13cdd5ea6a3998aec14ac331ad96bedbb770f" (Thumbprint) + "EnableBasicAuthentication": false, + "RestUser": "", + "RestPass": "", + "EnableCors": true, + "AllowOrigins": [], // Example: "http://www.example.com" + "DisableControllers": [ "WalletController" ], + "EnableCompression": true, + "CompressionLevel": "SmallestSize", // "Fastest" or "Optimal" or "NoCompression" or "SmallestSize" + "EnableForwardedHeaders": false, + "EnableSwagger": true, + "MaxPageSize": 50, + "MaxConcurrentConnections": 40, + "MaxTransactionFee": 10000000, + "MaxGasInvoke": 20000000, + "MaxTransactionSize": 1024, + "WalletSessionTimeout": 120 + } +} From 83372022c984c71ddbb2b0df64a83e16c6cfc1dc Mon Sep 17 00:00:00 2001 From: Fernando Diaz Toledano Date: Wed, 8 Nov 2023 09:02:55 +0100 Subject: [PATCH 13/30] Revert "Add Rest Web Server `WIP` (#810)" This reverts commit e9d8683360ae968a79ad4e3a70e95fac27584938. --- docs/RestServer/Addons.md | 108 --- docs/RestServer/ConfigFile.md | 56 -- docs/RestServer/README.md | 136 ---- neo-modules.sln | 7 - .../BasicAuthenticationHandler.cs | 62 -- src/RestServer/Binder/UInt160Binder.cs | 47 -- .../Binder/UInt160BinderProvider.cs | 33 - .../Controllers/v1/ContractsController.cs | 214 ------ .../Controllers/v1/LedgerController.cs | 389 ----------- .../Controllers/v1/NodeController.cs | 86 --- .../Controllers/v1/TokensController.cs | 304 --------- .../Controllers/v1/UtilsController.cs | 106 --- .../Controllers/v1/WalletController.cs | 646 ------------------ .../Exceptions/AddressFormatException.cs | 18 - .../Exceptions/ApplicationEngineException.cs | 18 - .../Exceptions/BlockNotFoundException.cs | 18 - .../Exceptions/ContractNotFoundException.cs | 18 - .../InvalidParameterRangeException.cs | 18 - .../JsonPropertyNullOrEmptyException.cs | 19 - .../Exceptions/Nep11NotSupportedException.cs | 18 - .../Exceptions/Nep17NotSupportedException.cs | 18 - src/RestServer/Exceptions/NodeException.cs | 18 - .../Exceptions/NodeNetworkException.cs | 18 - .../QueryParameterNotFoundException.cs | 18 - src/RestServer/Exceptions/RestErrorCodes.cs | 19 - .../Exceptions/ScriptHashFormatException.cs | 18 - .../TransactionNotFoundException.cs | 18 - .../Exceptions/UInt256FormatException.cs | 18 - src/RestServer/Exceptions/WalletException.cs | 18 - .../WalletInsufficientFundsException.cs | 18 - .../Exceptions/WalletOpenException.cs | 19 - .../Exceptions/WalletSessionException.cs | 18 - .../Extensions/LedgerContractExtensions.cs | 142 ---- src/RestServer/Extensions/ModelExtensions.cs | 99 --- .../Extensions/UInt160Extensions.cs | 27 - src/RestServer/Helpers/ContractHelper.cs | 58 -- src/RestServer/Helpers/ScriptHelper.cs | 59 -- .../Middleware/RestServerMiddleware.cs | 43 -- .../Models/Blockchain/AccountDetails.cs | 33 - src/RestServer/Models/CountModel.cs | 21 - src/RestServer/Models/Error/ErrorModel.cs | 32 - .../Error/ParameterFormatExceptionModel.cs | 28 - src/RestServer/Models/ExecutionEngineModel.cs | 49 -- .../Models/Ledger/MemoryPoolCountModel.cs | 31 - src/RestServer/Models/Node/PluginModel.cs | 31 - .../Models/Node/ProtocolSettingsModel.cs | 40 -- src/RestServer/Models/Node/RemoteNodeModel.cs | 36 - .../Models/Token/NEP11TokenModel.cs | 19 - .../Models/Token/NEP17TokenModel.cs | 23 - .../Models/Token/TokenBalanceModel.cs | 24 - .../Models/Utils/UtilsAddressIsValidModel.cs | 11 - .../Models/Utils/UtilsAddressModel.cs | 21 - .../Models/Utils/UtilsScriptHashModel.cs | 21 - .../Wallet/WalletAccountBalanceModel.cs | 26 - .../Models/Wallet/WalletAddressModel.cs | 51 -- .../Models/Wallet/WalletAssetModel.cs | 54 -- .../Wallet/WalletChangePasswordModel.cs | 40 -- .../Models/Wallet/WalletCreateAccountModel.cs | 24 - .../Models/Wallet/WalletCreateModel.cs | 45 -- .../Models/Wallet/WalletExportKeyModel.cs | 34 - .../Models/Wallet/WalletImportKey.cs | 27 - .../WalletImportMultiSigAddressModel.cs | 32 - .../Models/Wallet/WalletKeyModel.cs | 33 - .../Wallet/WalletMultiSignContractModel.cs | 34 - .../Models/Wallet/WalletOpenModel.cs | 33 - .../Models/Wallet/WalletSendModel.cs | 58 -- .../Models/Wallet/WalletSessionModel.cs | 24 - .../Wallet/WalletTransactionScriptModel.cs | 35 - .../Json/BigDecimalJsonConverter.cs | 48 -- .../Json/BlockHeaderJsonConverter.cs | 32 - .../Newtonsoft/Json/BlockJsonConverter.cs | 30 - .../Json/ContractAbiJsonConverter.cs | 28 - .../ContractEventDescriptorJsonConverter.cs | 28 - .../Json/ContractGroupJsonConverter.cs | 28 - .../Newtonsoft/Json/ContractJsonConverter.cs | 28 - .../Json/ContractManifestJsonConverter.cs | 28 - .../Json/ContractMethodJsonConverter.cs | 28 - .../ContractMethodParametersJsonConverter.cs | 27 - ...ontractParameterDefinitionJsonConverter.cs | 28 - .../Json/ContractParameterJsonConverter.cs | 33 - ...ntractPermissionDescriptorJsonConverter.cs | 28 - .../Json/ContractPermissionJsonConverter.cs | 28 - .../Newtonsoft/Json/ECPointJsonConverter.cs | 37 - .../Newtonsoft/Json/GuidJsonConverter.cs | 27 - .../Json/InteropInterfaceJsonConverter.cs | 31 - .../Json/MethodTokenJsonConverter.cs | 28 - .../Newtonsoft/Json/NefFileJsonConverter.cs | 24 - .../Json/ReadOnlyMemoryBytesJsonConverter.cs | 29 - .../Newtonsoft/Json/SignerJsonConverter.cs | 29 - .../Newtonsoft/Json/StackItemJsonConverter.cs | 33 - .../Json/TransactionAttributeJsonConverter.cs | 28 - .../Json/TransactionJsonConverter.cs | 28 - .../Newtonsoft/Json/UInt160JsonConverter.cs | 39 -- .../Newtonsoft/Json/UInt256JsonConverter.cs | 36 - .../Newtonsoft/Json/VmArrayJsonConverter.cs | 31 - .../Newtonsoft/Json/VmBooleanJsonConverter.cs | 31 - .../Newtonsoft/Json/VmBufferJsonConverter.cs | 31 - .../Json/VmByteStringJsonConverter.cs | 31 - .../Newtonsoft/Json/VmIntegerJsonConverter.cs | 31 - .../Newtonsoft/Json/VmMapJsonConverter.cs | 31 - .../Newtonsoft/Json/VmNullJsonConverter.cs | 31 - .../Newtonsoft/Json/VmPointerJsonConverter.cs | 31 - .../Newtonsoft/Json/VmStructJsonConverter.cs | 31 - .../Json/WitnessConditionJsonConverter.cs | 95 --- .../Newtonsoft/Json/WitnessJsonConverter.cs | 32 - .../Json/WitnessRuleJsonConverter.cs | 24 - .../BlackListControllerFeatureProvider.cs | 35 - src/RestServer/RestServer.csproj | 25 - src/RestServer/RestServerPlugin.Console.cs | 131 ---- src/RestServer/RestServerPlugin.cs | 62 -- src/RestServer/RestServerSettings.cs | 162 ----- src/RestServer/RestServerUtility.JTokens.cs | 302 -------- src/RestServer/RestServerUtility.cs | 346 ---------- src/RestServer/RestWebServer.cs | 417 ----------- src/RestServer/Tokens/NEP11Token.cs | 178 ----- src/RestServer/Tokens/NEP17Token.cs | 75 -- src/RestServer/WalletSessionManager.cs | 54 -- src/RestServer/config.json | 27 - 118 files changed, 6972 deletions(-) delete mode 100644 docs/RestServer/Addons.md delete mode 100644 docs/RestServer/ConfigFile.md delete mode 100644 docs/RestServer/README.md delete mode 100644 src/RestServer/Authentication/BasicAuthenticationHandler.cs delete mode 100644 src/RestServer/Binder/UInt160Binder.cs delete mode 100644 src/RestServer/Binder/UInt160BinderProvider.cs delete mode 100644 src/RestServer/Controllers/v1/ContractsController.cs delete mode 100644 src/RestServer/Controllers/v1/LedgerController.cs delete mode 100644 src/RestServer/Controllers/v1/NodeController.cs delete mode 100644 src/RestServer/Controllers/v1/TokensController.cs delete mode 100644 src/RestServer/Controllers/v1/UtilsController.cs delete mode 100644 src/RestServer/Controllers/v1/WalletController.cs delete mode 100644 src/RestServer/Exceptions/AddressFormatException.cs delete mode 100644 src/RestServer/Exceptions/ApplicationEngineException.cs delete mode 100644 src/RestServer/Exceptions/BlockNotFoundException.cs delete mode 100644 src/RestServer/Exceptions/ContractNotFoundException.cs delete mode 100644 src/RestServer/Exceptions/InvalidParameterRangeException.cs delete mode 100644 src/RestServer/Exceptions/JsonPropertyNullOrEmptyException.cs delete mode 100644 src/RestServer/Exceptions/Nep11NotSupportedException.cs delete mode 100644 src/RestServer/Exceptions/Nep17NotSupportedException.cs delete mode 100644 src/RestServer/Exceptions/NodeException.cs delete mode 100644 src/RestServer/Exceptions/NodeNetworkException.cs delete mode 100644 src/RestServer/Exceptions/QueryParameterNotFoundException.cs delete mode 100644 src/RestServer/Exceptions/RestErrorCodes.cs delete mode 100644 src/RestServer/Exceptions/ScriptHashFormatException.cs delete mode 100644 src/RestServer/Exceptions/TransactionNotFoundException.cs delete mode 100644 src/RestServer/Exceptions/UInt256FormatException.cs delete mode 100644 src/RestServer/Exceptions/WalletException.cs delete mode 100644 src/RestServer/Exceptions/WalletInsufficientFundsException.cs delete mode 100644 src/RestServer/Exceptions/WalletOpenException.cs delete mode 100644 src/RestServer/Exceptions/WalletSessionException.cs delete mode 100644 src/RestServer/Extensions/LedgerContractExtensions.cs delete mode 100644 src/RestServer/Extensions/ModelExtensions.cs delete mode 100644 src/RestServer/Extensions/UInt160Extensions.cs delete mode 100644 src/RestServer/Helpers/ContractHelper.cs delete mode 100644 src/RestServer/Helpers/ScriptHelper.cs delete mode 100644 src/RestServer/Middleware/RestServerMiddleware.cs delete mode 100644 src/RestServer/Models/Blockchain/AccountDetails.cs delete mode 100644 src/RestServer/Models/CountModel.cs delete mode 100644 src/RestServer/Models/Error/ErrorModel.cs delete mode 100644 src/RestServer/Models/Error/ParameterFormatExceptionModel.cs delete mode 100644 src/RestServer/Models/ExecutionEngineModel.cs delete mode 100644 src/RestServer/Models/Ledger/MemoryPoolCountModel.cs delete mode 100644 src/RestServer/Models/Node/PluginModel.cs delete mode 100644 src/RestServer/Models/Node/ProtocolSettingsModel.cs delete mode 100644 src/RestServer/Models/Node/RemoteNodeModel.cs delete mode 100644 src/RestServer/Models/Token/NEP11TokenModel.cs delete mode 100644 src/RestServer/Models/Token/NEP17TokenModel.cs delete mode 100644 src/RestServer/Models/Token/TokenBalanceModel.cs delete mode 100644 src/RestServer/Models/Utils/UtilsAddressIsValidModel.cs delete mode 100644 src/RestServer/Models/Utils/UtilsAddressModel.cs delete mode 100644 src/RestServer/Models/Utils/UtilsScriptHashModel.cs delete mode 100644 src/RestServer/Models/Wallet/WalletAccountBalanceModel.cs delete mode 100644 src/RestServer/Models/Wallet/WalletAddressModel.cs delete mode 100644 src/RestServer/Models/Wallet/WalletAssetModel.cs delete mode 100644 src/RestServer/Models/Wallet/WalletChangePasswordModel.cs delete mode 100644 src/RestServer/Models/Wallet/WalletCreateAccountModel.cs delete mode 100644 src/RestServer/Models/Wallet/WalletCreateModel.cs delete mode 100644 src/RestServer/Models/Wallet/WalletExportKeyModel.cs delete mode 100644 src/RestServer/Models/Wallet/WalletImportKey.cs delete mode 100644 src/RestServer/Models/Wallet/WalletImportMultiSigAddressModel.cs delete mode 100644 src/RestServer/Models/Wallet/WalletKeyModel.cs delete mode 100644 src/RestServer/Models/Wallet/WalletMultiSignContractModel.cs delete mode 100644 src/RestServer/Models/Wallet/WalletOpenModel.cs delete mode 100644 src/RestServer/Models/Wallet/WalletSendModel.cs delete mode 100644 src/RestServer/Models/Wallet/WalletSessionModel.cs delete mode 100644 src/RestServer/Models/Wallet/WalletTransactionScriptModel.cs delete mode 100644 src/RestServer/Newtonsoft/Json/BigDecimalJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/BlockHeaderJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/BlockJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/ContractAbiJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/ContractEventDescriptorJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/ContractGroupJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/ContractJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/ContractManifestJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/ContractMethodJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/ContractMethodParametersJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/ContractParameterDefinitionJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/ContractParameterJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/ContractPermissionDescriptorJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/ContractPermissionJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/ECPointJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/GuidJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/InteropInterfaceJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/MethodTokenJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/NefFileJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/ReadOnlyMemoryBytesJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/SignerJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/StackItemJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/TransactionAttributeJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/TransactionJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/UInt160JsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/UInt256JsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/VmArrayJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/VmBooleanJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/VmBufferJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/VmByteStringJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/VmIntegerJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/VmMapJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/VmNullJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/VmPointerJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/VmStructJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/WitnessConditionJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/WitnessJsonConverter.cs delete mode 100644 src/RestServer/Newtonsoft/Json/WitnessRuleJsonConverter.cs delete mode 100644 src/RestServer/Providers/BlackListControllerFeatureProvider.cs delete mode 100644 src/RestServer/RestServer.csproj delete mode 100644 src/RestServer/RestServerPlugin.Console.cs delete mode 100644 src/RestServer/RestServerPlugin.cs delete mode 100644 src/RestServer/RestServerSettings.cs delete mode 100644 src/RestServer/RestServerUtility.JTokens.cs delete mode 100644 src/RestServer/RestServerUtility.cs delete mode 100644 src/RestServer/RestWebServer.cs delete mode 100644 src/RestServer/Tokens/NEP11Token.cs delete mode 100644 src/RestServer/Tokens/NEP17Token.cs delete mode 100644 src/RestServer/WalletSessionManager.cs delete mode 100644 src/RestServer/config.json diff --git a/docs/RestServer/Addons.md b/docs/RestServer/Addons.md deleted file mode 100644 index 07be39f4b..000000000 --- a/docs/RestServer/Addons.md +++ /dev/null @@ -1,108 +0,0 @@ -## RestServer Plugin -In this secion of you will learn how to make a `neo-cli` plugin that integrates with `RestServer` -plugin. Lets take a look at [Example Plugin](/examples/RestServerPlugin). - -- No reference to `RestServer` is reqired. -- Requires DotNet 7.0 - -## Folder Structure -```bash -Project -├── Controllers -│ └── ExampleController.cs -├── ExamplePlugin.cs -├── ExamplePlugin.csproj -├── Exceptions -│ └── CustomException.cs -└── Models - └── ErrorModel.cs -``` -The only thing that is important here is the `controllers` folder. This folder is required for the `RestServer` -plugin to register the controllers in its web server. This location is where you put all your controllers. - -## Controllers -The `controller` class is the same as ASP.Net Core's. Controllers must have their attribute set -as `[ApiController]` and inherent from `ControllerBase`. - -## Swagger Controller -A `Swagger` controller uses special attributes that are set on your controller's class. - -**Controller Class Attributes** -- `[Produces(MediaTypeNames.Application.Json)]` (_Required_) -- `[Consumes(MediaTypeNames.Application.Json)]` (_Required_) -- `[ApiExplorerSettings(GroupName = "v1")]` - - **GroupName** - _is which version of the API you are targeting._ -- `[ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(ErrorModel))]` (_Required_) - - **Type** - _Must have a base class of [error](#error-class)._ - -## Error Class -Needs to be the same as `RestServer` of else there will be some inconsistencies -with end users not knowing which type to use. This class can be `public` or `internal`. -Properties `Code`, `Name` and `Message` values can be whatever you desire. - -**Model** -```csharp -public class ErrorModel -{ - public int Code { get; set; }; - public string Name { get; set; }; - public string Message { get; set; }; -} -``` - -## Controller Actions -Controller actions need to have special attributes as well as code comments. - -- `[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(string))]` - -HTTP status code `200 (OK)` is required with return type defined. You can use more than one attribute. One per HTTP status code. - -### Action Example -```csharp -[HttpGet("contracts/{hash:required}/sayHello", Name = "GetSayHello")] -[ProducesResponseType(StatusCodes.Status204NoContent)] -[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(string))] -public IActionResult GetSayHello( - [FromRoute(Name = "hash")] - UInt160 scripthash) -{ - if (scripthash == UInt160.Zero) - return NoContent(); - return Ok($"Hello, {scripthash}"); -} -``` -Notice that the _above_ example also returns with HTTP status code of `204 No Content`. -This action `route` also extends the `contracts` API. Adding method `sayHello`. Routes -can be what you like as well. But if you want to extend on any existing controller you -must use existing routes paths. - -### Path(s) -- `/api/v1/contracts/` -- `/api/v1/ledger/` -- `/api/v1/node/` -- `/api/v1/tokens` -- `/api/v1/Utils/` - -### Excluded Path(s) -- `/api/v1/wallet/` - -_for security reasons_. - -### Code Comments for Swagger -```csharp -/// -/// -/// -/// -/// -/// Successful -/// An error occurred. See Response for details. -``` - -Also note that you need to have `GenerateDocumentationFile` enabled in your -`.csproj` file. The `xml` file that is generated; in our case would be `RestServerPlugin.xml`. -This file gets put in same directory `Plugins/RestServerPlugin/` which is in the root of `neo-node` -executable folder. Where you will see `neo-cli.exe`. - -File `RestServerPlugin.xml` will get added to `Swagger` automatically by the `RestServer` -plugin. diff --git a/docs/RestServer/ConfigFile.md b/docs/RestServer/ConfigFile.md deleted file mode 100644 index 303a920f1..000000000 --- a/docs/RestServer/ConfigFile.md +++ /dev/null @@ -1,56 +0,0 @@ -## Table - -| Name | Type | Description | -| :--- | :---: | :--- | -|**Network**|_uint32_|_Network you would like the `RestServer` to be enabled on._| -|**BindAddress**|_string_|_Ip address of the interface you want to bind too._| -|**Port**|_uint32_|_Port number to bind too._| -|**KeepAliveTimeout**|_uint32_|_Time to keep the request alive, in seconds._| -|**SslCertFile**|_string_|_Is the path and file name of a certificate file, relative to the directory that contains the node's executable files._| -|**SslCertPassword**|_string_|_Is the password required to access the `X.509` certificate data._| -|**TrustedAuthorities**|_StringArray_|_Tumbprints of the of the last certificate authority in the chain._| -|**EnableBasicAuthentication**|_boolean_|_enables basic authentication._| -|**RestUser**|_string_|_Basic authentication's `username`._| -|**RestPass**|_string_|_Basic authentication's `password`._| -|**EnableCors**|_boolean_|_Enables Cross-origin resource sharing (`CORS`). Note by default it enables `*` any origin._| -|**AllowOrigins**|_StringArray_|_A list of the origins to allow. Note needs to add origins for basic auth to work with `CORS`._| -|**DisableControllers**|_StringArray_|_A list of `controllers` to be disabled. Requires restart of the node, if changed._| -|**EnableCompression**|_boolean_|_Enables `GZip` data compression._| -|**CompressionLevel**|_enum_|_Compression level. Values can be `Fastest`, `Optimal`, `NoCompression` or `SmallestSize`_| -|**EnableForwardedHeaders**|_boolean_|_Enables response/request headers for proxy forwarding. (data center usage)_| -|**EnableSwagger**|_boolean_|_Enables `Swagger` with `Swagger UI` for the rest services._| -|**MaxPageSize**|_uint32_|_Max page size for searches on `Ledger`/`Contracts` route._| -|**MaxConcurrentConnections**|_int64_|_Max allow concurrent HTTP connections._| -|**MaxTransactionFee**|_int64_|_Max transaction fee for `wallet` transfers._| -|**MaxInvokeGas**|_int64_|_Max gas to be invoked on the `Neo` virtual machine._| -|**WalletSessionTimeout**|_uint32_|_When `wallet` session expires, in seconds._| - -## Default "Config.json" file -```json -{ - "PluginConfiguration": { - "Network": 860833102, - "BindAddress": "127.0.0.1", - "Port": 10339, - "KeepAliveTimeout": 120, - "SslCertFile": "", - "SslCertPassword": "", - "TrustedAuthorities": [], - "EnableBasicAuthentication": false, - "RestUser": "", - "RestPass": "", - "EnableCors": true, - "AllowOrigins": [], - "DisableControllers": [ "WalletController" ], - "EnableCompression": true, - "CompressionLevel": "SmallestSize", - "EnableForwardedHeaders": false, - "EnableSwagger": true, - "MaxPageSize": 50, - "MaxConcurrentConnections": 40, - "MaxTransactionFee": 10000000, - "MaxInvokeGas": 20000000, - "WalletSessionTimeout": 120 - } -} -``` diff --git a/docs/RestServer/README.md b/docs/RestServer/README.md deleted file mode 100644 index 05b068776..000000000 --- a/docs/RestServer/README.md +++ /dev/null @@ -1,136 +0,0 @@ -## RestServer -In this section you will learn about `RestServer` plugin and how it works. - -See [config.json](ConfigFile.md) for information about the configurations. - -## Dependencies -- **Microsoft.AspNetCore.JsonPatch.dll** `Required` -- **Microsoft.AspNetCore.Mvc.NewtonsoftJson.dll** `Required` -- **Microsoft.OpenApi.dll** `Swagger` -- **Swashbuckle.AspNetCore.Swagger.dll** `Swagger` -- **Swashbuckle.AspNetCore.SwaggerGen.dll** `Swagger` -- **Swashbuckle.AspNetCore.SwaggerUI.dll** `Swagger` -- **Swashbuckle.AspNetCore.Newtonsoft.dll** `Swagger` -- **RestServer.xml** `Swagger UI` - -These files go in the same directory as the `RestServer.dll`. In neo-cli -`plugins/RestServer/` folder. - -## Response Headers -| Name | Value(s) | Description | -| :---: | --- | :--- | -|**server**|_neo-cli/3.6.0 RestServer/3.6.0_|_`neo-cli` and `RestServer` version._| - -Custom headers can be added by [Neo RestServer Plugins](Addons.md). - -## JSON Serializer -`RestServer` uses custom Newtonsoft Json Converters to serialize controller action -responses and `route` parameters. - -**One Way Binding** - `Write` only. -- `Neo.SmartContract.ContractState` -- `Neo.SmartContract.NefFile` -- `Neo.SmartContract.MethodToken` -- `Neo.SmartContract.Native.TrimmedBlock` -- `Neo.SmartContract.Manifest.ContractAbi` -- `Neo.SmartContract.Manifest.ContractGroup` -- `Neo.SmartContract.Manifest.ContractManifest` -- `Neo.SmartContract.Manifest.ContractPermission` -- `Neo.SmartContract.Manifest.ContractPermissionDescriptor` -- `Neo.Network.P2P.Payloads.Block` -- `Neo.Network.P2P.Payloads.Header` -- `Neo.Network.P2P.Payloads.Signer` -- `Neo.Network.P2P.Payloads.TransactionAttribute` -- `Neo.Network.P2P.Payloads.Transaction` -- `Neo.Network.P2P.Payloads.Witness` - -**Two Way Binding** - `Read` & `Write` -- `System.Guid` -- `System.ReadOnlyMemory` -- `Neo.BigDecimal` -- `Neo.UInt160` -- `Neo.UInt256` -- `Neo.Cryptography.ECC.ECPoint` -- `Neo.VM.Types.Array` -- `Neo.VM.Types.Boolean` -- `Neo.VM.Types.Buffer` -- `Neo.VM.Types.ByteString` -- `Neo.VM.Types.Integer` -- `Neo.VM.Types.InteropInterface` -- `Neo.VM.Types.Null` -- `Neo.VM.Types.Map` -- `Neo.VM.Types.Pointer` -- `Neo.VM.Types.StackItem` -- `Neo.VM.Types.Struct` - -## Remote Endpoints -Parametes `{hash}` can be any Neo N3 address or scripthash; `{address}` can be any Neo N3 address **only**; `{number}` and `{index}` can be any _**uint32**_. - -**Parameter Examples** -- `{hash}` - _0xef4073a0f2b305a38ec4050e4d3d28bc40ea63f5_ **or** _NiHURyS83nX2mpxtA7xq84cGxVbHojj5Wc_ -- `{address}` - _NiHURyS83nX2mpxtA7xq84cGxVbHojj5Wc_ -- `{number}` - _1_ -- `{index}` - _2500000_ - -**Paths** -- Utils - - `[GET]` `/api/v1/utils/{hash}/address` - - `[GET]` `/api/v1/utils/{address}/scripthash` - - `[GET]` `/api/v1/utils/{hash}/{address}/validate` -- Node - - `[GET]` `/api/v1/node` - - `[GET]` `/api/v1/node/peers` - - `[GET]` `/api/v1/node/plugins` - - `[GET]` `/api/v1/node/settings` -- Ledger - - `[GET]` `/api/v1/ledger/neo/accounts` - - `[GET]` `/api/v1/ledger/gas/accounts` - - `[GET]` `/api/v1/ledger/blocks?page={number}&size={number}` - - `[GET]` `/api/v1/ledger/blocks/height` - - `[GET]` `/api/v1/ledger/blocks/{index}` - - `[GET]` `/api/v1/ledger/blocks/{index}/header` - - `[GET]` `/api/v1/ledger/blocks/{index}/witness` - - `[GET]` `/api/v1/ledger/blocks/{index}/transactions?page={number}&size={number}` - - `[GET]` `/api/v1/ledger/transactions/{hash}` - - `[GET]` `/api/v1/ledger/transactions/{hash}/witnesses` - - `[GET]` `/api/v1/ledger/transactions/{hash}/signers` - - `[GET]` `/api/v1/ledger/transactions/{hash}/atributes` - - `[GET]` `/api/v1/ledger/memorypool?page={number}&size={number}` - - `[GET]` `/api/v1/ledger/memorypool/verified?page={number}&size={number}` - - `[GET]` `/api/v1/ledger/memorypool/unverified?page={number}&size={number}` - - `[GET]` `/api/v1/ledger/memorypool/count` -- Tokens - - `[GET]` `/api/v1/tokens/balanceof/{address}` - - NFTs - - `[GET]` `/api/v1/tokens/nep-11?page={number}&size={number}` - - `[GET]` `/api/v1/tokens/nep-11/count` - - `[GET]` `/api/v1/tokens/nep-11/{hash}/balanceof/{address}` - - NEP-17 - - `[GET]` `/api/v1/tokens/nep-17?page={number}&size={number}` - - `[GET]` `/api/v1/tokens/nep-17/count` - - `[GET]` `/api/v1/tokens/nep-17/{hash}/balanceof/{address}` -- Contracts - - `[GET]` `/api/v1/contracts?page={number}&size={number}` - - `[GET]` `/api/v1/contracts/count` - - `[GET]` `/api/v1/contracts/{hash}` - - `[GET]` `/api/v1/contracts/{hash}/abi` - - `[GET]` `/api/v1/contracts/{hash}/manifest` - - `[GET]` `/api/v1/contracts/{hash}/nef` - - `[GET]` `/api/v1/contracts/{hash}/storage` -- Wallet - - `[POST]` `/api/v1/wallet/open` - - `[POST]` `/api/v1/wallet/create` - - `[POST]` `/api/v1/wallet/{session}/address/create` - - `[GET]` `/api/v1/wallet/{session}/address/list` - - `[GET]` `/api/v1/wallet/{session}/asset/list` - - `[GET]` `/api/v1/wallet/{session}/balance/list` - - `[POST]` `/api/v1/wallet/{session}/changepassword` - - `[GET]` `/api/v1/wallet/{session}/close` - - `[GET]` `/api/v1/wallet/{session}/delete/{address}` - - `[GET]` `/api/v1/wallet/{session}/export/{address}` - - `[GET]` `/api/v1/wallet/{session}/export` - - `[GET]` `/api/v1/wallet/{session}/gas/unclaimed` - - `[GET]` `/api/v1/wallet/{session}/key/list` - - `[POST]` `/api/v1/wallet/{session}/import` - - `[POST]` `/api/v1/wallet/{session}/import/multisigaddress` - - `[POST]` `/api/v1/wallet/{session}/transfer` diff --git a/neo-modules.sln b/neo-modules.sln index 926fc514a..8a1931586 100644 --- a/neo-modules.sln +++ b/neo-modules.sln @@ -43,8 +43,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SQLiteWallet", "src\SQLiteW EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StorageDumper", "src\StorageDumper\StorageDumper.csproj", "{938D86EA-0F48-436B-9255-4AD9A8E6B9AC}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RestServer", "src\RestServer\RestServer.csproj", "{A893825D-65FF-4FA9-85EF-16F3AC626A29}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -123,10 +121,6 @@ Global {938D86EA-0F48-436B-9255-4AD9A8E6B9AC}.Debug|Any CPU.Build.0 = Debug|Any CPU {938D86EA-0F48-436B-9255-4AD9A8E6B9AC}.Release|Any CPU.ActiveCfg = Release|Any CPU {938D86EA-0F48-436B-9255-4AD9A8E6B9AC}.Release|Any CPU.Build.0 = Release|Any CPU - {A893825D-65FF-4FA9-85EF-16F3AC626A29}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A893825D-65FF-4FA9-85EF-16F3AC626A29}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A893825D-65FF-4FA9-85EF-16F3AC626A29}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A893825D-65FF-4FA9-85EF-16F3AC626A29}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -150,7 +144,6 @@ Global {8D2EE375-2E2D-45FE-A4E9-0254D12C7554} = {59D802AB-C552-422A-B9C3-64D329FBCDCC} {D121D57A-512E-4F74-ADA1-24482BF5C42B} = {97E81C78-1637-481F-9485-DA1225E94C23} {938D86EA-0F48-436B-9255-4AD9A8E6B9AC} = {97E81C78-1637-481F-9485-DA1225E94C23} - {A893825D-65FF-4FA9-85EF-16F3AC626A29} = {97E81C78-1637-481F-9485-DA1225E94C23} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {61D3ADE6-BBFC-402D-AB42-1C71C9F9EDE3} diff --git a/src/RestServer/Authentication/BasicAuthenticationHandler.cs b/src/RestServer/Authentication/BasicAuthenticationHandler.cs deleted file mode 100644 index 17eb614fb..000000000 --- a/src/RestServer/Authentication/BasicAuthenticationHandler.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (C) 2015-2023 neo-restful-plugin. -// -// The RestServer 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 Microsoft.AspNetCore.Authentication; -using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Options; -using Neo.Plugins.RestServer; -using System.Net.Http.Headers; -using System.Security.Claims; -using System.Text; -using System.Text.Encodings.Web; - -namespace RestServer.Authentication -{ - internal class BasicAuthenticationHandler : AuthenticationHandler - { - public BasicAuthenticationHandler( - IOptionsMonitor options, - ILoggerFactory logger, - UrlEncoder encoder, - ISystemClock clock) : base(options, logger, encoder, clock) - { - } - - protected override Task HandleAuthenticateAsync() - { - var authHeader = Request.Headers.Authorization; - if (string.IsNullOrEmpty(authHeader) == false && AuthenticationHeaderValue.TryParse(authHeader, out var authValue)) - { - if (authValue.Scheme.Equals("basic", StringComparison.OrdinalIgnoreCase) && authValue.Parameter != null) - { - try - { - var decodedParams = Encoding.UTF8.GetString(Convert.FromBase64String(authValue.Parameter)); - var creds = decodedParams.Split(':', 2); - if (creds[0] == RestServerSettings.Current.RestUser && creds[1] == RestServerSettings.Current.RestPass) - { - var claims = new[] { new Claim(ClaimTypes.NameIdentifier, creds[0]) }; - var identity = new ClaimsIdentity(claims, Scheme.Name); - var principal = new ClaimsPrincipal(identity); - var ticket = new AuthenticationTicket(principal, Scheme.Name); - - return Task.FromResult(AuthenticateResult.Success(ticket)); - } - - } - catch (FormatException) - { - } - } - } - return Task.FromResult(AuthenticateResult.Fail("Authentication Failed!!!")); - } - } -} diff --git a/src/RestServer/Binder/UInt160Binder.cs b/src/RestServer/Binder/UInt160Binder.cs deleted file mode 100644 index fa72ad595..000000000 --- a/src/RestServer/Binder/UInt160Binder.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 Microsoft.AspNetCore.Mvc.ModelBinding; - -namespace Neo.Plugins.RestServer.Binder -{ - internal class UInt160Binder : IModelBinder - { - - public Task BindModelAsync(ModelBindingContext bindingContext) - { - _ = bindingContext ?? throw new ArgumentNullException(nameof(bindingContext)); - - if (bindingContext.BindingSource == BindingSource.Path || - bindingContext.BindingSource == BindingSource.Query) - { - var modelName = bindingContext.ModelName; - - // Try to fetch the value of the argument by name - var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName); - - if (valueProviderResult == ValueProviderResult.None) - return Task.CompletedTask; - - bindingContext.ModelState.SetModelValue(modelName, valueProviderResult); - - var value = valueProviderResult.FirstValue; - - // Check if the argument value is null or empty - if (string.IsNullOrEmpty(value)) - return Task.CompletedTask; - - var model = RestServerUtility.ConvertToScriptHash(value, RestServerPlugin.NeoSystem.Settings); - bindingContext.Result = ModelBindingResult.Success(model); - } - return Task.CompletedTask; - } - } -} diff --git a/src/RestServer/Binder/UInt160BinderProvider.cs b/src/RestServer/Binder/UInt160BinderProvider.cs deleted file mode 100644 index f2aceeb1e..000000000 --- a/src/RestServer/Binder/UInt160BinderProvider.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 Microsoft.AspNetCore.Mvc.ModelBinding; -using Microsoft.AspNetCore.Mvc.ModelBinding.Binders; - -namespace Neo.Plugins.RestServer.Binder -{ - internal class NeoBinderProvider : IModelBinderProvider - { - public IModelBinder GetBinder(ModelBinderProviderContext context) - { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } - - if (context.Metadata.ModelType == typeof(UInt160)) - { - return new BinderTypeModelBinder(typeof(UInt160Binder)); - } - - return null; - } - } -} diff --git a/src/RestServer/Controllers/v1/ContractsController.cs b/src/RestServer/Controllers/v1/ContractsController.cs deleted file mode 100644 index 9c545da9e..000000000 --- a/src/RestServer/Controllers/v1/ContractsController.cs +++ /dev/null @@ -1,214 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Neo.Plugins.RestServer.Exceptions; -using Neo.Plugins.RestServer.Extensions; -using Neo.Plugins.RestServer.Helpers; -using Neo.Plugins.RestServer.Models; -using Neo.Plugins.RestServer.Models.Error; -using Neo.SmartContract; -using Neo.SmartContract.Manifest; -using Neo.SmartContract.Native; -using System.Net.Mime; - -namespace Neo.Plugins.RestServer.Controllers.v1 -{ - [Route("/api/v{version:apiVersion}/contracts")] - [Produces(MediaTypeNames.Application.Json)] - [Consumes(MediaTypeNames.Application.Json)] - [ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(ErrorModel))] - [ApiVersion("1.0")] - [ApiController] - public class ContractsController : ControllerBase - { - private readonly NeoSystem _neosystem; - - public ContractsController() - { - _neosystem = RestServerPlugin.NeoSystem ?? throw new NodeNetworkException(); - } - - /// - /// Get all the smart contracts from the blockchain. - /// - /// Page - /// Page Size - /// An array of Contract object. - /// No more pages. - /// Successful - /// An error occurred. See Response for details. - [HttpGet(Name = "GetContracts")] - [ProducesResponseType(StatusCodes.Status204NoContent)] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ContractState[]))] - public IActionResult Get( - [FromQuery(Name = "page")] - int skip = 1, - [FromQuery(Name = "size")] - int take = 1) - { - if (skip < 1 || take < 1 || take > RestServerSettings.Current.MaxPageSize) - throw new InvalidParameterRangeException(); - var contracts = NativeContract.ContractManagement.ListContracts(_neosystem.StoreView); - if (contracts.Any() == false) - return NoContent(); - var contractRequestList = contracts.OrderBy(o => o.Manifest.Name).Skip((skip - 1) * take).Take(take); - if (contractRequestList.Any() == false) - return NoContent(); - return Ok(contractRequestList); - } - - /// - /// Gets count of total smart contracts on blockchain. - /// - /// Count Object - /// Successful - /// An error occurred. See Response for details. - [HttpGet("count", Name = "GetContractCount")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CountModel))] - public IActionResult GetCount() - { - var contracts = NativeContract.ContractManagement.ListContracts(_neosystem.StoreView); - return Ok(new CountModel() { Count = contracts.Count() }); - } - - /// - /// Get a smart contract's storage. - /// - /// ScriptHash - /// An array of the Key (Base64) Value (Base64) Pairs objects. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("{hash:required}/storage", Name = "GetContractStorage")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(KeyValuePair, ReadOnlyMemory>[]))] - public IActionResult GetContractStorage( - [FromRoute(Name = "hash")] - UInt160 scripthash) - { - if (NativeContract.IsNative(scripthash)) - return NoContent(); - var contract = NativeContract.ContractManagement.GetContract(_neosystem.StoreView, scripthash); - if (contract == null) - throw new ContractNotFoundException(scripthash); - var contractStorage = contract.GetStorage(_neosystem.StoreView); - return Ok(contractStorage.Select(s => new KeyValuePair, ReadOnlyMemory>(s.key.Key, s.value.Value))); - } - - /// - /// Get a smart contract. - /// - /// ScriptHash - /// Contract Object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("{hash:required}", Name = "GetContract")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ContractState))] - public IActionResult GetByScriptHash( - [FromRoute(Name = "hash")] - UInt160 scripthash) - { - var contracts = NativeContract.ContractManagement.GetContract(_neosystem.StoreView, scripthash); - if (contracts == null) - throw new ContractNotFoundException(scripthash); - return Ok(contracts); - } - - /// - /// Get abi of a smart contract. - /// - /// ScriptHash - /// Contract Abi Object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("{hash:required}/abi", Name = "GetContractAbi")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ContractAbi))] - public IActionResult GetContractAbi( - [FromRoute(Name = "hash")] - UInt160 scripthash) - { - var contracts = NativeContract.ContractManagement.GetContract(_neosystem.StoreView, scripthash); - if (contracts == null) - throw new ContractNotFoundException(scripthash); - return Ok(contracts.Manifest.Abi); - } - /// - /// Get manifest of a smart contract. - /// - /// ScriptHash - /// Contract Manifest object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("{hash:required}/manifest", Name = "GetContractManifest")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ContractManifest))] - public IActionResult GetContractManifest( - [FromRoute(Name = "hash")] - UInt160 scripthash) - { - var contracts = NativeContract.ContractManagement.GetContract(_neosystem.StoreView, scripthash); - if (contracts == null) - throw new ContractNotFoundException(scripthash); - return Ok(contracts.Manifest); - } - /// - /// Get nef of a smart contract. - /// - /// ScriptHash - /// Contract Nef object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("{hash:required}/nef", Name = "GetContractNefFile")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(NefFile))] - public IActionResult GetContractNef( - [FromRoute(Name = "hash")] - UInt160 scripthash) - { - var contracts = NativeContract.ContractManagement.GetContract(_neosystem.StoreView, scripthash); - if (contracts == null) - throw new ContractNotFoundException(scripthash); - return Ok(contracts.Nef); - } - - /// - /// Invoke a method as ReadOnly Flag on a smart contract. - /// - /// ScriptHash - /// method name - /// JArray of the contract parameters. - /// Execution Engine object. - /// Successful - /// An error occurred. See Response for details. - [HttpPost("{hash:required}/invoke", Name = "InvokeContractMethod")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ExecutionEngineModel))] - public IActionResult InvokeContract( - [FromRoute(Name = "hash")] - UInt160 scripthash, - [FromQuery(Name = "method")] - string method, - [FromBody] - ContractParameter[] contractParameters) - { - var contracts = NativeContract.ContractManagement.GetContract(_neosystem.StoreView, scripthash); - if (contracts == null) - throw new ContractNotFoundException(scripthash); - if (string.IsNullOrEmpty(method)) - throw new QueryParameterNotFoundException(nameof(method)); - try - { - var engine = ScriptHelper.InvokeMethod(_neosystem.Settings, _neosystem.StoreView, contracts.Hash, method, contractParameters, out var script); - return Ok(engine.ToModel()); - } - catch (Exception ex) - { - throw ex?.InnerException ?? ex; - } - } - } -} diff --git a/src/RestServer/Controllers/v1/LedgerController.cs b/src/RestServer/Controllers/v1/LedgerController.cs deleted file mode 100644 index 31d669f74..000000000 --- a/src/RestServer/Controllers/v1/LedgerController.cs +++ /dev/null @@ -1,389 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Neo.Network.P2P.Payloads; -using Neo.Plugins.RestServer.Exceptions; -using Neo.Plugins.RestServer.Extensions; -using Neo.Plugins.RestServer.Models.Blockchain; -using Neo.Plugins.RestServer.Models.Error; -using Neo.Plugins.RestServer.Models.Ledger; -using Neo.SmartContract.Native; -using System.Net.Mime; - -namespace Neo.Plugins.RestServer.Controllers.v1 -{ - [Route("/api/v{version:apiVersion}/ledger")] - [Produces(MediaTypeNames.Application.Json)] - [Consumes(MediaTypeNames.Application.Json)] - [ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(ErrorModel))] - [ApiVersion("1.0")] - [ApiController] - public class LedgerController : ControllerBase - { - private readonly NeoSystem _neosystem; - - public LedgerController() - { - _neosystem = RestServerPlugin.NeoSystem ?? throw new NodeNetworkException(); - } - - #region Accounts - - /// - /// Gets all the accounts that hold gas on the blockchain. - /// - /// An array of account details object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("gas/accounts", Name = "GetGasAccounts")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(AccountDetails[]))] - public IActionResult ShowGasAccounts() - { - var accounts = NativeContract.GAS.ListAccounts(_neosystem.StoreView, _neosystem.Settings); - return Ok(accounts.OrderByDescending(o => o.Balance)); - } - - /// - /// Get all the accounts that hold neo on the blockchain. - /// - /// An array of account details object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("neo/accounts", Name = "GetNeoAccounts")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(AccountDetails[]))] - public IActionResult ShowNeoAccounts() - { - var accounts = NativeContract.NEO.ListAccounts(_neosystem.StoreView, _neosystem.Settings); - return Ok(accounts.OrderByDescending(o => o.Balance)); - } - - #endregion - - #region Blocks - - /// - /// Get blocks from the blockchain. - /// - /// Page - /// Page Size - /// An array of Block Header Objects - /// No more pages. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("blocks", Name = "GetBlocks")] - [ProducesResponseType(StatusCodes.Status204NoContent)] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Header[]))] - public IActionResult GetBlocks( - [FromQuery(Name = "page")] - uint skip = 1, - [FromQuery(Name = "size")] - uint take = 1) - { - if (skip < 1 || take < 1 || take > RestServerSettings.Current.MaxPageSize) - throw new InvalidParameterRangeException(); - //var start = (skip - 1) * take + startIndex; - //var end = start + take; - var start = NativeContract.Ledger.CurrentIndex(_neosystem.StoreView) - (skip - 1) * take; - var end = start - take; - var lstOfBlocks = new List
(); - for (uint i = start; i > end; i--) - { - var block = NativeContract.Ledger.GetBlock(_neosystem.StoreView, i); - if (block == null) - break; - lstOfBlocks.Add(block.Header); - } - if (lstOfBlocks.Any() == false) - return NoContent(); - return Ok(lstOfBlocks); - } - - /// - /// Gets the current block height of the connected node. - /// - /// Full Block Object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("blocks/height", Name = "GetBlockHeight")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Block))] - public IActionResult GetCurrentBlock() - { - var currentIndex = NativeContract.Ledger.CurrentIndex(_neosystem.StoreView); - var block = NativeContract.Ledger.GetHeader(_neosystem.StoreView, currentIndex); - return Ok(block); - } - - /// - /// Gets a block by an its index. - /// - /// Block Index - /// Full Block Object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("blocks/{index:min(0)}", Name = "GetBlock")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Block))] - public IActionResult GetBlock( - [FromRoute(Name = "index")] - uint blockIndex) - { - var block = NativeContract.Ledger.GetBlock(_neosystem.StoreView, blockIndex); - if (block == null) - throw new BlockNotFoundException(blockIndex); - return Ok(block); - } - - /// - /// Gets a block header by block index. - /// - /// Blocks index. - /// Block Header Object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("blocks/{index:min(0)}/header", Name = "GetBlockHeader")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Header))] - public IActionResult GetBlockHeader( - [FromRoute(Name = "index")] - uint blockIndex) - { - var block = NativeContract.Ledger.GetBlock(_neosystem.StoreView, blockIndex); - if (block == null) - throw new BlockNotFoundException(blockIndex); - return Ok(block.Header); - } - - /// - /// Gets the witness of the block - /// - /// Block Index. - /// Witness Object - /// Successful - /// An error occurred. See Response for details. - [HttpGet("blocks/{index:min(0)}/witness", Name = "GetBlockWitness")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Witness))] - public IActionResult GetBlockWitness( - [FromRoute(Name = "index")] - uint blockIndex) - { - var block = NativeContract.Ledger.GetBlock(_neosystem.StoreView, blockIndex); - if (block == null) - throw new BlockNotFoundException(blockIndex); - return Ok(block.Witness); - } - - /// - /// Gets the transactions of the block. - /// - /// Block Index. - /// Page - /// Page Size - /// An array of transaction object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("blocks/{index:min(0)}/transactions", Name = "GetBlockTransactions")] - [ProducesResponseType(StatusCodes.Status204NoContent)] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Transaction[]))] - public IActionResult GetBlockTransactions( - [FromRoute(Name = "index")] - uint blockIndex, - [FromQuery(Name = "page")] - int skip = 1, - [FromQuery(Name = "size")] - int take = 1) - { - if (skip < 1 || take < 1 || take > RestServerSettings.Current.MaxPageSize) - throw new InvalidParameterRangeException(); - var block = NativeContract.Ledger.GetBlock(_neosystem.StoreView, blockIndex); - if (block == null) - throw new BlockNotFoundException(blockIndex); - if (block.Transactions == null || block.Transactions.Length == 0) - return NoContent(); - return Ok(block.Transactions.Skip((skip - 1) * take).Take(take)); - } - - #endregion - - #region Transactions - - /// - /// Gets a transaction - /// - /// Hash256 - /// Transaction object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("transactions/{hash:required}", Name = "GetTransaction")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Transaction))] - public IActionResult GetTransaction( - [FromRoute( Name = "hash")] - UInt256 hash) - { - if (NativeContract.Ledger.ContainsTransaction(_neosystem.StoreView, hash) == false) - return NotFound(); - var txst = NativeContract.Ledger.GetTransaction(_neosystem.StoreView, hash); - if (txst == null) - throw new TransactionNotFoundException(hash); - return Ok(txst); - } - - /// - /// Gets the witness of a transaction. - /// - /// Hash256 - /// An array of witness object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("transactions/{hash:required}/witnesses", Name = "GetTransactionWitnesses")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Witness[]))] - public IActionResult GetTransactionWitnesses( - [FromRoute( Name = "hash")] - UInt256 hash) - { - if (NativeContract.Ledger.ContainsTransaction(_neosystem.StoreView, hash) == false) - throw new TransactionNotFoundException(hash); - var tx = NativeContract.Ledger.GetTransaction(_neosystem.StoreView, hash); - return Ok(tx.Witnesses); - } - - /// - /// Gets the signers of a transaction. - /// - /// Hash256 - /// An array of Signer object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("transactions/{hash:required}/signers", Name = "GetTransactionSigners")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Signer[]))] - public IActionResult GetTransactionSigners( - [FromRoute( Name = "hash")] - UInt256 hash) - { - if (NativeContract.Ledger.ContainsTransaction(_neosystem.StoreView, hash) == false) - throw new TransactionNotFoundException(hash); - var tx = NativeContract.Ledger.GetTransaction(_neosystem.StoreView, hash); - return Ok(tx.Signers); - } - - /// - /// Gets the transaction attributes of a transaction. - /// - /// Hash256 - /// An array of the transaction attributes object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("transactions/{hash:required}/attributes", Name = "GetTransactionAttributes")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(TransactionAttribute[]))] - public IActionResult GetTransactionAttributes( - [FromRoute( Name = "hash")] - UInt256 hash) - { - if (NativeContract.Ledger.ContainsTransaction(_neosystem.StoreView, hash) == false) - throw new TransactionNotFoundException(hash); - var tx = NativeContract.Ledger.GetTransaction(_neosystem.StoreView, hash); - return Ok(tx.Attributes); - } - - #endregion - - #region Memory Pool - - /// - /// Gets memory pool. - /// - /// Page - /// Page Size. - /// An array of the Transaction object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("memorypool", Name = "GetMemoryPoolTransactions")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Transaction[]))] - public IActionResult GetMemoryPool( - [FromQuery(Name = "page")] - int skip = 1, - [FromQuery(Name = "size")] - int take = 1) - { - if (skip < 0 || take < 0 || take > RestServerSettings.Current.MaxPageSize) - throw new InvalidParameterRangeException(); - return Ok(_neosystem.MemPool.Skip((skip - 1) * take).Take(take)); - } - - /// - /// Gets the count of the memory pool. - /// - /// Memory Pool Count Object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("memorypool/count", Name = "GetMemoryPoolCount")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(MemoryPoolCountModel))] - public IActionResult GetMemoryPoolCount() => - Ok(new MemoryPoolCountModel() - { - Count = _neosystem.MemPool.Count, - UnVerifiedCount = _neosystem.MemPool.UnVerifiedCount, - VerifiedCount = _neosystem.MemPool.VerifiedCount, - }); - - /// - /// Gets verified memory pool. - /// - /// Page - /// Page Size. - /// An array of the Transaction object. - /// No more pages. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("memorypool/verified", Name = "GetMemoryPoolVeridiedTransactions")] - [ProducesResponseType(StatusCodes.Status204NoContent)] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Transaction[]))] - public IActionResult GetMemoryPoolVerified( - [FromQuery(Name = "page")] - int skip = 1, - [FromQuery(Name = "size")] - int take = 1) - { - if (skip < 0 || take < 0 || take > RestServerSettings.Current.MaxPageSize) - throw new InvalidParameterRangeException(); - if (_neosystem.MemPool.Any() == false) - return NoContent(); - var vTx = _neosystem.MemPool.GetVerifiedTransactions(); - return Ok(vTx.Skip((skip - 1) * take).Take(take)); - } - - /// - /// Gets unverified memory pool. - /// - /// Page - /// Page Size. - /// An array of the Transaction object. - /// No more pages. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("memorypool/unverified", Name = "GetMemoryPoolUnveridiedTransactions")] - [ProducesResponseType(StatusCodes.Status204NoContent)] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Transaction[]))] - public IActionResult GetMemoryPoolUnVerified( - [FromQuery(Name = "page")] - int skip = 1, - [FromQuery(Name = "size")] - int take = 1) - { - if (skip < 0 || take < 0 || take > RestServerSettings.Current.MaxPageSize) - throw new InvalidParameterRangeException(); - if (_neosystem.MemPool.Any() == false) - return NoContent(); - _neosystem.MemPool.GetVerifiedAndUnverifiedTransactions(out _, out var unVerifiedTransactions); - return Ok(unVerifiedTransactions.Skip((skip - 1) * take).Take(take)); - } - - #endregion - } -} diff --git a/src/RestServer/Controllers/v1/NodeController.cs b/src/RestServer/Controllers/v1/NodeController.cs deleted file mode 100644 index 2bde367cc..000000000 --- a/src/RestServer/Controllers/v1/NodeController.cs +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Neo.IO; -using Neo.Network.P2P; -using Neo.Plugins.RestServer.Exceptions; -using Neo.Plugins.RestServer.Extensions; -using Neo.Plugins.RestServer.Models.Error; -using Neo.Plugins.RestServer.Models.Node; -using System.Net.Mime; - -namespace Neo.Plugins.RestServer.Controllers.v1 -{ - [Route("/api/v{version:apiVersion}/node")] - [Produces(MediaTypeNames.Application.Json)] - [Consumes(MediaTypeNames.Application.Json)] - [ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(ErrorModel))] - [ApiVersion("1.0")] - [ApiController] - public class NodeController : ControllerBase - { - private readonly LocalNode _neolocalnode; - private readonly NeoSystem _neosystem; - - public NodeController() - { - _neolocalnode = RestServerPlugin.LocalNode; - _neosystem = RestServerPlugin.NeoSystem ?? throw new NodeNetworkException(); - } - - /// - /// Gets the connected remote nodes. - /// - /// An array of the Remote Node Objects. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("peers", Name = "GetNodeRemotePeers")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(RemoteNodeModel[]))] - public IActionResult GetPeers() - { - var rNodes = _neolocalnode - .GetRemoteNodes() - .OrderByDescending(o => o.LastBlockIndex) - .ToArray(); - - return Ok(rNodes.Select(s => s.ToModel())); - } - - /// - /// Gets all the loaded plugins of the current connected node. - /// - /// An array of the Plugin objects. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("plugins", Name = "GetNodePlugins")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(PluginModel[]))] - public IActionResult GetPlugins() => - Ok(Plugin.Plugins.Select(s => - new PluginModel() - { - Name = s.Name, - Version = s.Version.ToString(3), - Description = s.Description, - })); - - /// - /// Gets the ProtocolSettings of the currently connected node. - /// - /// Protocol Settings Object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("settings", Name = "GetNodeProtocolSettings")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(ProtocolSettingsModel))] - public IActionResult GetSettings() => - Ok(_neosystem.Settings.ToModel()); - } -} diff --git a/src/RestServer/Controllers/v1/TokensController.cs b/src/RestServer/Controllers/v1/TokensController.cs deleted file mode 100644 index a947d78cd..000000000 --- a/src/RestServer/Controllers/v1/TokensController.cs +++ /dev/null @@ -1,304 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Neo.Plugins.RestServer.Exceptions; -using Neo.Plugins.RestServer.Extensions; -using Neo.Plugins.RestServer.Helpers; -using Neo.Plugins.RestServer.Models; -using Neo.Plugins.RestServer.Models.Error; -using Neo.Plugins.RestServer.Models.Token; -using Neo.Plugins.RestServer.Tokens; -using Neo.SmartContract.Native; -using System.Net.Mime; - -namespace Neo.Plugins.RestServer.Controllers.v1 -{ - [Route("/api/v{version:apiVersion}/tokens")] - [Produces(MediaTypeNames.Application.Json)] - [Consumes(MediaTypeNames.Application.Json)] - [ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(ErrorModel))] - [ApiVersion("1.0")] - [ApiController] - public class TokensController : ControllerBase - { - private readonly NeoSystem _neosystem; - - public TokensController() - { - _neosystem = RestServerPlugin.NeoSystem ?? throw new NodeNetworkException(); - } - - #region NEP-17 - - /// - /// Gets all Nep-17 valid contracts from the blockchain. - /// - /// Page - /// Page Size - /// An array of the Nep-17 Token Object. - /// No more pages. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("nep-17", Name = "GetNep17Tokens")] - [ProducesResponseType(StatusCodes.Status204NoContent)] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(NEP17TokenModel[]))] - public IActionResult GetNEP17( - [FromQuery(Name = "page")] - int skip = 1, - [FromQuery(Name = "size")] - int take = 1) - { - if (skip < 1 || take < 1 || take > RestServerSettings.Current.MaxPageSize) - throw new InvalidParameterRangeException(); - var tokenList = NativeContract.ContractManagement.ListContracts(_neosystem.StoreView); - var vaildContracts = tokenList - .Where(w => ContractHelper.IsNep17Supported(w)) - .OrderBy(o => o.Manifest.Name) - .Skip((skip - 1) * take) - .Take(take); - if (vaildContracts.Any() == false) - return NoContent(); - var listResults = new List(); - foreach (var contract in vaildContracts) - { - try - { - var token = new NEP17Token(_neosystem, contract.Hash); - listResults.Add(token.ToModel()); - } - catch - { - } - } - if (listResults.Any() == false) - return NoContent(); - return Ok(listResults); - } - - /// - /// The count of how many Nep-17 contracts are on the blockchain. - /// - /// Count Object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("nep-17/count", Name = "GetNep17TokenCount")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CountModel))] - public IActionResult GetNEP17Count() - { - return Ok(new CountModel() - { - Count = NativeContract.ContractManagement.ListContracts(_neosystem.StoreView).Count(c => ContractHelper.IsNep17Supported(c)) - }); - } - - /// - /// Gets the balance of the Nep-17 contract by an address. - /// - /// Nep-17 ScriptHash - /// Neo Address ScriptHash - /// Token Balance Object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("nep-17/{scripthash:required}/balanceof/{address:required}", Name = "GetNep17TokenBalanceOf")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(TokenBalanceModel))] - public IActionResult GetNEP17( - [FromRoute(Name = "scripthash")] - UInt160 tokenAddessOrScripthash, - [FromRoute(Name = "address")] - UInt160 lookupAddressOrScripthash) - { - var contract = NativeContract.ContractManagement.GetContract(_neosystem.StoreView, tokenAddessOrScripthash); - if (contract == null) - throw new ContractNotFoundException(tokenAddessOrScripthash); - if (ContractHelper.IsNep17Supported(contract) == false) - throw new Nep17NotSupportedException(tokenAddessOrScripthash); - try - { - var token = new NEP17Token(_neosystem, tokenAddessOrScripthash); - return Ok(new TokenBalanceModel() - { - Name = token.Name, - ScriptHash = token.ScriptHash, - Symbol = token.Symbol, - Decimals = token.Decimals, - Balance = token.BalanceOf(lookupAddressOrScripthash).Value, - TotalSupply = token.TotalSupply().Value, - }); - } - catch - { - throw new Nep17NotSupportedException(tokenAddessOrScripthash); - } - } - - #endregion - - #region NEP-11 - - /// - /// Gets all the Nep-11 valid contracts on from the blockchain. - /// - /// Page - /// Page Size - /// Nep-11 Token Object. - /// No more pages. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("nep-11", Name = "GetNep11Tokens")] - [ProducesResponseType(StatusCodes.Status204NoContent)] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(NEP11TokenModel[]))] - public IActionResult GetNEP11( - [FromQuery(Name = "page")] - int skip = 1, - [FromQuery(Name = "size")] - int take = 1) - { - if (skip < 1 || take < 1 || take > RestServerSettings.Current.MaxPageSize) - throw new InvalidParameterRangeException(); - var tokenList = NativeContract.ContractManagement.ListContracts(_neosystem.StoreView); - var vaildContracts = tokenList - .Where(ContractHelper.IsNep11Supported) - .OrderBy(o => o.Manifest.Name) - .Skip((skip - 1) * take) - .Take(take); - if (vaildContracts.Any() == false) - return NoContent(); - var listResults = new List(); - foreach (var contract in vaildContracts) - { - try - { - var token = new NEP11Token(_neosystem, contract.Hash); - listResults.Add(token.ToModel()); - } - catch - { - } - } - if (listResults.Any() == false) - return NoContent(); - return Ok(listResults); - } - - /// - /// The count of how many Nep-11 contracts are on the blockchain. - /// - /// Count Object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("nep-11/count", Name = "GetNep11TokenCount")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(CountModel))] - public IActionResult GetNEP11Count() - { - return Ok(new CountModel() { Count = NativeContract.ContractManagement.ListContracts(_neosystem.StoreView).Count(c => ContractHelper.IsNep11Supported(c)) }); - } - - /// - /// Gets the balance of the Nep-11 contract by an address. - /// - /// Nep-11 ScriptHash - /// Neo Address ScriptHash - /// Token Balance Object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("nep-11/{scripthash:required}/balanceof/{address:required}", Name = "GetNep11TokenBalanceOf")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(TokenBalanceModel))] - public IActionResult GetNEP11( - [FromRoute(Name = "scripthash")] - UInt160 sAddressHash, - [FromRoute(Name = "address")] - UInt160 addressHash) - { - var contract = NativeContract.ContractManagement.GetContract(_neosystem.StoreView, sAddressHash); - if (contract == null) - throw new ContractNotFoundException(sAddressHash); - if (ContractHelper.IsNep11Supported(contract) == false) - throw new Nep11NotSupportedException(sAddressHash); - try - { - var token = new NEP11Token(_neosystem, sAddressHash); - return Ok(new TokenBalanceModel() - { - Name = token.Name, - ScriptHash = token.ScriptHash, - Symbol = token.Symbol, - Decimals = token.Decimals, - Balance = token.BalanceOf(addressHash).Value, - TotalSupply = token.TotalSupply().Value, - }); - } - catch - { - throw new Nep11NotSupportedException(sAddressHash); - } - } - - #endregion - - /// - /// Gets every single NEP17/NEP11 on the blockchain's balance by ScriptHash - /// - /// - /// Token Balance Object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("balanceof/{address:required}", Name = "GetAllTokensBalanceOf")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(TokenBalanceModel))] - public IActionResult GetBalances( - [FromRoute(Name = "address")] - UInt160 addressOrScripthash) - { - var tokenList = NativeContract.ContractManagement.ListContracts(_neosystem.StoreView); - var validContracts = tokenList - .Where(w => ContractHelper.IsNep17Supported(w) || ContractHelper.IsNep11Supported(w)) - .OrderBy(o => o.Manifest.Name); - var listResults = new List(); - foreach (var contract in validContracts) - { - try - { - var token = new NEP17Token(_neosystem, contract.Hash); - var balance = token.BalanceOf(addressOrScripthash).Value; - if (balance == 0) - continue; - listResults.Add(new() - { - Name = token.Name, - ScriptHash = token.ScriptHash, - Symbol = token.Symbol, - Decimals = token.Decimals, - Balance = balance, - TotalSupply = token.TotalSupply().Value, - }); - - var nft = new NEP11Token(_neosystem, contract.Hash); - balance = nft.BalanceOf(addressOrScripthash).Value; - if (balance == 0) - continue; - listResults.Add(new() - { - Name = nft.Name, - ScriptHash = nft.ScriptHash, - Symbol = nft.Symbol, - Balance = balance, - Decimals = nft.Decimals, - TotalSupply = nft.TotalSupply().Value, - }); - } - catch (NotSupportedException) - { - } - } - return Ok(listResults); - } - } -} diff --git a/src/RestServer/Controllers/v1/UtilsController.cs b/src/RestServer/Controllers/v1/UtilsController.cs deleted file mode 100644 index ad3f54342..000000000 --- a/src/RestServer/Controllers/v1/UtilsController.cs +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Neo.Plugins.RestServer.Exceptions; -using Neo.Plugins.RestServer.Models.Error; -using Neo.Plugins.RestServer.Models.Utils; -using Neo.Wallets; -using System.Net.Mime; - -namespace Neo.Plugins.RestServer.Controllers.v1 -{ - [Route("/api/v{version:apiVersion}/utils")] - [Produces(MediaTypeNames.Application.Json)] - [Consumes(MediaTypeNames.Application.Json)] - [ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(ErrorModel))] - [ApiVersion("1.0")] - [ApiController] - public class UtilsController : ControllerBase - { - private readonly NeoSystem _neosystem; - - public UtilsController() - { - _neosystem = RestServerPlugin.NeoSystem ?? throw new NodeNetworkException(); - } - - #region Validation - - /// - /// Converts script to Neo address. - /// - /// ScriptHash - /// Util Address Object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("{hash:required}/address", Name = "GetAddressByScripthash")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(UtilsAddressModel))] - public IActionResult ScriptHashToWalletAddress( - [FromRoute(Name = "hash")] - UInt160 ScriptHash) - { - try - { - return Ok(new UtilsAddressModel() { Address = ScriptHash.ToAddress(_neosystem.Settings.AddressVersion) }); - } - catch (FormatException) - { - throw new ScriptHashFormatException(); - } - } - - /// - /// Converts Neo address to ScriptHash - /// - /// Neo Address - /// Util ScriptHash Object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("{address:required}/scripthash", Name = "GetScripthashByAddress")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(UtilsScriptHashModel))] - public IActionResult WalletAddressToScriptHash( - [FromRoute(Name = "address")] - string address) - { - try - { - return Ok(new UtilsScriptHashModel() { ScriptHash = address.ToScriptHash(_neosystem.Settings.AddressVersion) }); - } - catch (FormatException) - { - throw new AddressFormatException(); - } - } - - /// - /// Get whether or not a Neo address or ScriptHash is valid. - /// - /// - /// Util Address Valid Object. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("{address:required}/validate", Name = "IsValidAddressOrScriptHash")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(UtilsAddressIsValidModel))] - public IActionResult ValidateAddress( - [FromRoute(Name = "address")] - string AddressOrScriptHash) - { - return Ok(new UtilsAddressIsValidModel() - { - Address = AddressOrScriptHash, - IsValid = RestServerUtility.TryConvertToScriptHash(AddressOrScriptHash, _neosystem.Settings, out _), - }); - } - - #endregion - } -} diff --git a/src/RestServer/Controllers/v1/WalletController.cs b/src/RestServer/Controllers/v1/WalletController.cs deleted file mode 100644 index 56760825c..000000000 --- a/src/RestServer/Controllers/v1/WalletController.cs +++ /dev/null @@ -1,646 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 Akka.Actor; -using Microsoft.AspNetCore.Cors; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.Mvc; -using Neo.Network.P2P.Payloads; -using Neo.Plugins.RestServer.Exceptions; -using Neo.Plugins.RestServer.Helpers; -using Neo.Plugins.RestServer.Models.Error; -using Neo.Plugins.RestServer.Models.Wallet; -using Neo.SmartContract; -using Neo.SmartContract.Native; -using Neo.Wallets; -using Neo.Wallets.NEP6; -using System.Net.Mime; -using System.Numerics; - -namespace Neo.Plugins.RestServer.Controllers.v1 -{ - /// - /// Wallet API - /// - [Route("/api/v{version:apiVersion}/wallet")] - [DisableCors] - [Produces(MediaTypeNames.Application.Json)] - [Consumes(MediaTypeNames.Application.Json)] - [ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(ErrorModel))] - [ApiVersion("1.0")] - [ApiController] - public class WalletController : ControllerBase - { - internal static WalletSessionManager WalletSessions { get; } = new(); - - private readonly NeoSystem _neosystem; - - /// - /// CTOR - /// - /// Node network doesn't match plugins network. - public WalletController() - { - _neosystem = RestServerPlugin.NeoSystem ?? throw new NodeNetworkException(); - } - - /// - /// Opens a wallet. - /// - /// - /// A newly created wallet session object. - /// Returns newly create wallet session object. - /// An error occurred. See Response for details. - [HttpPost("open", Name = "WalletOpen")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletSessionModel))] - public IActionResult WalletOpen( - [FromBody] - WalletOpenModel model) - { - if (new FileInfo(model.Path).DirectoryName.StartsWith(AppContext.BaseDirectory, StringComparison.InvariantCultureIgnoreCase) == false) - throw new UnauthorizedAccessException(model.Path); - if (System.IO.File.Exists(model.Path) == false) - throw new FileNotFoundException(null, model.Path); - var wallet = Wallet.Open(model.Path, model.Password, _neosystem.Settings); - if (wallet == null) - throw new WalletOpenException($"File '{model.Path}' could not be opened."); - var sessionId = Guid.NewGuid(); - WalletSessions[sessionId] = new WalletSession(wallet); - return Ok(new WalletSessionModel() - { - SessionId = sessionId, - }); - } - - /// - /// Closes a wallet session. - /// - /// Session Id of the open/created wallet. - /// Empty response body, if successful. - /// Successfully closed the wallet session. - /// An error occurred. See Response for details. - [HttpGet("{session:required}/close", Name = "WalletClose")] - [ProducesResponseType(StatusCodes.Status200OK)] - public IActionResult WalletClose( - [FromRoute(Name = "session")] - Guid sessionId) - { - if (WalletSessions.ContainsKey(sessionId) == false) - throw new KeyNotFoundException(sessionId.ToString("n")); - if (WalletSessions.TryRemove(sessionId, out _) == false) - throw new WalletSessionException("Failed to remove session."); - return Ok(); - } - - /// - /// Get all the keys of the wallet from each account. - /// - /// Session Id of the open/created wallet. - /// A list of export key objects. - /// Successfully exported the keys. - /// An error occurred. See Response for details. - [HttpGet("{session:required}/export", Name = "WalletExportKeys")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletExportKeyModel[]))] - public IActionResult WalletExport( - [FromRoute(Name = "session")] - Guid sessionId) - { - if (WalletSessions.ContainsKey(sessionId) == false) - throw new KeyNotFoundException(sessionId.ToString("n")); - var session = WalletSessions[sessionId]; - session.ResetExpiration(); - var wallet = session.Wallet; - var keys = wallet.GetAccounts().Where(p => p.HasKey) - .Select(s => new WalletExportKeyModel() - { - ScriptHash = s.ScriptHash, - Address = s.Address, - Wif = s.GetKey().Export() - }).ToArray(); - return Ok(keys); - } - - /// - /// Get a key of the wallet by a specific account. - /// - /// Session Id of the open/created wallet. - /// ScriptHash of the wallet address. - /// A export key object. - /// Successfully exported the key. - /// An error occurred. See Response for details. - [HttpGet("{session:required}/export/{address:required}", Name = "WalletExportKeysByAddressOrScripthash")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletExportKeyModel))] - public IActionResult WalletExportKey( - [FromRoute(Name = "session")] - Guid sessionId, - [FromRoute(Name = "address")] - UInt160 scriptHash) - { - if (WalletSessions.ContainsKey(sessionId) == false) - throw new KeyNotFoundException(sessionId.ToString("n")); - var session = WalletSessions[sessionId]; - session.ResetExpiration(); - var wallet = session.Wallet; - var account = wallet.GetAccount(scriptHash); - if (account == null) - throw new WalletException($"Account {scriptHash} doesn\'t exist."); - var key = account.GetKey(); - return Ok(new WalletExportKeyModel - { - ScriptHash = account.ScriptHash, - Address = account.Address, - Wif = key.Export(), - }); - } - - /// - /// Create a new address in the wallet with an optional private key. - /// - /// Session Id of the open/created wallet. - /// - /// Wallet address object. - /// Successfully created address. - /// An error occurred. See Response for details. - [HttpPost("{session:required}/address/create", Name = "WalletCreateAddress")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletAddressModel))] - public IActionResult WalletCreateNewAddress( - [FromRoute(Name = "session")] - Guid sessionId, - [FromBody] - WalletCreateAccountModel model) - { - if (WalletSessions.ContainsKey(sessionId) == false) - throw new KeyNotFoundException(sessionId.ToString("n")); - var session = WalletSessions[sessionId]; - session.ResetExpiration(); - var wallet = session.Wallet; - var account = model.PrivateKey == null || model.PrivateKey.Length == 0 ? - wallet.CreateAccount() : - wallet.CreateAccount(model.PrivateKey); - if (account == null) - throw new WalletException("Account couldn't be created."); - if (wallet is NEP6Wallet nep6) - nep6.Save(); - return Ok(new WalletAddressModel() - { - Address = account.Address, - ScriptHash = account.ScriptHash, - Publickey = account.GetKey().PublicKey, - HasKey = account.HasKey, - Label = account.Label, - WatchOnly = account.WatchOnly, - }); - } - - /// - /// Get the wallet balance of a specific asset. - /// - /// Session Id of the open/created wallet. - /// ScriptHash of the wallet address. - /// Account balance object of all the accounts in the wallet. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("{session:required}/balance/{asset:required}", Name = "WalletBalanceOf")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletAccountBalanceModel))] - public IActionResult WalletBalance( - [FromRoute(Name = "session")] - Guid sessionId, - [FromRoute(Name = "asset")] - UInt160 scriptHash) - { - if (WalletSessions.ContainsKey(sessionId) == false) - throw new KeyNotFoundException(sessionId.ToString("n")); - var session = WalletSessions[sessionId]; - session.ResetExpiration(); - var wallet = session.Wallet; - var balance = wallet.GetAvailable(_neosystem.StoreView, scriptHash); - return Ok(new WalletAccountBalanceModel() - { - Balance = balance.Value, - }); - } - - /// - /// Get unclaimed gas of the wallet for all accounts total. - /// - /// Session Id of the open/created wallet. - /// Account balance object - /// Successful - /// An error occurred. See Response for details. - [HttpGet("{session:required}/gas/unclaimed", Name = "GetUnClaimedGas")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletAccountBalanceModel))] - public IActionResult WalletUnClaimedGas( - [FromRoute(Name = "session")] - Guid sessionId) - { - if (WalletSessions.ContainsKey(sessionId) == false) - throw new KeyNotFoundException(sessionId.ToString("n")); - var session = WalletSessions[sessionId]; - session.ResetExpiration(); - var wallet = session.Wallet; - using var snapshot = _neosystem.GetSnapshot(); - uint height = NativeContract.Ledger.CurrentIndex(snapshot) + 1; - BigInteger gas = BigInteger.Zero; - foreach (var account in wallet.GetAccounts().Select(s => s.ScriptHash)) - gas += NativeContract.NEO.UnclaimedGas(snapshot, account, height); - return Ok(new WalletAccountBalanceModel - { - Balance = gas, - }); - } - - /// - /// import a private key into the wallet. - /// - /// Session Id of the open/created wallet. - /// - /// New wallet address object. - /// Successful - /// An error occurred. See Response for details. - [HttpPost("{session:required}/import", Name = "WalletImportByWif")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletAddressModel))] - public IActionResult WalletImportPrivateKey( - [FromRoute(Name = "session")] - Guid sessionId, - [FromBody] - WalletImportKey model) - { - if (WalletSessions.ContainsKey(sessionId) == false) - throw new KeyNotFoundException(sessionId.ToString("n")); - var session = WalletSessions[sessionId]; - session.ResetExpiration(); - var wallet = session.Wallet; - var account = wallet.Import(model.Wif); - if (account == null) - throw new WalletException("Account couldn\'t be imported."); - if (wallet is NEP6Wallet nep6) - nep6.Save(); - return Ok(new WalletAddressModel() - { - Address = account.Address, - ScriptHash = account.ScriptHash, - Publickey = account.GetKey().PublicKey, - HasKey = account.HasKey, - Label = account.Label, - WatchOnly = account.WatchOnly, - }); - } - - /// - /// List all the addresses in the wallet. - /// - /// Session Id of the open/created wallet. - /// An array of wallet address objects. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("{session:required}/address/list", Name = "GetWalletListAddress")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletAddressModel[]))] - public IActionResult WalletListAddresses( - [FromRoute(Name = "session")] - Guid sessionId) - { - if (WalletSessions.ContainsKey(sessionId) == false) - throw new KeyNotFoundException(sessionId.ToString("n")); - var session = WalletSessions[sessionId]; - session.ResetExpiration(); - var wallet = session.Wallet; - var accounts = new List(); - foreach (var account in wallet.GetAccounts()) - accounts.Add(new WalletAddressModel() - { - Address = account.Address, - ScriptHash = account.ScriptHash, - Publickey = account.GetKey().PublicKey, - HasKey = account.HasKey, - Label = account.Label, - WatchOnly = account.WatchOnly, - }); - return Ok(accounts); - } - - /// - /// Deletes an account from the wallet. - /// - /// Session Id of the open/created wallet. - /// ScriptHash of the wallet address. - /// Empty body response. - /// No backups are made. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("{session:required}/delete/{account:required}", Name = "WalletDeleteAccountByAddressOrScriptHash")] - [ProducesResponseType(StatusCodes.Status200OK)] - public IActionResult WalletDeleteAccount( - [FromRoute(Name = "session")] - Guid sessionId, - [FromRoute(Name = "account")] - UInt160 scriptHash) - { - if (WalletSessions.ContainsKey(sessionId) == false) - throw new KeyNotFoundException(sessionId.ToString("n")); - var session = WalletSessions[sessionId]; - session.ResetExpiration(); - var wallet = session.Wallet; - if (wallet.DeleteAccount(scriptHash) == false) - throw new WalletException($"Could not delete '{scriptHash}' account."); - else - { - if (wallet is NEP6Wallet wallet6) - wallet6.Save(); - return Ok(); - } - } - - /// - /// Trasnsfer assets from one wallet address to another address on the blockchain. - /// - /// Session Id of the open/created wallet. - /// - /// Transaction object - /// Successful - /// An error occurred. See Response for details. - [HttpPost("{session:required}/transfer", Name = "WalletTransferAssets")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Transaction))] - public IActionResult WalletTransferAssets( - [FromRoute(Name = "session")] - Guid sessionId, - [FromBody] - WalletSendModel model) - { - if (WalletSessions.ContainsKey(sessionId) == false) - throw new KeyNotFoundException(sessionId.ToString("n")); - var session = WalletSessions[sessionId]; - session.ResetExpiration(); - var wallet = session.Wallet; - using var snapshot = _neosystem.GetSnapshot(); - try - { - var descriptor = new AssetDescriptor(snapshot, _neosystem.Settings, model.AssetId); - var amount = new BigDecimal(model.Amount, descriptor.Decimals); - if (amount.Sign <= 0) - throw new WalletException($"Invalid Amount."); - var signers = model.Signers?.Select(s => new Signer() { Scopes = WitnessScope.CalledByEntry, Account = s }).ToArray(); - var tx = wallet.MakeTransaction(snapshot, - new[] - { - new TransferOutput() - { - AssetId = model.AssetId, - Value = amount, - ScriptHash = model.To, - Data = model.Data, - }, - }, - model.From, signers); - if (tx == null) - throw new WalletInsufficientFundsException(); - var totalFees = new BigDecimal((BigInteger)(tx.SystemFee + tx.NetworkFee), NativeContract.GAS.Decimals); - if (totalFees.Value > RestServerSettings.Current.MaxTransactionFee) - throw new WalletException("The transaction fees are to much."); - var context = new ContractParametersContext(snapshot, tx, _neosystem.Settings.Network); - wallet.Sign(context); - if (context.Completed == false) - throw new WalletException("Transaction could not be completed at this time."); - tx.Witnesses = context.GetWitnesses(); - _neosystem.Blockchain.Tell(tx); - return Ok(tx); - } - catch (Exception ex) - { - throw ex.InnerException ?? ex; - } - } - - /// - /// Create a wallet. - /// - /// - /// A wallet session object. - /// Successful - /// An error occurred. See Response for details. - [HttpPost("create", Name = "WalletCreate")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletSessionModel))] - public IActionResult WalletCreate( - [FromBody] - WalletCreateModel model) - { - if (new FileInfo(model.Path).DirectoryName.StartsWith(AppContext.BaseDirectory, StringComparison.InvariantCultureIgnoreCase) == false) - throw new UnauthorizedAccessException(model.Path); - var wallet = Wallet.Create(model.Name, model.Path, model.Password, _neosystem.Settings); - if (wallet == null) - throw new WalletException("Wallet files in that format are not supported, please use a .json or .db3 file extension."); - if (string.IsNullOrEmpty(model.Wif) == false) - wallet.Import(model.Wif); - if (wallet is NEP6Wallet nep6) - nep6.Save(); - var sessionId = Guid.NewGuid(); - WalletSessions[sessionId] = new WalletSession(wallet); - return Ok(new WalletSessionModel() - { - SessionId = sessionId, - }); - } - - /// - /// Import multi-signature addresss into the wallet. - /// - /// Session Id of the open/created wallet. - /// - /// - /// Successful - /// An error occurred. See Response for details. - [HttpPost("{session:required}/import/multisigaddress", Name = "WalletImportMultiSigAddress")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletMultiSignContractModel))] - public IActionResult WalletImportMultiSigAddress( - [FromRoute(Name = "session")] - Guid sessionId, - [FromBody] - WalletImportMultiSigAddressModel model) - { - if (WalletSessions.ContainsKey(sessionId) == false) - throw new KeyNotFoundException(sessionId.ToString("n")); - if (model.PublicKeys == null || model.PublicKeys.Length == 0) - throw new WalletException($"{nameof(model.PublicKeys)} is invalid."); - var session = WalletSessions[sessionId]; - var wallet = session.Wallet; - session.ResetExpiration(); - - int n = model.PublicKeys.Length; - - if (model.RequiredSignatures < 1 || model.RequiredSignatures > n || n > 1024) - throw new WalletException($"{nameof(model.RequiredSignatures)} and {nameof(model.PublicKeys)} is invalid."); - - Contract multiSignContract = Contract.CreateMultiSigContract(model.RequiredSignatures, model.PublicKeys); - KeyPair keyPair = wallet.GetAccounts().FirstOrDefault(p => p.HasKey && model.PublicKeys.Contains(p.GetKey().PublicKey))?.GetKey(); - if (keyPair == null) - throw new WalletException("Couldn\'t get key pair."); - var account = wallet.CreateAccount(multiSignContract, keyPair); - if (account == null) - throw new WalletException("Account couldn\'t be created."); - if (wallet is NEP6Wallet nep6) - nep6.Save(); - return Ok(new WalletMultiSignContractModel - { - Address = multiSignContract.ScriptHash.ToAddress(_neosystem.Settings.AddressVersion), - ScriptHash = multiSignContract.ScriptHash, - Script = multiSignContract.Script, - }); - } - - /// - /// List assets of the wallet. - /// - /// Session Id of the open/created wallet. - /// An array of wallet asset objects. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("{session:required}/asset/list", Name = "GetWalletAssetList")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletAssetModel[]))] - public IActionResult WalletListAsset( - [FromRoute(Name = "session")] - Guid sessionId) - { - if (WalletSessions.ContainsKey(sessionId) == false) - throw new KeyNotFoundException(sessionId.ToString("n")); - var session = WalletSessions[sessionId]; - var wallet = session.Wallet; - session.ResetExpiration(); - var assets = new List(); - foreach (var account in wallet.GetAccounts()) - assets.Add(new() - { - Address = account.Address, - ScriptHash = account.ScriptHash, - PublicKey = account.GetKey().PublicKey, - Neo = wallet.GetBalance(_neosystem.StoreView, NativeContract.NEO.Hash, account.ScriptHash).Value, - NeoHash = NativeContract.NEO.Hash, - Gas = wallet.GetBalance(_neosystem.StoreView, NativeContract.GAS.Hash, account.ScriptHash).Value, - GasHash = NativeContract.GAS.Hash, - }); - return Ok(assets); - } - - /// - /// List all account keys in the wallet. - /// - /// Session Id of the open/created wallet. - /// An array of wallet key objects. - /// Successful - /// An error occurred. See Response for details. - [HttpGet("{session:required}/key/list", Name = "GetWalletKeyList")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(WalletKeyModel[]))] - public IActionResult WalletListKeys( - [FromRoute(Name = "session")] - Guid sessionId) - { - if (WalletSessions.ContainsKey(sessionId) == false) - throw new KeyNotFoundException(sessionId.ToString("n")); - var session = WalletSessions[sessionId]; - var wallet = session.Wallet; - session.ResetExpiration(); - var keys = new List(); - foreach (var account in wallet.GetAccounts().Where(w => w.HasKey)) - keys.Add(new() - { - Address = account.Address, - ScriptHash = account.ScriptHash, - PublicKey = account.GetKey().PublicKey, - }); - return Ok(keys); - } - - /// - /// Change wallet password. - /// - /// Session Id of the open/created wallet. - /// - /// Empty body response. - /// Successful - /// An error occurred. See Response for details. - [HttpPost("{session:required}/changepassword", Name = "WalletChangePassword")] - [ProducesResponseType(StatusCodes.Status200OK)] - public IActionResult WalletChangePassword( - [FromRoute(Name = "session")] - Guid sessionId, - [FromBody] - WalletChangePasswordModel model) - { - if (WalletSessions.ContainsKey(sessionId) == false) - throw new KeyNotFoundException(sessionId.ToString("n")); - if (model.OldPassword == model.NewPassword) - throw new WalletException($"{nameof(model.OldPassword)} is the same as {nameof(model.NewPassword)}."); - var session = WalletSessions[sessionId]; - var wallet = session.Wallet; - session.ResetExpiration(); - if (wallet.VerifyPassword(model.OldPassword) == false) - throw new WalletException("Invalid password! Session terminated!"); - if (model.CreateBackupFile && wallet is NEP6Wallet) - { - var bakFile = wallet.Path + $".{sessionId:n}.bak"; - if (System.IO.File.Exists(wallet.Path) == false) - throw new WalletException("Create wallet backup failed. Wallet file doesn\'t exist."); - if (System.IO.File.Exists(bakFile) && model.OverwriteIfBackupFileExists == false) - throw new WalletException("Backup File already exists for this session."); - System.IO.File.Copy(wallet.Path, bakFile, true); - } - if (wallet.ChangePassword(model.OldPassword, model.NewPassword) == false) - throw new WalletException("Failed to change password!"); - if (wallet is NEP6Wallet nep6) - nep6.Save(); - return Ok(); - } - - /// - /// Create a transaction with a script. - /// - /// Session Id of the open/created wallet. - /// - /// Transaction object. - /// Successful - /// An error occurred. See Response for details. - [HttpPost("{session:required}/transaction/script", Name = "WalletTransactionWithScript")] - [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Transaction))] - public IActionResult WalletTransactionWithScript( - [FromRoute(Name = "session")] - Guid sessionId, - [FromBody] - WalletTransactionScriptModel model) - { - if (WalletSessions.ContainsKey(sessionId) == false) - throw new KeyNotFoundException(sessionId.ToString("n")); - if (model.Script == null || model.Script.Length == 0) - throw new JsonPropertyNullOrEmptyException(nameof(model.Script)); - var session = WalletSessions[sessionId]; - session.ResetExpiration(); - var wallet = session.Wallet; - var signers = model.Signers?.Select(s => new Signer() { Scopes = WitnessScope.CalledByEntry, Account = s }).ToArray(); - var appEngine = ScriptHelper.InvokeScript(model.Script, signers); - if (appEngine.State != VM.VMState.HALT) - throw new ApplicationEngineException(appEngine.FaultException?.InnerException?.Message ?? appEngine.FaultException?.Message ?? string.Empty); - var tx = wallet.MakeTransaction(_neosystem.StoreView, model.Script, model.From, signers, maxGas: RestServerSettings.Current.MaxGasInvoke); - try - { - var context = new ContractParametersContext(_neosystem.StoreView, tx, _neosystem.Settings.Network); - wallet.Sign(context); - if (context.Completed == false) - throw new WalletException($"Incomplete signature: {context}"); - else - { - tx.Witnesses = context.GetWitnesses(); - _neosystem.Blockchain.Tell(tx); - return Ok(tx); - } - } - catch (Exception ex) - { - throw ex.InnerException ?? ex; - } - } - } -} diff --git a/src/RestServer/Exceptions/AddressFormatException.cs b/src/RestServer/Exceptions/AddressFormatException.cs deleted file mode 100644 index e2249ac36..000000000 --- a/src/RestServer/Exceptions/AddressFormatException.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Exceptions -{ - internal class AddressFormatException : Exception - { - public AddressFormatException() : base() { } - public AddressFormatException(string message) : base(message) { } - } -} diff --git a/src/RestServer/Exceptions/ApplicationEngineException.cs b/src/RestServer/Exceptions/ApplicationEngineException.cs deleted file mode 100644 index 37030f7e6..000000000 --- a/src/RestServer/Exceptions/ApplicationEngineException.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Exceptions -{ - internal class ApplicationEngineException : Exception - { - public ApplicationEngineException() : base() { } - public ApplicationEngineException(string message) : base(message) { } - } -} diff --git a/src/RestServer/Exceptions/BlockNotFoundException.cs b/src/RestServer/Exceptions/BlockNotFoundException.cs deleted file mode 100644 index c669afcf5..000000000 --- a/src/RestServer/Exceptions/BlockNotFoundException.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Exceptions -{ - internal class BlockNotFoundException : Exception - { - public BlockNotFoundException() { } - public BlockNotFoundException(uint index) : base($"block '{index}' as not found.") { } - } -} diff --git a/src/RestServer/Exceptions/ContractNotFoundException.cs b/src/RestServer/Exceptions/ContractNotFoundException.cs deleted file mode 100644 index f363c467e..000000000 --- a/src/RestServer/Exceptions/ContractNotFoundException.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Exceptions -{ - internal class ContractNotFoundException : Exception - { - public ContractNotFoundException() : base() { } - public ContractNotFoundException(UInt160 scriptHash) : base($"Contract '{scriptHash}' was not found.") { } - } -} diff --git a/src/RestServer/Exceptions/InvalidParameterRangeException.cs b/src/RestServer/Exceptions/InvalidParameterRangeException.cs deleted file mode 100644 index 021e40cf5..000000000 --- a/src/RestServer/Exceptions/InvalidParameterRangeException.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Exceptions -{ - internal class InvalidParameterRangeException : Exception - { - public InvalidParameterRangeException() : base() { } - public InvalidParameterRangeException(string message) : base(message) { } - } -} diff --git a/src/RestServer/Exceptions/JsonPropertyNullOrEmptyException.cs b/src/RestServer/Exceptions/JsonPropertyNullOrEmptyException.cs deleted file mode 100644 index 6afe08e79..000000000 --- a/src/RestServer/Exceptions/JsonPropertyNullOrEmptyException.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Exceptions -{ - internal class JsonPropertyNullOrEmptyException : Exception - { - public JsonPropertyNullOrEmptyException() : base() { } - - public JsonPropertyNullOrEmptyException(string paramName) : base($"Value cannot be null or empty. (Parameter '{paramName}')") { } - } -} diff --git a/src/RestServer/Exceptions/Nep11NotSupportedException.cs b/src/RestServer/Exceptions/Nep11NotSupportedException.cs deleted file mode 100644 index 5382dbdef..000000000 --- a/src/RestServer/Exceptions/Nep11NotSupportedException.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Exceptions -{ - internal class Nep11NotSupportedException : Exception - { - public Nep11NotSupportedException() { } - public Nep11NotSupportedException(UInt160 scriptHash) : base($"Contract '{scriptHash}' does not support NEP-11.") { } - } -} diff --git a/src/RestServer/Exceptions/Nep17NotSupportedException.cs b/src/RestServer/Exceptions/Nep17NotSupportedException.cs deleted file mode 100644 index 00e672a1f..000000000 --- a/src/RestServer/Exceptions/Nep17NotSupportedException.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Exceptions -{ - internal class Nep17NotSupportedException : Exception - { - public Nep17NotSupportedException() { } - public Nep17NotSupportedException(UInt160 scriptHash) : base($"Contract '{scriptHash}' does not support NEP-17.") { } - } -} diff --git a/src/RestServer/Exceptions/NodeException.cs b/src/RestServer/Exceptions/NodeException.cs deleted file mode 100644 index f59ec669d..000000000 --- a/src/RestServer/Exceptions/NodeException.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Exceptions -{ - internal class NodeException : Exception - { - public NodeException() : base() { } - public NodeException(string message) : base(message) { } - } -} diff --git a/src/RestServer/Exceptions/NodeNetworkException.cs b/src/RestServer/Exceptions/NodeNetworkException.cs deleted file mode 100644 index da45244b2..000000000 --- a/src/RestServer/Exceptions/NodeNetworkException.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Exceptions -{ - internal class NodeNetworkException : Exception - { - public NodeNetworkException() : base("Network does not match config file's.") { } - public NodeNetworkException(string message) : base(message) { } - } -} diff --git a/src/RestServer/Exceptions/QueryParameterNotFoundException.cs b/src/RestServer/Exceptions/QueryParameterNotFoundException.cs deleted file mode 100644 index 8be1af0eb..000000000 --- a/src/RestServer/Exceptions/QueryParameterNotFoundException.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Exceptions -{ - internal class QueryParameterNotFoundException : Exception - { - public QueryParameterNotFoundException() { } - public QueryParameterNotFoundException(string parameterName) : base($"Query parameter '{parameterName}' was not found.") { } - } -} diff --git a/src/RestServer/Exceptions/RestErrorCodes.cs b/src/RestServer/Exceptions/RestErrorCodes.cs deleted file mode 100644 index 2fb434106..000000000 --- a/src/RestServer/Exceptions/RestErrorCodes.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Exceptions -{ - internal static class RestErrorCodes - { - //=========================Rest Codes========================= - public const int GenericException = 1000; - public const int ParameterFormatException = 1001; - } -} diff --git a/src/RestServer/Exceptions/ScriptHashFormatException.cs b/src/RestServer/Exceptions/ScriptHashFormatException.cs deleted file mode 100644 index dcfe04f87..000000000 --- a/src/RestServer/Exceptions/ScriptHashFormatException.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Exceptions -{ - internal class ScriptHashFormatException : Exception - { - public ScriptHashFormatException() : base() { } - public ScriptHashFormatException(string message) : base(message) { } - } -} diff --git a/src/RestServer/Exceptions/TransactionNotFoundException.cs b/src/RestServer/Exceptions/TransactionNotFoundException.cs deleted file mode 100644 index e27e810cc..000000000 --- a/src/RestServer/Exceptions/TransactionNotFoundException.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Exceptions -{ - internal class TransactionNotFoundException : Exception - { - public TransactionNotFoundException() { } - public TransactionNotFoundException(UInt256 txhash) : base($"Transaction '{txhash}' was not found.") { } - } -} diff --git a/src/RestServer/Exceptions/UInt256FormatException.cs b/src/RestServer/Exceptions/UInt256FormatException.cs deleted file mode 100644 index 9d77cf295..000000000 --- a/src/RestServer/Exceptions/UInt256FormatException.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Exceptions -{ - internal class UInt256FormatException : Exception - { - public UInt256FormatException() { } - public UInt256FormatException(string message) : base(message) { } - } -} diff --git a/src/RestServer/Exceptions/WalletException.cs b/src/RestServer/Exceptions/WalletException.cs deleted file mode 100644 index 47861b083..000000000 --- a/src/RestServer/Exceptions/WalletException.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Exceptions -{ - internal class WalletException : Exception - { - public WalletException() : base() { } - public WalletException(string message) : base(message) { } - } -} diff --git a/src/RestServer/Exceptions/WalletInsufficientFundsException.cs b/src/RestServer/Exceptions/WalletInsufficientFundsException.cs deleted file mode 100644 index 9b061c590..000000000 --- a/src/RestServer/Exceptions/WalletInsufficientFundsException.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Exceptions -{ - internal class WalletInsufficientFundsException : Exception - { - public WalletInsufficientFundsException() : base("Wallet has insufficient funds.") { } - public WalletInsufficientFundsException(string message) : base(message) { } - } -} diff --git a/src/RestServer/Exceptions/WalletOpenException.cs b/src/RestServer/Exceptions/WalletOpenException.cs deleted file mode 100644 index bcdfa3317..000000000 --- a/src/RestServer/Exceptions/WalletOpenException.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Exceptions -{ - internal class WalletOpenException : Exception - { - public WalletOpenException() : base() { } - - public WalletOpenException(string message) : base(message) { } - } -} diff --git a/src/RestServer/Exceptions/WalletSessionException.cs b/src/RestServer/Exceptions/WalletSessionException.cs deleted file mode 100644 index b6db9bea7..000000000 --- a/src/RestServer/Exceptions/WalletSessionException.cs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Exceptions -{ - internal class WalletSessionException : Exception - { - public WalletSessionException() : base() { } - public WalletSessionException(string message) : base(message) { } - } -} diff --git a/src/RestServer/Extensions/LedgerContractExtensions.cs b/src/RestServer/Extensions/LedgerContractExtensions.cs deleted file mode 100644 index 7a86db8f8..000000000 --- a/src/RestServer/Extensions/LedgerContractExtensions.cs +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.IO; -using Neo.Persistence; -using Neo.Plugins.RestServer.Models.Blockchain; -using Neo.SmartContract; -using Neo.SmartContract.Native; -using Neo.Wallets; - -#pragma warning disable IDE0060 - -namespace Neo.Plugins.RestServer.Extensions -{ - internal static class LedgerContractExtensions - { - private const byte _prefix_block = 5; - private const byte _prefix_transaction = 11; - private const byte _prefix_account = 20; - private const byte _prefix_totalsupply = 11; - - public static IEnumerable<(StorageKey key, StorageItem value)> GetStorageByPrefix(this ContractState contractState, DataCache snapshot, byte[] prefix) - { - ArgumentNullException.ThrowIfNull(nameof(contractState)); - ArgumentNullException.ThrowIfNull(nameof(snapshot)); - if (prefix?.Length == 0) - throw new ArgumentNullException(nameof(prefix)); - foreach (var (key, value) in snapshot.Find(StorageKey.CreateSearchPrefix(contractState.Id, prefix))) - yield return (key, value); - } - - public static StorageItem GetStorageByKey(this ContractState contractState, DataCache snapshot, byte[] storageKey) - { - ArgumentNullException.ThrowIfNull(nameof(contractState)); - ArgumentNullException.ThrowIfNull(nameof(snapshot)); - if (storageKey?.Length == 0) - throw new ArgumentNullException(nameof(storageKey)); - foreach (var (key, value) in snapshot.Find(StorageKey.CreateSearchPrefix(contractState.Id, storageKey))) - if (key.Key.Span.SequenceEqual(storageKey)) - return value; - return default; - } - - public static IEnumerable<(StorageKey key, StorageItem value)> GetStorage(this ContractState contractState, DataCache snapshot) - { - ArgumentNullException.ThrowIfNull(nameof(contractState)); - ArgumentNullException.ThrowIfNull(nameof(snapshot)); - return ListContractStorage(null, snapshot, contractState.Id); - } - - public static IEnumerable<(StorageKey key, StorageItem value)> ListContractStorage(this ContractManagement contractManagement, DataCache snapshot, int contractId) - { - ArgumentNullException.ThrowIfNull(nameof(snapshot)); - if (contractId < 0) - throw new ArgumentOutOfRangeException(nameof(contractId)); - foreach (var (key, value) in snapshot.Find(StorageKey.CreateSearchPrefix(contractId, ReadOnlySpan.Empty))) - yield return (key, value); - } - - public static IEnumerable ListBlocks(this LedgerContract ledger, DataCache snapshot) - { - ArgumentNullException.ThrowIfNull(nameof(snapshot)); - var kb = new KeyBuilder(NativeContract.Ledger.Id, _prefix_block); - var prefixKey = kb.ToArray(); - foreach (var (key, value) in snapshot.Seek(prefixKey, SeekDirection.Forward)) - if (key.ToArray().AsSpan().StartsWith(prefixKey)) - yield return value.Value.AsSerializable(); - else - yield break; - } - - public static IEnumerable ListTransactions(this LedgerContract ledger, DataCache snapshot, uint page, uint pageSize) - { - ArgumentNullException.ThrowIfNull(nameof(snapshot)); - var kb = new KeyBuilder(NativeContract.Ledger.Id, _prefix_transaction); - var prefixKey = kb.ToArray(); - uint index = 1; - foreach (var (key, value) in snapshot.Seek(prefixKey, SeekDirection.Forward)) - { - if (key.ToArray().AsSpan().StartsWith(prefixKey)) - { - if (index >= page && index < (pageSize + page)) - yield return value.GetInteroperable(); - index++; - } - else - yield break; - } - } - - public static IEnumerable ListAccounts(this GasToken gasToken, DataCache snapshot, ProtocolSettings protocolSettings) - { - ArgumentNullException.ThrowIfNull(nameof(snapshot)); - var kb = new KeyBuilder(gasToken.Id, _prefix_account); - var prefixKey = kb.ToArray(); - foreach (var (key, value) in snapshot.Seek(prefixKey, SeekDirection.Forward)) - { - if (key.ToArray().AsSpan().StartsWith(prefixKey)) - { - var addressHash = new UInt160(key.ToArray().AsSpan(5)); - yield return new AccountDetails() - { - ScriptHash = addressHash, - Address = addressHash.ToAddress(protocolSettings.AddressVersion), - Balance = value.GetInteroperable().Balance, - }; - } - else - yield break; - } - } - - public static IEnumerable ListAccounts(this NeoToken neoToken, DataCache snapshot, ProtocolSettings protocolSettings) - { - ArgumentNullException.ThrowIfNull(nameof(snapshot)); - var kb = new KeyBuilder(neoToken.Id, _prefix_account); - var prefixKey = kb.ToArray(); - foreach (var (key, value) in snapshot.Seek(prefixKey, SeekDirection.Forward)) - { - if (key.ToArray().AsSpan().StartsWith(prefixKey)) - { - var addressHash = new UInt160(key.ToArray().AsSpan(5)); - yield return new AccountDetails() - { - ScriptHash = addressHash, - Address = addressHash.ToAddress(protocolSettings.AddressVersion), - Balance = value.GetInteroperable().Balance, - }; - } - else - yield break; - } - } - } -} diff --git a/src/RestServer/Extensions/ModelExtensions.cs b/src/RestServer/Extensions/ModelExtensions.cs deleted file mode 100644 index 027b559c5..000000000 --- a/src/RestServer/Extensions/ModelExtensions.cs +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Network.P2P; -using Neo.Plugins.RestServer.Models; -using Neo.Plugins.RestServer.Models.Error; -using Neo.Plugins.RestServer.Models.Node; -using Neo.Plugins.RestServer.Models.Token; -using Neo.Plugins.RestServer.Tokens; -using Neo.SmartContract; - -namespace Neo.Plugins.RestServer.Extensions -{ - internal static class ModelExtensions - { - public static ExecutionEngineModel ToModel(this ApplicationEngine ae) => - new() - { - GasConsumed = ae.GasConsumed, - State = ae.State, - Notifications = ae.Notifications.Select(s => - new BlockchainEventModel() - { - ScriptHash = s.ScriptHash, - EventName = s.EventName, - State = s.State.ToArray(), - }).ToArray(), - ResultStack = ae.ResultStack.ToArray(), - FaultException = ae.FaultException == null ? - null : - new ErrorModel() - { - Code = ae.FaultException?.InnerException?.HResult ?? ae.FaultException.HResult, - Name = ae.FaultException?.InnerException?.GetType().Name ?? ae.FaultException?.GetType().Name, - Message = ae.FaultException?.InnerException?.Message ?? ae.FaultException?.Message, - }, - }; - - public static NEP17TokenModel ToModel(this NEP17Token token) => - new() - { - Name = token.Name, - Symbol = token.Symbol, - ScriptHash = token.ScriptHash, - Decimals = token.Decimals, - TotalSupply = token.TotalSupply().Value, - }; - - public static NEP11TokenModel ToModel(this NEP11Token nep11) => - new() - { - Name = nep11.Name, - ScriptHash = nep11.ScriptHash, - Symbol = nep11.Symbol, - Decimals = nep11.Decimals, - TotalSupply = nep11.TotalSupply().Value, - Tokens = nep11.Tokens().Select(s => new - { - Key = s, - Value = nep11.Properties(s), - }).ToDictionary(key => Convert.ToHexString(key.Key), value => value.Value), - }; - - public static ProtocolSettingsModel ToModel(this ProtocolSettings protocolSettings) => - new() - { - Network = protocolSettings.Network, - AddressVersion = protocolSettings.AddressVersion, - ValidatorsCount = protocolSettings.ValidatorsCount, - MillisecondsPerBlock = protocolSettings.MillisecondsPerBlock, - MaxValidUntilBlockIncrement = protocolSettings.MaxValidUntilBlockIncrement, - MaxTransactionsPerBlock = protocolSettings.MaxTransactionsPerBlock, - MemoryPoolMaxTransactions = protocolSettings.MemoryPoolMaxTransactions, - MaxTraceableBlocks = protocolSettings.MaxTraceableBlocks, - InitialGasDistribution = protocolSettings.InitialGasDistribution, - SeedList = protocolSettings.SeedList, - NativeUpdateHistory = protocolSettings.NativeUpdateHistory, - Hardforks = protocolSettings.Hardforks, - StandbyValidators = protocolSettings.StandbyValidators, - StandbyCommittee = protocolSettings.StandbyCommittee, - }; - - public static RemoteNodeModel ToModel(this RemoteNode remoteNode) => - new() - { - RemoteAddress = remoteNode.Remote.Address.ToString(), - RemotePort = remoteNode.Remote.Port, - ListenTcpPort = remoteNode.ListenerTcpPort, - LastBlockIndex = remoteNode.LastBlockIndex, - }; - } -} diff --git a/src/RestServer/Extensions/UInt160Extensions.cs b/src/RestServer/Extensions/UInt160Extensions.cs deleted file mode 100644 index 472948257..000000000 --- a/src/RestServer/Extensions/UInt160Extensions.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Plugins.RestServer.Helpers; -using Neo.SmartContract.Native; - -namespace Neo.Plugins.RestServer.Extensions -{ - internal static class UInt160Extensions - { - public static bool IsValidNep17(this UInt160 scriptHash) - { - var contractState = NativeContract.ContractManagement.GetContract(RestServerPlugin.NeoSystem.StoreView, scriptHash); - return ContractHelper.IsNep17Supported(contractState); - } - - public static bool IsValidContract(this UInt160 scriptHash) => - NativeContract.ContractManagement.GetContract(RestServerPlugin.NeoSystem.StoreView, scriptHash) != null; - } -} diff --git a/src/RestServer/Helpers/ContractHelper.cs b/src/RestServer/Helpers/ContractHelper.cs deleted file mode 100644 index f2f7bcda0..000000000 --- a/src/RestServer/Helpers/ContractHelper.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Persistence; -using Neo.SmartContract; -using Neo.SmartContract.Manifest; -using Neo.SmartContract.Native; - -namespace Neo.Plugins.RestServer.Helpers -{ - public static class ContractHelper - { - public static ContractParameterDefinition[] GetAbiEventParams(DataCache snapshot, UInt160 scriptHash, string eventName) - { - var contractState = NativeContract.ContractManagement.GetContract(snapshot, scriptHash); - if (contractState == null) - return Array.Empty(); - return contractState.Manifest.Abi.Events.SingleOrDefault(s => s.Name.Equals(eventName, StringComparison.OrdinalIgnoreCase))?.Parameters; - } - - public static bool IsNep17Supported(DataCache snapshot, UInt160 scriptHash) - { - var contractState = NativeContract.ContractManagement.GetContract(snapshot, scriptHash); - if (contractState == null) - return false; - return IsNep17Supported(contractState); - } - - public static bool IsNep11Supported(DataCache snapshot, UInt160 scriptHash) - { - var contractState = NativeContract.ContractManagement.GetContract(snapshot, scriptHash); - if (contractState == null) - return false; - return IsNep11Supported(contractState); - } - - public static bool IsNep17Supported(ContractState contractState) => - contractState.Manifest.SupportedStandards.Any(a => a.Equals("NEP-17")); - - public static bool IsNep11Supported(ContractState contractState) => - contractState.Manifest.SupportedStandards.Any(a => a.Equals("NEP-11")); - - public static ContractMethodDescriptor GetContractMethod(DataCache snapshot, UInt160 scriptHash, string method, int pCount) - { - var contractState = NativeContract.ContractManagement.GetContract(snapshot, scriptHash); - if (contractState == null) - return null; - return contractState.Manifest.Abi.GetMethod(method, pCount); - } - } -} diff --git a/src/RestServer/Helpers/ScriptHelper.cs b/src/RestServer/Helpers/ScriptHelper.cs deleted file mode 100644 index 092fdcc84..000000000 --- a/src/RestServer/Helpers/ScriptHelper.cs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Network.P2P.Payloads; -using Neo.Persistence; -using Neo.SmartContract; -using Neo.SmartContract.Native; -using Neo.VM; -using Neo.VM.Types; -using Array = System.Array; - -namespace Neo.Plugins.RestServer.Helpers -{ - internal static class ScriptHelper - { - public static bool InvokeMethod(ProtocolSettings protocolSettings, DataCache snapshot, UInt160 scriptHash, string method, out StackItem[] results, params object[] args) - { - using var scriptBuilder = new ScriptBuilder(); - scriptBuilder.EmitDynamicCall(scriptHash, method, CallFlags.ReadOnly, args); - byte[] script = scriptBuilder.ToArray(); - using var engine = ApplicationEngine.Run(script, snapshot, settings: protocolSettings, gas: RestServerSettings.Current.MaxGasInvoke); - results = engine.State == VMState.FAULT ? Array.Empty() : engine.ResultStack.ToArray(); - return engine.State == VMState.HALT; - } - - public static ApplicationEngine InvokeMethod(ProtocolSettings protocolSettings, DataCache snapshot, UInt160 scriptHash, string method, ContractParameter[] args, out byte[] script) - { - using var scriptBuilder = new ScriptBuilder(); - scriptBuilder.EmitDynamicCall(scriptHash, method, CallFlags.ReadOnly, args); - script = scriptBuilder.ToArray(); - using var engine = ApplicationEngine.Run(script, snapshot, settings: protocolSettings, gas: RestServerSettings.Current.MaxGasInvoke); - return engine; - } - - public static ApplicationEngine InvokeScript(ReadOnlyMemory script, Signer[] signers = null, Witness[] witnesses = null) - { - var neosystem = RestServerPlugin.NeoSystem; - var snapshot = neosystem.GetSnapshot(); - Transaction tx = signers == null ? null : new Transaction - { - Version = 0, - Nonce = (uint)Random.Shared.Next(), - ValidUntilBlock = NativeContract.Ledger.CurrentIndex(snapshot) + neosystem.Settings.MaxValidUntilBlockIncrement, - Signers = signers, - Attributes = Array.Empty(), - Script = script, - Witnesses = witnesses - }; - return ApplicationEngine.Run(script, snapshot, tx, settings: neosystem.Settings, gas: RestServerSettings.Current.MaxGasInvoke); - } - } -} diff --git a/src/RestServer/Middleware/RestServerMiddleware.cs b/src/RestServer/Middleware/RestServerMiddleware.cs deleted file mode 100644 index fe9a18c9d..000000000 --- a/src/RestServer/Middleware/RestServerMiddleware.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 Microsoft.AspNetCore.Http; -using System.Reflection; - -namespace Neo.Plugins.RestServer.Middleware -{ - internal class RestServerMiddleware - { - private readonly RequestDelegate _next; - - public RestServerMiddleware(RequestDelegate next) - { - _next = next; - } - - public async Task InvokeAsync(HttpContext context) - { - var request = context.Request; - var response = context.Response; - - SetServerInfomationHeader(response); - - await _next(context); - } - - public static void SetServerInfomationHeader(HttpResponse response) - { - var neoCliAsm = Assembly.GetEntryAssembly().GetName(); - var restServerAsm = Assembly.GetExecutingAssembly().GetName(); - - response.Headers.Server = $"{neoCliAsm.Name}/{neoCliAsm.Version.ToString(3)} {restServerAsm.Name}/{restServerAsm.Version.ToString(3)}"; - } - } -} diff --git a/src/RestServer/Models/Blockchain/AccountDetails.cs b/src/RestServer/Models/Blockchain/AccountDetails.cs deleted file mode 100644 index 5acb0ceec..000000000 --- a/src/RestServer/Models/Blockchain/AccountDetails.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 System.Numerics; - -namespace Neo.Plugins.RestServer.Models.Blockchain -{ - internal class AccountDetails - { - /// - /// Scripthash - /// - /// 0xed7cc6f5f2dd842d384f254bc0c2d58fb69a4761 - public UInt160 ScriptHash { get; set; } - /// - /// Wallet address. - /// - /// NNLi44dJNXtDNSBkofB48aTVYtb1zZrNEs - public string Address { get; set; } - /// - /// Balance of the account. - /// - /// 10000000 - public BigInteger Balance { get; set; } - } -} diff --git a/src/RestServer/Models/CountModel.cs b/src/RestServer/Models/CountModel.cs deleted file mode 100644 index afbf09145..000000000 --- a/src/RestServer/Models/CountModel.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Models -{ - internal class CountModel - { - /// - /// The count of how many objects. - /// - /// 378 - public int Count { get; set; } - } -} diff --git a/src/RestServer/Models/Error/ErrorModel.cs b/src/RestServer/Models/Error/ErrorModel.cs deleted file mode 100644 index bc35543fa..000000000 --- a/src/RestServer/Models/Error/ErrorModel.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Models.Error -{ - internal class ErrorModel - { - /// - /// Error's HResult Code. - /// - /// 1000 - public int Code { get; init; } = 1000; - /// - /// Error's name of the type. - /// - /// GeneralException - public string Name { get; init; } = "GeneralException"; - /// - /// Error's exception message. - /// - /// An error occurred. - /// Could be InnerException message as well, If exists. - public string Message { get; init; } = "An error occurred."; - } -} diff --git a/src/RestServer/Models/Error/ParameterFormatExceptionModel.cs b/src/RestServer/Models/Error/ParameterFormatExceptionModel.cs deleted file mode 100644 index b842123da..000000000 --- a/src/RestServer/Models/Error/ParameterFormatExceptionModel.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Plugins.RestServer.Exceptions; - -namespace Neo.Plugins.RestServer.Models.Error -{ - internal class ParameterFormatExceptionModel : ErrorModel - { - public ParameterFormatExceptionModel() - { - Code = RestErrorCodes.ParameterFormatException; - Name = nameof(RestErrorCodes.ParameterFormatException); - } - - public ParameterFormatExceptionModel(string message) : this() - { - Message = message; - } - } -} diff --git a/src/RestServer/Models/ExecutionEngineModel.cs b/src/RestServer/Models/ExecutionEngineModel.cs deleted file mode 100644 index 5710e550f..000000000 --- a/src/RestServer/Models/ExecutionEngineModel.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Plugins.RestServer.Models.Error; -using Neo.SmartContract; -using Neo.VM; -using Neo.VM.Types; - -namespace Neo.Plugins.RestServer.Models -{ - internal class ExecutionEngineModel - { - public long GasConsumed { get; set; } = 0L; - public VMState State { get; set; } = VMState.NONE; - public BlockchainEventModel[] Notifications { get; set; } = System.Array.Empty(); - public StackItem[] ResultStack { get; set; } = System.Array.Empty(); - public ErrorModel FaultException { get; set; } - } - - internal class BlockchainEventModel - { - public UInt160 ScriptHash { get; set; } = new(); - public string EventName { get; set; } = string.Empty; - public StackItem[] State { get; set; } = System.Array.Empty(); - - public static BlockchainEventModel Create(UInt160 scriptHash, string eventName, StackItem[] state) => - new() - { - ScriptHash = scriptHash, - EventName = eventName ?? string.Empty, - State = state, - }; - - public static BlockchainEventModel Create(NotifyEventArgs notifyEventArgs, StackItem[] state) => - new() - { - ScriptHash = notifyEventArgs.ScriptHash, - EventName = notifyEventArgs.EventName, - State = state, - }; - } -} diff --git a/src/RestServer/Models/Ledger/MemoryPoolCountModel.cs b/src/RestServer/Models/Ledger/MemoryPoolCountModel.cs deleted file mode 100644 index d411f0eac..000000000 --- a/src/RestServer/Models/Ledger/MemoryPoolCountModel.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Models.Ledger -{ - internal class MemoryPoolCountModel - { - /// - /// Total count all transactions. - /// - /// 110 - public int Count { get; set; } - /// - /// Count of unverified transactions - /// - /// 10 - public int UnVerifiedCount { get; set; } - /// - /// Count of verified transactions. - /// - /// 100 - public int VerifiedCount { get; set; } - } -} diff --git a/src/RestServer/Models/Node/PluginModel.cs b/src/RestServer/Models/Node/PluginModel.cs deleted file mode 100644 index 36d388d17..000000000 --- a/src/RestServer/Models/Node/PluginModel.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Models.Node -{ - internal class PluginModel - { - /// - /// Name - /// - /// RestServer - public string Name { get; set; } - /// - /// Version - /// - /// 3.5.0 - public string Version { get; set; } - /// - /// Description - /// - /// Enables REST Web Sevices for the node - public string Description { get; set; } - } -} diff --git a/src/RestServer/Models/Node/ProtocolSettingsModel.cs b/src/RestServer/Models/Node/ProtocolSettingsModel.cs deleted file mode 100644 index 590ad7f04..000000000 --- a/src/RestServer/Models/Node/ProtocolSettingsModel.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Cryptography.ECC; - -namespace Neo.Plugins.RestServer.Models.Node -{ - internal class ProtocolSettingsModel - { - /// - /// Network - /// - /// 860833102 - public uint Network { get; set; } - /// - /// AddressVersion - /// - /// 53 - public byte AddressVersion { get; set; } - public int ValidatorsCount { get; set; } - public uint MillisecondsPerBlock { get; set; } - public uint MaxValidUntilBlockIncrement { get; set; } - public uint MaxTransactionsPerBlock { get; set; } - public int MemoryPoolMaxTransactions { get; set; } - public uint MaxTraceableBlocks { get; set; } - public ulong InitialGasDistribution { get; set; } - public IReadOnlyCollection SeedList { get; set; } - public IReadOnlyDictionary NativeUpdateHistory { get; set; } - public IReadOnlyDictionary Hardforks { get; set; } - public IReadOnlyList StandbyValidators { get; set; } - public IReadOnlyList StandbyCommittee { get; set; } - } -} diff --git a/src/RestServer/Models/Node/RemoteNodeModel.cs b/src/RestServer/Models/Node/RemoteNodeModel.cs deleted file mode 100644 index 647ec5e79..000000000 --- a/src/RestServer/Models/Node/RemoteNodeModel.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Models.Node -{ - public class RemoteNodeModel - { - /// - /// Remote peer's ip address. - /// - /// 10.0.0.100 - public string RemoteAddress { get; set; } - /// - /// Remote peer's port number. - /// - /// 20333 - public int RemotePort { get; set; } - /// - /// Remote peer's listening tcp port. - /// - /// 20333 - public int ListenTcpPort { get; set; } - /// - /// Remote peer's last synced block height. - /// - /// 2584158 - public uint LastBlockIndex { get; set; } - } -} diff --git a/src/RestServer/Models/Token/NEP11TokenModel.cs b/src/RestServer/Models/Token/NEP11TokenModel.cs deleted file mode 100644 index a454646ea..000000000 --- a/src/RestServer/Models/Token/NEP11TokenModel.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.VM.Types; - -namespace Neo.Plugins.RestServer.Models.Token -{ - internal class NEP11TokenModel : NEP17TokenModel - { - public IReadOnlyDictionary> Tokens { get; set; } - } -} diff --git a/src/RestServer/Models/Token/NEP17TokenModel.cs b/src/RestServer/Models/Token/NEP17TokenModel.cs deleted file mode 100644 index b769a3eed..000000000 --- a/src/RestServer/Models/Token/NEP17TokenModel.cs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 System.Numerics; - -namespace Neo.Plugins.RestServer.Models.Token -{ - internal class NEP17TokenModel - { - public string Name { get; set; } - public UInt160 ScriptHash { get; set; } - public string Symbol { get; set; } - public byte Decimals { get; set; } - public BigInteger TotalSupply { get; set; } - } -} diff --git a/src/RestServer/Models/Token/TokenBalanceModel.cs b/src/RestServer/Models/Token/TokenBalanceModel.cs deleted file mode 100644 index a3a10e7d0..000000000 --- a/src/RestServer/Models/Token/TokenBalanceModel.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 System.Numerics; - -namespace Neo.Plugins.RestServer.Models.Token -{ - public class TokenBalanceModel - { - public string Name { get; set; } - public UInt160 ScriptHash { get; set; } - public string Symbol { get; set; } - public byte Decimals { get; set; } - public BigInteger Balance { get; set; } - public BigInteger TotalSupply { get; set; } - } -} diff --git a/src/RestServer/Models/Utils/UtilsAddressIsValidModel.cs b/src/RestServer/Models/Utils/UtilsAddressIsValidModel.cs deleted file mode 100644 index 7295f9a13..000000000 --- a/src/RestServer/Models/Utils/UtilsAddressIsValidModel.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace Neo.Plugins.RestServer.Models.Utils -{ - internal class UtilsAddressIsValidModel : UtilsAddressModel - { - /// - /// Indicates if address can be converted to ScriptHash or Neo Address. - /// - /// true - public bool IsValid { get; set; } - } -} diff --git a/src/RestServer/Models/Utils/UtilsAddressModel.cs b/src/RestServer/Models/Utils/UtilsAddressModel.cs deleted file mode 100644 index 9b9694159..000000000 --- a/src/RestServer/Models/Utils/UtilsAddressModel.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Models.Utils -{ - internal class UtilsAddressModel - { - /// - /// Wallet address that was exported. - /// - /// NNLi44dJNXtDNSBkofB48aTVYtb1zZrNEs - public virtual string Address { get; set; } - } -} diff --git a/src/RestServer/Models/Utils/UtilsScriptHashModel.cs b/src/RestServer/Models/Utils/UtilsScriptHashModel.cs deleted file mode 100644 index 5a24603ba..000000000 --- a/src/RestServer/Models/Utils/UtilsScriptHashModel.cs +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Models.Utils -{ - internal class UtilsScriptHashModel - { - /// - /// Scripthash of the wallet account exported. - /// - /// 0xed7cc6f5f2dd842d384f254bc0c2d58fb69a4761 - public UInt160 ScriptHash { get; set; } - } -} diff --git a/src/RestServer/Models/Wallet/WalletAccountBalanceModel.cs b/src/RestServer/Models/Wallet/WalletAccountBalanceModel.cs deleted file mode 100644 index b920c8466..000000000 --- a/src/RestServer/Models/Wallet/WalletAccountBalanceModel.cs +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 System.Numerics; - -namespace Neo.Plugins.RestServer.Models.Wallet -{ - /// - /// Wallet account balance object. - /// - internal class WalletAccountBalanceModel - { - /// - /// Balance of the account. - /// - /// 10000000 - public BigInteger Balance { get; set; } - } -} diff --git a/src/RestServer/Models/Wallet/WalletAddressModel.cs b/src/RestServer/Models/Wallet/WalletAddressModel.cs deleted file mode 100644 index d2d0184bd..000000000 --- a/src/RestServer/Models/Wallet/WalletAddressModel.cs +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Cryptography.ECC; - -namespace Neo.Plugins.RestServer.Models.Wallet -{ - /// - /// Wallet address object. - /// - public class WalletAddressModel - { - /// - /// Wallet address that was exported. - /// - /// NNLi44dJNXtDNSBkofB48aTVYtb1zZrNEs - public string Address { get; set; } - /// - /// Scripthash of the wallet account exported. - /// - /// 0xed7cc6f5f2dd842d384f254bc0c2d58fb69a4761 - public UInt160 ScriptHash { get; set; } - /// - /// Public key of the wallet address. - /// - /// 03cdb067d930fd5adaa6c68545016044aaddec64ba39e548250eaea551172e535c - public ECPoint Publickey { get; set; } - /// - /// has a private key or not. - /// - /// true - public bool HasKey { get; set; } - /// - /// The display name for the address. - /// - /// Default Account - public string Label { get; set; } - /// - /// is the address a WatchOnly address. - /// - /// false - public bool WatchOnly { get; set; } - } -} diff --git a/src/RestServer/Models/Wallet/WalletAssetModel.cs b/src/RestServer/Models/Wallet/WalletAssetModel.cs deleted file mode 100644 index 9d0766e2a..000000000 --- a/src/RestServer/Models/Wallet/WalletAssetModel.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Cryptography.ECC; -using System.Numerics; - -namespace Neo.Plugins.RestServer.Models.Wallet -{ - public class WalletAssetModel - { - /// - /// Wallet address that was exported. - /// - /// NNLi44dJNXtDNSBkofB48aTVYtb1zZrNEs - public string Address { get; set; } - /// - /// Scripthash of the wallet account exported. - /// - /// 0xed7cc6f5f2dd842d384f254bc0c2d58fb69a4761 - public UInt160 ScriptHash { get; set; } - /// - /// Public key of the wallet address. - /// - /// 03cdb067d930fd5adaa6c68545016044aaddec64ba39e548250eaea551172e535c - public ECPoint PublicKey { get; set; } - /// - /// Neo amount. - /// - /// 1 - public BigInteger Neo { get; set; } - /// - /// Neo ScriptHash Address. - /// - /// 0xef4073a0f2b305a38ec4050e4d3d28bc40ea63f5 - public UInt160 NeoHash { get; set; } - /// - /// Gas amount. - /// - /// 10000000 - public BigInteger Gas { get; set; } - /// - /// Gas ScriptHash Address. - /// - /// 0xd2a4cff31913016155e38e474a2c06d08be276cf - public UInt160 GasHash { get; set; } - } -} diff --git a/src/RestServer/Models/Wallet/WalletChangePasswordModel.cs b/src/RestServer/Models/Wallet/WalletChangePasswordModel.cs deleted file mode 100644 index d0aa6b034..000000000 --- a/src/RestServer/Models/Wallet/WalletChangePasswordModel.cs +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 System.ComponentModel.DataAnnotations; - -namespace Neo.Plugins.RestServer.Models.Wallet -{ - public class WalletChangePasswordModel - { - /// - /// Current password. - /// - /// Password1! - [Required(AllowEmptyStrings = false)] - public string OldPassword { get; set; } - /// - /// New Password. - /// - /// HelloWorld1! - [Required(AllowEmptyStrings = false)] - public string NewPassword { get; set; } - /// - /// Should create a backup file. - /// - /// false - public bool CreateBackupFile { get; set; } - /// - /// if backup file exists overwrite it. - /// - /// false - public bool OverwriteIfBackupFileExists { get; set; } - } -} diff --git a/src/RestServer/Models/Wallet/WalletCreateAccountModel.cs b/src/RestServer/Models/Wallet/WalletCreateAccountModel.cs deleted file mode 100644 index 5e3f1f36b..000000000 --- a/src/RestServer/Models/Wallet/WalletCreateAccountModel.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Models.Wallet -{ - /// - /// Create account object. - /// - public class WalletCreateAccountModel - { - /// - /// Private key of the address you want to create. Can be null or empty. - /// - /// CHeABTw3Q5SkjWharPAhgE+p+rGVN9FhlO4hXoJZQqA= - public byte[] PrivateKey { get; set; } - } -} diff --git a/src/RestServer/Models/Wallet/WalletCreateModel.cs b/src/RestServer/Models/Wallet/WalletCreateModel.cs deleted file mode 100644 index 82c0cdebd..000000000 --- a/src/RestServer/Models/Wallet/WalletCreateModel.cs +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 System.ComponentModel.DataAnnotations; - -namespace Neo.Plugins.RestServer.Models.Wallet -{ - /// - /// Wallet create object. - /// - public class WalletCreateModel - { - /// - /// Account display name - /// - /// Default Account - /// Can be null. - public string Name { get; set; } - /// - /// Path of the wallet file relative to the neo-cli path. - /// - /// ./wallets/mywallet.json - [Required(AllowEmptyStrings = false)] - public string Path { get; set; } - /// - /// Representation of the private. - /// - /// L3tgppXLgdaeqSGSFw1Go3skBiy8vQAM7YMXvTHsKQtE16PBncSU - /// Can be null or empty. - public string Wif { get; set; } - /// - /// Password to open the wallet file. - /// - /// Password1! - [Required(AllowEmptyStrings = false)] - public string Password { get; set; } - } -} diff --git a/src/RestServer/Models/Wallet/WalletExportKeyModel.cs b/src/RestServer/Models/Wallet/WalletExportKeyModel.cs deleted file mode 100644 index 8d18e88b7..000000000 --- a/src/RestServer/Models/Wallet/WalletExportKeyModel.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Models.Wallet -{ - /// - /// Export key wallet object - /// - internal class WalletExportKeyModel - { - /// - /// Scripthash of the wallet account exported. - /// - /// 0xed7cc6f5f2dd842d384f254bc0c2d58fb69a4761 - public UInt160 ScriptHash { get; set; } - /// - /// Wallet address that was exported. - /// - /// NNLi44dJNXtDNSBkofB48aTVYtb1zZrNEs - public string Address { get; set; } - /// - /// Representation of the private. - /// - /// L3tgppXLgdaeqSGSFw1Go3skBiy8vQAM7YMXvTHsKQtE16PBncSU - public string Wif { get; set; } - } -} diff --git a/src/RestServer/Models/Wallet/WalletImportKey.cs b/src/RestServer/Models/Wallet/WalletImportKey.cs deleted file mode 100644 index 2dfe03c84..000000000 --- a/src/RestServer/Models/Wallet/WalletImportKey.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 System.ComponentModel.DataAnnotations; - -namespace Neo.Plugins.RestServer.Models.Wallet -{ - /// - /// Wallet import key object. - /// - public class WalletImportKey - { - /// - /// Representation of the private. - /// - /// L3tgppXLgdaeqSGSFw1Go3skBiy8vQAM7YMXvTHsKQtE16PBncSU - [Required(AllowEmptyStrings = false)] - public string Wif { get; set; } - } -} diff --git a/src/RestServer/Models/Wallet/WalletImportMultiSigAddressModel.cs b/src/RestServer/Models/Wallet/WalletImportMultiSigAddressModel.cs deleted file mode 100644 index e22fe944c..000000000 --- a/src/RestServer/Models/Wallet/WalletImportMultiSigAddressModel.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Cryptography.ECC; -using System.ComponentModel.DataAnnotations; - -namespace Neo.Plugins.RestServer.Models.Wallet -{ - /// - /// Import Multi-Signature Address Object. - /// - public class WalletImportMultiSigAddressModel - { - /// - /// Minimum required signatures to sign. - /// - /// 2 - public ushort RequiredSignatures { get; set; } - /// - /// Array of public keys of the addresses. - /// - [Required] - public ECPoint[] PublicKeys { get; set; } - } -} diff --git a/src/RestServer/Models/Wallet/WalletKeyModel.cs b/src/RestServer/Models/Wallet/WalletKeyModel.cs deleted file mode 100644 index 3d8f1f176..000000000 --- a/src/RestServer/Models/Wallet/WalletKeyModel.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Cryptography.ECC; - -namespace Neo.Plugins.RestServer.Models.Wallet -{ - public class WalletKeyModel - { - /// - /// Wallet address that was exported. - /// - /// NNLi44dJNXtDNSBkofB48aTVYtb1zZrNEs - public string Address { get; set; } - /// - /// Scripthash of the wallet account exported. - /// - /// 0xed7cc6f5f2dd842d384f254bc0c2d58fb69a4761 - public UInt160 ScriptHash { get; set; } - /// - /// Public key of the wallet address. - /// - /// 03cdb067d930fd5adaa6c68545016044aaddec64ba39e548250eaea551172e535c - public ECPoint PublicKey { get; set; } - } -} diff --git a/src/RestServer/Models/Wallet/WalletMultiSignContractModel.cs b/src/RestServer/Models/Wallet/WalletMultiSignContractModel.cs deleted file mode 100644 index d04606de0..000000000 --- a/src/RestServer/Models/Wallet/WalletMultiSignContractModel.cs +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Models.Wallet -{ - /// - /// Multi-Signature Contract Object. - /// - internal class WalletMultiSignContractModel - { - /// - /// Wallet address that was exported. - /// - /// NNLi44dJNXtDNSBkofB48aTVYtb1zZrNEs - public string Address { get; set; } - /// - /// Scripthash of the wallet account exported. - /// - /// 0xed7cc6f5f2dd842d384f254bc0c2d58fb69a4761 - public UInt160 ScriptHash { get; set; } - /// - /// Script that used to create the address - /// - /// CHeABTw3Q5SkjWharPAhgE+p+rGVN9FhlO4hXoJZQqA= - public byte[] Script { get; set; } - } -} diff --git a/src/RestServer/Models/Wallet/WalletOpenModel.cs b/src/RestServer/Models/Wallet/WalletOpenModel.cs deleted file mode 100644 index 34ebe6bbc..000000000 --- a/src/RestServer/Models/Wallet/WalletOpenModel.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 System.ComponentModel.DataAnnotations; - -namespace Neo.Plugins.RestServer.Models.Wallet -{ - /// - /// Open wallet request object. - /// - public class WalletOpenModel - { - /// - /// Path of the wallet file relative to the neo-cli path. - /// - /// ./wallets/mywallet.json - [Required(AllowEmptyStrings = false)] - public string Path { get; set; } - /// - /// Password to open the wallet file. - /// - /// Password1! - [Required(AllowEmptyStrings = false)] - public string Password { get; set; } - } -} diff --git a/src/RestServer/Models/Wallet/WalletSendModel.cs b/src/RestServer/Models/Wallet/WalletSendModel.cs deleted file mode 100644 index d2c031520..000000000 --- a/src/RestServer/Models/Wallet/WalletSendModel.cs +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 System.ComponentModel.DataAnnotations; -using System.Numerics; - -namespace Neo.Plugins.RestServer.Models.Wallet -{ - /// - /// Wallet send object. - /// - public class WalletSendModel - { - /// - /// Asset Id - /// - /// 0xef4073a0f2b305a38ec4050e4d3d28bc40ea63f5 - [Required] - public UInt160 AssetId { get; set; } - /// - /// ScriptHash of the address in the wallet to send from. - /// - /// 0xed7cc6f5f2dd842d384f254bc0c2d58fb69a4761 - [Required] - public UInt160 From { get; set; } - /// - /// ScriptHash of the address in the wallet to send too. - /// - /// 0xed7cc6f5f2dd842d384f254bc0c2d58fb69a4761 - [Required] - public UInt160 To { get; set; } - /// - /// Amount - /// - /// 1 - /// Not user representation. - [Required] - public BigInteger Amount { get; set; } - /// - /// Data you would like to send. - /// - /// can be null or empty. - /// SGVsbG8gV29ybGQ= - public byte[] Data { get; set; } - /// - /// An array of the signer that will be signing the transaction. - /// - /// Can be null - public UInt160[] Signers { get; set; } - } -} diff --git a/src/RestServer/Models/Wallet/WalletSessionModel.cs b/src/RestServer/Models/Wallet/WalletSessionModel.cs deleted file mode 100644 index ef226f8d4..000000000 --- a/src/RestServer/Models/Wallet/WalletSessionModel.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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. - -namespace Neo.Plugins.RestServer.Models.Wallet -{ - /// - /// Open/Created wallet session object. - /// - public class WalletSessionModel - { - /// - /// Session id for an open/created wallet. - /// - /// 066843daf5ce45aba803587780998cdb - public Guid SessionId { get; set; } - } -} diff --git a/src/RestServer/Models/Wallet/WalletTransactionScriptModel.cs b/src/RestServer/Models/Wallet/WalletTransactionScriptModel.cs deleted file mode 100644 index 833563cb6..000000000 --- a/src/RestServer/Models/Wallet/WalletTransactionScriptModel.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 System.ComponentModel.DataAnnotations; - -namespace Neo.Plugins.RestServer.Models.Wallet -{ - public class WalletTransactionScriptModel - { - /// - /// Script to use. - /// - /// CHeABTw3Q5SkjWharPAhgE+p+rGVN9FhlO4hXoJZQqA= - [Required] - public byte[] Script { get; set; } - /// - /// ScriptHash of the address in the wallet to send from. - /// - /// 0xed7cc6f5f2dd842d384f254bc0c2d58fb69a4761 - [Required] - public UInt160 From { get; set; } - /// - /// An array of the signer that will be signing the transaction. - /// - /// Can be null - public UInt160[] Signers { get; set; } - } -} diff --git a/src/RestServer/Newtonsoft/Json/BigDecimalJsonConverter.cs b/src/RestServer/Newtonsoft/Json/BigDecimalJsonConverter.cs deleted file mode 100644 index 20d8be78a..000000000 --- a/src/RestServer/Newtonsoft/Json/BigDecimalJsonConverter.cs +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using System.Numerics; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json -{ - public class BigDecimalJsonConverter : JsonConverter - { - public override bool CanRead => true; - public override bool CanWrite => true; - - public override BigDecimal ReadJson(JsonReader reader, Type objectType, BigDecimal existingValue, bool hasExistingValue, JsonSerializer serializer) - { - var token = JToken.ReadFrom(reader); - if (token.Type == JTokenType.Object) - { - var valueProp = ((JObject)token).Properties().SingleOrDefault(p => p.Name.Equals("value", StringComparison.InvariantCultureIgnoreCase)); - var decimalsProp = ((JObject)token).Properties().SingleOrDefault(p => p.Name.Equals("decimals", StringComparison.InvariantCultureIgnoreCase)); - - if (valueProp != null && decimalsProp != null) - { - return new BigDecimal(valueProp.ToObject(), decimalsProp.ToObject()); - } - } - throw new FormatException(); - } - - public override void WriteJson(JsonWriter writer, BigDecimal value, JsonSerializer serializer) - { - var o = JToken.FromObject(new - { - value.Value, - value.Decimals, - }, serializer); - o.WriteTo(writer); - } - } -} diff --git a/src/RestServer/Newtonsoft/Json/BlockHeaderJsonConverter.cs b/src/RestServer/Newtonsoft/Json/BlockHeaderJsonConverter.cs deleted file mode 100644 index 5d30b5efe..000000000 --- a/src/RestServer/Newtonsoft/Json/BlockHeaderJsonConverter.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Network.P2P.Payloads; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json -{ - public class BlockHeaderJsonConverter : JsonConverter
- { - public override bool CanRead => false; - public override bool CanWrite => true; - - public override Header ReadJson(JsonReader reader, Type objectType, Header existingValue, bool hasExistingValue, JsonSerializer serializer) - { - throw new NotImplementedException(); - } - - public override void WriteJson(JsonWriter writer, Header value, JsonSerializer serializer) - { - var j = RestServerUtility.BlockHeaderToJToken(value, serializer); - j.WriteTo(writer); - } - } -} diff --git a/src/RestServer/Newtonsoft/Json/BlockJsonConverter.cs b/src/RestServer/Newtonsoft/Json/BlockJsonConverter.cs deleted file mode 100644 index 113053af7..000000000 --- a/src/RestServer/Newtonsoft/Json/BlockJsonConverter.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Network.P2P.Payloads; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json; - -public class BlockJsonConverter : JsonConverter -{ - public override bool CanRead => false; - - public override bool CanWrite => true; - - public override Block ReadJson(JsonReader reader, Type objectType, Block existingValue, bool hasExistingValue, JsonSerializer serializer) => - throw new NotImplementedException(); - - public override void WriteJson(JsonWriter writer, Block value, JsonSerializer serializer) - { - var j = RestServerUtility.BlockToJToken(value, serializer); - j.WriteTo(writer); - } -} diff --git a/src/RestServer/Newtonsoft/Json/ContractAbiJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractAbiJsonConverter.cs deleted file mode 100644 index 47ba189df..000000000 --- a/src/RestServer/Newtonsoft/Json/ContractAbiJsonConverter.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.SmartContract.Manifest; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json; - -public class ContractAbiJsonConverter : JsonConverter -{ - public override bool CanRead => false; - - public override bool CanWrite => true; - - public override ContractAbi ReadJson(JsonReader reader, Type objectType, ContractAbi existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); - public override void WriteJson(JsonWriter writer, ContractAbi value, JsonSerializer serializer) - { - var j = RestServerUtility.ContractAbiToJToken(value, serializer); - j.WriteTo(writer); - } -} diff --git a/src/RestServer/Newtonsoft/Json/ContractEventDescriptorJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractEventDescriptorJsonConverter.cs deleted file mode 100644 index 510664275..000000000 --- a/src/RestServer/Newtonsoft/Json/ContractEventDescriptorJsonConverter.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.SmartContract.Manifest; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json; - -public class ContractEventDescriptorJsonConverter : JsonConverter -{ - public override bool CanRead => false; - - public override bool CanWrite => true; - - public override ContractEventDescriptor ReadJson(JsonReader reader, Type objectType, ContractEventDescriptor existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); - public override void WriteJson(JsonWriter writer, ContractEventDescriptor value, JsonSerializer serializer) - { - var j = RestServerUtility.ContractEventToJToken(value, serializer); - j.WriteTo(writer); - } -} diff --git a/src/RestServer/Newtonsoft/Json/ContractGroupJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractGroupJsonConverter.cs deleted file mode 100644 index 0e58fa010..000000000 --- a/src/RestServer/Newtonsoft/Json/ContractGroupJsonConverter.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.SmartContract.Manifest; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json; - -public class ContractGroupJsonConverter : JsonConverter -{ - public override bool CanRead => false; - - public override bool CanWrite => true; - - public override ContractGroup ReadJson(JsonReader reader, Type objectType, ContractGroup existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); - public override void WriteJson(JsonWriter writer, ContractGroup value, JsonSerializer serializer) - { - var j = RestServerUtility.ContractGroupToJToken(value, serializer); - j.WriteTo(writer); - } -} diff --git a/src/RestServer/Newtonsoft/Json/ContractJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractJsonConverter.cs deleted file mode 100644 index 0a55e26d7..000000000 --- a/src/RestServer/Newtonsoft/Json/ContractJsonConverter.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.SmartContract; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json; - -public class ContractJsonConverter : JsonConverter -{ - public override bool CanRead => false; - - public override bool CanWrite => true; - - public override ContractState ReadJson(JsonReader reader, Type objectType, ContractState existingValue, bool hasExistingValue, global::Newtonsoft.Json.JsonSerializer serializer) => throw new NotImplementedException(); - public override void WriteJson(JsonWriter writer, ContractState value, global::Newtonsoft.Json.JsonSerializer serializer) - { - var j = RestServerUtility.ContractStateToJToken(value, serializer); - j.WriteTo(writer); - } -} diff --git a/src/RestServer/Newtonsoft/Json/ContractManifestJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractManifestJsonConverter.cs deleted file mode 100644 index ae602e755..000000000 --- a/src/RestServer/Newtonsoft/Json/ContractManifestJsonConverter.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.SmartContract.Manifest; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json; - -public class ContractManifestJsonConverter : JsonConverter -{ - public override bool CanRead => false; - - public override bool CanWrite => true; - - public override ContractManifest ReadJson(JsonReader reader, Type objectType, ContractManifest existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); - public override void WriteJson(JsonWriter writer, ContractManifest value, JsonSerializer serializer) - { - var j = RestServerUtility.ContractManifestToJToken(value, serializer); - j.WriteTo(writer); - } -} diff --git a/src/RestServer/Newtonsoft/Json/ContractMethodJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractMethodJsonConverter.cs deleted file mode 100644 index 2d7155b0d..000000000 --- a/src/RestServer/Newtonsoft/Json/ContractMethodJsonConverter.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.SmartContract.Manifest; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json; - -public class ContractMethodJsonConverter : JsonConverter -{ - public override bool CanRead => false; - - public override bool CanWrite => true; - - public override ContractMethodDescriptor ReadJson(JsonReader reader, Type objectType, ContractMethodDescriptor existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); - public override void WriteJson(JsonWriter writer, ContractMethodDescriptor value, JsonSerializer serializer) - { - var j = RestServerUtility.ContractMethodToJToken(value, serializer); - j.WriteTo(writer); - } -} diff --git a/src/RestServer/Newtonsoft/Json/ContractMethodParametersJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractMethodParametersJsonConverter.cs deleted file mode 100644 index 3b80a30c0..000000000 --- a/src/RestServer/Newtonsoft/Json/ContractMethodParametersJsonConverter.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.SmartContract.Manifest; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json; -public class ContractMethodParametersJsonConverter : JsonConverter -{ - public override bool CanRead => base.CanRead; - - public override bool CanWrite => base.CanWrite; - - public override ContractParameterDefinition ReadJson(JsonReader reader, Type objectType, ContractParameterDefinition existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); - public override void WriteJson(JsonWriter writer, ContractParameterDefinition value, JsonSerializer serializer) - { - var j = RestServerUtility.ContractMethodParameterToJToken(value, serializer); - j.WriteTo(writer); - } -} diff --git a/src/RestServer/Newtonsoft/Json/ContractParameterDefinitionJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractParameterDefinitionJsonConverter.cs deleted file mode 100644 index 5a99c9812..000000000 --- a/src/RestServer/Newtonsoft/Json/ContractParameterDefinitionJsonConverter.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.SmartContract.Manifest; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json; - -public class ContractParameterDefinitionJsonConverter : JsonConverter -{ - public override bool CanRead => false; - - public override bool CanWrite => true; - - public override ContractParameterDefinition ReadJson(JsonReader reader, Type objectType, ContractParameterDefinition existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); - public override void WriteJson(JsonWriter writer, ContractParameterDefinition value, JsonSerializer serializer) - { - var j = RestServerUtility.ContractParameterDefinitionToJToken(value, serializer); - j.WriteTo(writer); - } -} diff --git a/src/RestServer/Newtonsoft/Json/ContractParameterJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractParameterJsonConverter.cs deleted file mode 100644 index d32b45242..000000000 --- a/src/RestServer/Newtonsoft/Json/ContractParameterJsonConverter.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.SmartContract; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json -{ - public class ContractParameterJsonConverter : JsonConverter - { - public override bool CanRead => true; - public override bool CanWrite => false; - - public override ContractParameter ReadJson(JsonReader reader, Type objectType, ContractParameter existingValue, bool hasExistingValue, global::Newtonsoft.Json.JsonSerializer serializer) - { - var token = JToken.ReadFrom(reader); - return RestServerUtility.ContractParameterFromJToken(token); - } - - public override void WriteJson(JsonWriter writer, ContractParameter value, global::Newtonsoft.Json.JsonSerializer serializer) - { - throw new NotImplementedException(); - } - } -} diff --git a/src/RestServer/Newtonsoft/Json/ContractPermissionDescriptorJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractPermissionDescriptorJsonConverter.cs deleted file mode 100644 index 8c85ee764..000000000 --- a/src/RestServer/Newtonsoft/Json/ContractPermissionDescriptorJsonConverter.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.SmartContract.Manifest; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json; - -public class ContractPermissionDescriptorJsonConverter : JsonConverter -{ - public override bool CanRead => false; - - public override bool CanWrite => true; - - public override ContractPermissionDescriptor ReadJson(JsonReader reader, Type objectType, ContractPermissionDescriptor existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); - public override void WriteJson(JsonWriter writer, ContractPermissionDescriptor value, JsonSerializer serializer) - { - var j = RestServerUtility.ContractPermissionDescriptorToJToken(value, serializer); - j.WriteTo(writer); - } -} diff --git a/src/RestServer/Newtonsoft/Json/ContractPermissionJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ContractPermissionJsonConverter.cs deleted file mode 100644 index c4747f065..000000000 --- a/src/RestServer/Newtonsoft/Json/ContractPermissionJsonConverter.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.SmartContract.Manifest; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json; - -internal class ContractPermissionJsonConverter : JsonConverter -{ - public override bool CanRead => false; - - public override bool CanWrite => true; - - public override ContractPermission ReadJson(JsonReader reader, Type objectType, ContractPermission existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); - public override void WriteJson(JsonWriter writer, ContractPermission value, JsonSerializer serializer) - { - var j = RestServerUtility.ContractPermissionToJToken(value, serializer); - j.WriteTo(writer); - } -} diff --git a/src/RestServer/Newtonsoft/Json/ECPointJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ECPointJsonConverter.cs deleted file mode 100644 index 99b514b13..000000000 --- a/src/RestServer/Newtonsoft/Json/ECPointJsonConverter.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Cryptography.ECC; -using Neo.Plugins.RestServer.Exceptions; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json -{ - public class ECPointJsonConverter : JsonConverter - { - public override ECPoint ReadJson(JsonReader reader, Type objectType, ECPoint existingValue, bool hasExistingValue, JsonSerializer serializer) - { - var value = reader?.Value.ToString(); - try - { - return ECPoint.Parse(value, ECCurve.Secp256r1); - } - catch (FormatException) - { - throw new UInt256FormatException($"{value} is invalid."); - } - } - - public override void WriteJson(JsonWriter writer, ECPoint value, JsonSerializer serializer) - { - writer.WriteValue(value.ToString()); - } - } -} diff --git a/src/RestServer/Newtonsoft/Json/GuidJsonConverter.cs b/src/RestServer/Newtonsoft/Json/GuidJsonConverter.cs deleted file mode 100644 index 024a00f77..000000000 --- a/src/RestServer/Newtonsoft/Json/GuidJsonConverter.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json -{ - internal class GuidJsonConverter : JsonConverter - { - public override Guid ReadJson(JsonReader reader, Type objectType, Guid existingValue, bool hasExistingValue, JsonSerializer serializer) - { - return Guid.Parse(reader.Value?.ToString()); - } - - public override void WriteJson(JsonWriter writer, Guid value, JsonSerializer serializer) - { - writer.WriteValue(value.ToString("n")); - } - } -} diff --git a/src/RestServer/Newtonsoft/Json/InteropInterfaceJsonConverter.cs b/src/RestServer/Newtonsoft/Json/InteropInterfaceJsonConverter.cs deleted file mode 100644 index 8727577fc..000000000 --- a/src/RestServer/Newtonsoft/Json/InteropInterfaceJsonConverter.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.VM.Types; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json -{ - public class InteropInterfaceJsonConverter : JsonConverter - { - public override InteropInterface ReadJson(JsonReader reader, Type objectType, InteropInterface existingValue, bool hasExistingValue, JsonSerializer serializer) - { - var t = JToken.Load(reader); - return RestServerUtility.StackItemFromJToken(t) as InteropInterface; - } - - public override void WriteJson(JsonWriter writer, InteropInterface value, JsonSerializer serializer) - { - var t = RestServerUtility.StackItemToJToken(value, null, serializer); - t.WriteTo(writer); - } - } -} diff --git a/src/RestServer/Newtonsoft/Json/MethodTokenJsonConverter.cs b/src/RestServer/Newtonsoft/Json/MethodTokenJsonConverter.cs deleted file mode 100644 index 7503d3a67..000000000 --- a/src/RestServer/Newtonsoft/Json/MethodTokenJsonConverter.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.SmartContract; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json; - -public class MethodTokenJsonConverter : JsonConverter -{ - public override bool CanRead => false; - - public override bool CanWrite => true; - - public override MethodToken ReadJson(JsonReader reader, Type objectType, MethodToken existingValue, bool hasExistingValue, global::Newtonsoft.Json.JsonSerializer serializer) => throw new NotImplementedException(); - public override void WriteJson(JsonWriter writer, MethodToken value, global::Newtonsoft.Json.JsonSerializer serializer) - { - var j = RestServerUtility.MethodTokenToJToken(value, serializer); - j.WriteTo(writer); - } -} diff --git a/src/RestServer/Newtonsoft/Json/NefFileJsonConverter.cs b/src/RestServer/Newtonsoft/Json/NefFileJsonConverter.cs deleted file mode 100644 index d4e254d7e..000000000 --- a/src/RestServer/Newtonsoft/Json/NefFileJsonConverter.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.SmartContract; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json; - -public class NefFileJsonConverter : JsonConverter -{ - public override NefFile ReadJson(JsonReader reader, Type objectType, NefFile existingValue, bool hasExistingValue, global::Newtonsoft.Json.JsonSerializer serializer) => throw new NotImplementedException(); - public override void WriteJson(JsonWriter writer, NefFile value, global::Newtonsoft.Json.JsonSerializer serializer) - { - var j = RestServerUtility.ContractNefFileToJToken(value, serializer); - j.WriteTo(writer); - } -} diff --git a/src/RestServer/Newtonsoft/Json/ReadOnlyMemoryBytesJsonConverter.cs b/src/RestServer/Newtonsoft/Json/ReadOnlyMemoryBytesJsonConverter.cs deleted file mode 100644 index 99ea3d132..000000000 --- a/src/RestServer/Newtonsoft/Json/ReadOnlyMemoryBytesJsonConverter.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json -{ - public class ReadOnlyMemoryBytesJsonConverter : JsonConverter> - { - public override ReadOnlyMemory ReadJson(JsonReader reader, Type objectType, ReadOnlyMemory existingValue, bool hasExistingValue, JsonSerializer serializer) - { - var o = JToken.Load(reader); - return Convert.FromBase64String(o.ToObject()); - } - - public override void WriteJson(JsonWriter writer, ReadOnlyMemory value, JsonSerializer serializer) - { - writer.WriteValue(Convert.ToBase64String(value.Span)); - } - } -} diff --git a/src/RestServer/Newtonsoft/Json/SignerJsonConverter.cs b/src/RestServer/Newtonsoft/Json/SignerJsonConverter.cs deleted file mode 100644 index 50d596010..000000000 --- a/src/RestServer/Newtonsoft/Json/SignerJsonConverter.cs +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Network.P2P.Payloads; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json; - -public class SignerJsonConverter : JsonConverter -{ - public override bool CanRead => false; - - public override bool CanWrite => true; - - public override Signer ReadJson(JsonReader reader, Type objectType, Signer existingValue, bool hasExistingValue, JsonSerializer serializer) => - throw new NotImplementedException(); - - public override void WriteJson(JsonWriter writer, Signer value, JsonSerializer serializer) - { - var j = RestServerUtility.SignerToJToken(value, serializer); - j.WriteTo(writer); - } -} diff --git a/src/RestServer/Newtonsoft/Json/StackItemJsonConverter.cs b/src/RestServer/Newtonsoft/Json/StackItemJsonConverter.cs deleted file mode 100644 index dae151cb8..000000000 --- a/src/RestServer/Newtonsoft/Json/StackItemJsonConverter.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.VM.Types; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json -{ - public class StackItemJsonConverter : JsonConverter - { - public override StackItem ReadJson(JsonReader reader, Type objectType, StackItem existingValue, bool hasExistingValue, JsonSerializer serializer) - { - var t = JObject.Load(reader); - return RestServerUtility.StackItemFromJToken(t); - } - - public override void WriteJson(JsonWriter writer, StackItem value, JsonSerializer serializer) - { - var t = RestServerUtility.StackItemToJToken(value, null, serializer); - t.WriteTo(writer); - } - - - } -} diff --git a/src/RestServer/Newtonsoft/Json/TransactionAttributeJsonConverter.cs b/src/RestServer/Newtonsoft/Json/TransactionAttributeJsonConverter.cs deleted file mode 100644 index 4bc950fc9..000000000 --- a/src/RestServer/Newtonsoft/Json/TransactionAttributeJsonConverter.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Network.P2P.Payloads; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json; - -public class TransactionAttributeJsonConverter : JsonConverter -{ - public override bool CanRead => false; - - public override bool CanWrite => true; - - public override TransactionAttribute ReadJson(JsonReader reader, Type objectType, TransactionAttribute existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); - public override void WriteJson(JsonWriter writer, TransactionAttribute value, JsonSerializer serializer) - { - var j = RestServerUtility.TransactionAttributeToJToken(value, serializer); - j.WriteTo(writer); - } -} diff --git a/src/RestServer/Newtonsoft/Json/TransactionJsonConverter.cs b/src/RestServer/Newtonsoft/Json/TransactionJsonConverter.cs deleted file mode 100644 index 18080fe6a..000000000 --- a/src/RestServer/Newtonsoft/Json/TransactionJsonConverter.cs +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Network.P2P.Payloads; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json; - -public class TransactionJsonConverter : JsonConverter -{ - public override bool CanRead => false; - - public override bool CanWrite => true; - - public override Transaction ReadJson(JsonReader reader, Type objectType, Transaction existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); - public override void WriteJson(JsonWriter writer, Transaction value, JsonSerializer serializer) - { - var j = RestServerUtility.TransactionToJToken(value, serializer); - j.WriteTo(writer); - } -} diff --git a/src/RestServer/Newtonsoft/Json/UInt160JsonConverter.cs b/src/RestServer/Newtonsoft/Json/UInt160JsonConverter.cs deleted file mode 100644 index 581258efd..000000000 --- a/src/RestServer/Newtonsoft/Json/UInt160JsonConverter.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Plugins.RestServer.Exceptions; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json -{ - public class UInt160JsonConverter : JsonConverter - { - public override bool CanRead => true; - public override bool CanWrite => true; - - public override UInt160 ReadJson(JsonReader reader, Type objectType, UInt160 existingValue, bool hasExistingValue, JsonSerializer serializer) - { - var value = reader.Value?.ToString(); - try - { - return RestServerUtility.ConvertToScriptHash(value, RestServerPlugin.NeoSystem.Settings); - } - catch (FormatException) - { - throw new ScriptHashFormatException($"{value} is invalid."); - } - } - - public override void WriteJson(JsonWriter writer, UInt160 value, JsonSerializer serializer) - { - writer.WriteValue(value.ToString()); - } - } -} diff --git a/src/RestServer/Newtonsoft/Json/UInt256JsonConverter.cs b/src/RestServer/Newtonsoft/Json/UInt256JsonConverter.cs deleted file mode 100644 index b53814f01..000000000 --- a/src/RestServer/Newtonsoft/Json/UInt256JsonConverter.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Plugins.RestServer.Exceptions; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json -{ - public class UInt256JsonConverter : JsonConverter - { - public override UInt256 ReadJson(JsonReader reader, Type objectType, UInt256 existingValue, bool hasExistingValue, JsonSerializer serializer) - { - var value = reader.Value?.ToString(); - try - { - return UInt256.Parse(value); - } - catch (FormatException) - { - throw new UInt256FormatException($"{value} is invalid."); - } - } - - public override void WriteJson(JsonWriter writer, UInt256 value, JsonSerializer serializer) - { - writer.WriteValue(value.ToString()); - } - } -} diff --git a/src/RestServer/Newtonsoft/Json/VmArrayJsonConverter.cs b/src/RestServer/Newtonsoft/Json/VmArrayJsonConverter.cs deleted file mode 100644 index 350e65a07..000000000 --- a/src/RestServer/Newtonsoft/Json/VmArrayJsonConverter.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Array = Neo.VM.Types.Array; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json -{ - public class VmArrayJsonConverter : JsonConverter - { - public override Array ReadJson(JsonReader reader, Type objectType, Array existingValue, bool hasExistingValue, JsonSerializer serializer) - { - var t = JToken.Load(reader); - return RestServerUtility.StackItemFromJToken(t) as Array; - } - - public override void WriteJson(JsonWriter writer, Array value, JsonSerializer serializer) - { - var t = RestServerUtility.StackItemToJToken(value, null, serializer); - t.WriteTo(writer); - } - } -} diff --git a/src/RestServer/Newtonsoft/Json/VmBooleanJsonConverter.cs b/src/RestServer/Newtonsoft/Json/VmBooleanJsonConverter.cs deleted file mode 100644 index 662af037f..000000000 --- a/src/RestServer/Newtonsoft/Json/VmBooleanJsonConverter.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Boolean = Neo.VM.Types.Boolean; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json -{ - public class VmBooleanJsonConverter : JsonConverter - { - public override Boolean ReadJson(JsonReader reader, Type objectType, Boolean existingValue, bool hasExistingValue, JsonSerializer serializer) - { - var t = JToken.ReadFrom(reader); - return RestServerUtility.StackItemFromJToken(t) as Boolean; - } - - public override void WriteJson(JsonWriter writer, Boolean value, JsonSerializer serializer) - { - var t = RestServerUtility.StackItemToJToken(value, null, serializer); - t.WriteTo(writer); - } - } -} diff --git a/src/RestServer/Newtonsoft/Json/VmBufferJsonConverter.cs b/src/RestServer/Newtonsoft/Json/VmBufferJsonConverter.cs deleted file mode 100644 index 628489d6d..000000000 --- a/src/RestServer/Newtonsoft/Json/VmBufferJsonConverter.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Buffer = Neo.VM.Types.Buffer; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json -{ - public class VmBufferJsonConverter : JsonConverter - { - public override Buffer ReadJson(JsonReader reader, Type objectType, Buffer existingValue, bool hasExistingValue, JsonSerializer serializer) - { - var t = JToken.ReadFrom(reader); - return RestServerUtility.StackItemFromJToken(t) as Buffer; - } - - public override void WriteJson(JsonWriter writer, Buffer value, JsonSerializer serializer) - { - var t = RestServerUtility.StackItemToJToken(value, null, serializer); - t.WriteTo(writer); - } - } -} diff --git a/src/RestServer/Newtonsoft/Json/VmByteStringJsonConverter.cs b/src/RestServer/Newtonsoft/Json/VmByteStringJsonConverter.cs deleted file mode 100644 index 869484d3f..000000000 --- a/src/RestServer/Newtonsoft/Json/VmByteStringJsonConverter.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.VM.Types; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json -{ - public class VmByteStringJsonConverter : JsonConverter - { - public override ByteString ReadJson(JsonReader reader, Type objectType, ByteString existingValue, bool hasExistingValue, JsonSerializer serializer) - { - var t = JToken.ReadFrom(reader); - return RestServerUtility.StackItemFromJToken(t) as ByteString; - } - - public override void WriteJson(JsonWriter writer, ByteString value, JsonSerializer serializer) - { - var t = RestServerUtility.StackItemToJToken(value, null, serializer); - t.WriteTo(writer); - } - } -} diff --git a/src/RestServer/Newtonsoft/Json/VmIntegerJsonConverter.cs b/src/RestServer/Newtonsoft/Json/VmIntegerJsonConverter.cs deleted file mode 100644 index e30b22a38..000000000 --- a/src/RestServer/Newtonsoft/Json/VmIntegerJsonConverter.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using Integer = Neo.VM.Types.Integer; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json -{ - public class VmIntegerJsonConverter : JsonConverter - { - public override Integer ReadJson(JsonReader reader, Type objectType, Integer existingValue, bool hasExistingValue, JsonSerializer serializer) - { - var t = JToken.ReadFrom(reader); - return RestServerUtility.StackItemFromJToken(t) as Integer; - } - - public override void WriteJson(JsonWriter writer, Integer value, JsonSerializer serializer) - { - var t = RestServerUtility.StackItemToJToken(value, null, serializer); - t.WriteTo(writer); - } - } -} diff --git a/src/RestServer/Newtonsoft/Json/VmMapJsonConverter.cs b/src/RestServer/Newtonsoft/Json/VmMapJsonConverter.cs deleted file mode 100644 index ce467347c..000000000 --- a/src/RestServer/Newtonsoft/Json/VmMapJsonConverter.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.VM.Types; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json -{ - public class VmMapJsonConverter : JsonConverter - { - public override Map ReadJson(JsonReader reader, Type objectType, Map existingValue, bool hasExistingValue, JsonSerializer serializer) - { - var t = JToken.Load(reader); - return RestServerUtility.StackItemFromJToken(t) as Map; - } - - public override void WriteJson(JsonWriter writer, Map value, JsonSerializer serializer) - { - var t = RestServerUtility.StackItemToJToken(value, null, serializer); - t.WriteTo(writer); - } - } -} diff --git a/src/RestServer/Newtonsoft/Json/VmNullJsonConverter.cs b/src/RestServer/Newtonsoft/Json/VmNullJsonConverter.cs deleted file mode 100644 index 2bafeaf52..000000000 --- a/src/RestServer/Newtonsoft/Json/VmNullJsonConverter.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.VM.Types; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json -{ - public class VmNullJsonConverter : JsonConverter - { - public override Null ReadJson(JsonReader reader, Type objectType, Null existingValue, bool hasExistingValue, JsonSerializer serializer) - { - var t = JToken.ReadFrom(reader); - return RestServerUtility.StackItemFromJToken(t) as Null; - } - - public override void WriteJson(JsonWriter writer, Null value, JsonSerializer serializer) - { - var t = RestServerUtility.StackItemToJToken(value, null, serializer); - t.WriteTo(writer); - } - } -} diff --git a/src/RestServer/Newtonsoft/Json/VmPointerJsonConverter.cs b/src/RestServer/Newtonsoft/Json/VmPointerJsonConverter.cs deleted file mode 100644 index ba1da6bec..000000000 --- a/src/RestServer/Newtonsoft/Json/VmPointerJsonConverter.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.VM.Types; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json -{ - public class VmPointerJsonConverter : JsonConverter - { - public override Pointer ReadJson(JsonReader reader, Type objectType, Pointer existingValue, bool hasExistingValue, JsonSerializer serializer) - { - var t = JToken.ReadFrom(reader); - return RestServerUtility.StackItemFromJToken(t) as Pointer; - } - - public override void WriteJson(JsonWriter writer, Pointer value, JsonSerializer serializer) - { - var t = RestServerUtility.StackItemToJToken(value, null, serializer); - t.WriteTo(writer); - } - } -} diff --git a/src/RestServer/Newtonsoft/Json/VmStructJsonConverter.cs b/src/RestServer/Newtonsoft/Json/VmStructJsonConverter.cs deleted file mode 100644 index 05af0dd90..000000000 --- a/src/RestServer/Newtonsoft/Json/VmStructJsonConverter.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.VM.Types; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json -{ - public class VmStructJsonConverter : JsonConverter - { - public override Struct ReadJson(JsonReader reader, Type objectType, Struct existingValue, bool hasExistingValue, JsonSerializer serializer) - { - var t = JToken.Load(reader); - return RestServerUtility.StackItemFromJToken(t) as Struct; - } - - public override void WriteJson(JsonWriter writer, Struct value, JsonSerializer serializer) - { - var t = RestServerUtility.StackItemToJToken(value, null, serializer); - t.WriteTo(writer); - } - } -} diff --git a/src/RestServer/Newtonsoft/Json/WitnessConditionJsonConverter.cs b/src/RestServer/Newtonsoft/Json/WitnessConditionJsonConverter.cs deleted file mode 100644 index 342a37654..000000000 --- a/src/RestServer/Newtonsoft/Json/WitnessConditionJsonConverter.cs +++ /dev/null @@ -1,95 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Cryptography.ECC; -using Neo.Network.P2P.Payloads.Conditions; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json -{ - public sealed class WitnessConditionJsonConverter : JsonConverter - { - public override bool CanWrite => true; - public override bool CanRead => true; - - public override WitnessCondition ReadJson(JsonReader reader, Type objectType, WitnessCondition existingValue, bool hasExistingValue, JsonSerializer serializer) - { - var token = JToken.ReadFrom(reader); - if (token.Type == JTokenType.Object) - return FromJson((JObject)token); - throw new NotSupportedException($"{nameof(WitnessCondition)} Type({token.Type}) is not supported from JSON."); - } - - public override void WriteJson(JsonWriter writer, WitnessCondition value, JsonSerializer serializer) - { - var j = RestServerUtility.WitnessConditionToJToken(value, serializer); - j.WriteTo(writer); - } - - public static WitnessCondition FromJson(JObject o) - { - ArgumentNullException.ThrowIfNull(o, nameof(o)); - - var typeProp = o.Properties().Single(s => EqualsIgnoreCase(s.Name, "type")); - var type = Enum.Parse(typeProp.Value()); - try - { - switch (type) - { - case WitnessConditionType.Boolean: - var valueProp = o.Properties().Single(s => EqualsIgnoreCase(s.Name, "expression")); - return new BooleanCondition() { Expression = valueProp.Value() }; - case WitnessConditionType.Not: - valueProp = o.Properties().Single(s => EqualsIgnoreCase(s.Name, "expression")); - return new NotCondition() { Expression = FromJson((JObject)valueProp.Value) }; - case WitnessConditionType.And: - valueProp = o.Properties().Single(s => EqualsIgnoreCase(s.Name, "expressions")); - if (valueProp.Type == JTokenType.Array) - { - var array = (JArray)valueProp.Value; - return new AndCondition() { Expressions = array.Select(s => FromJson((JObject)s)).ToArray() }; - } - break; - case WitnessConditionType.Or: - valueProp = o.Properties().Single(s => EqualsIgnoreCase(s.Name, "expressions")); - if (valueProp.Type == JTokenType.Array) - { - var array = (JArray)valueProp.Value; - return new OrCondition() { Expressions = array.Select(s => FromJson((JObject)s)).ToArray() }; - } - break; - case WitnessConditionType.ScriptHash: - valueProp = o.Properties().Single(s => EqualsIgnoreCase(s.Name, "hash")); - return new ScriptHashCondition() { Hash = UInt160.Parse(valueProp.Value()) }; - case WitnessConditionType.Group: - valueProp = o.Properties().Single(s => EqualsIgnoreCase(s.Name, "group")); - return new GroupCondition() { Group = ECPoint.Parse(valueProp.Value(), ECCurve.Secp256r1) }; - case WitnessConditionType.CalledByEntry: - return new CalledByEntryCondition(); - case WitnessConditionType.CalledByContract: - valueProp = o.Properties().Single(s => EqualsIgnoreCase(s.Name, "hash")); - return new CalledByContractCondition() { Hash = UInt160.Parse(valueProp.Value()) }; - case WitnessConditionType.CalledByGroup: - valueProp = o.Properties().Single(s => EqualsIgnoreCase(s.Name, "group")); - return new CalledByGroupCondition() { Group = ECPoint.Parse(valueProp.Value(), ECCurve.Secp256r1) }; - } - } - catch (ArgumentNullException ex) - { - throw new NotSupportedException($"{ex.ParamName} is not supported from JSON."); - } - throw new NotSupportedException($"WitnessConditionType({type}) is not supported from JSON."); - } - - private static bool EqualsIgnoreCase(string left, string right) => - left.Equals(right, StringComparison.InvariantCultureIgnoreCase); - } -} diff --git a/src/RestServer/Newtonsoft/Json/WitnessJsonConverter.cs b/src/RestServer/Newtonsoft/Json/WitnessJsonConverter.cs deleted file mode 100644 index 0ef8842c1..000000000 --- a/src/RestServer/Newtonsoft/Json/WitnessJsonConverter.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Network.P2P.Payloads; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json; - -public class WitnessJsonConverter : JsonConverter -{ - public override bool CanRead => false; - - public override bool CanWrite => true; - - public override Witness ReadJson(JsonReader reader, Type objectType, Witness existingValue, bool hasExistingValue, JsonSerializer serializer) - { - throw new NotImplementedException(); - } - - public override void WriteJson(JsonWriter writer, Witness value, JsonSerializer serializer) - { - var j = RestServerUtility.WitnessToJToken(value, serializer); - j.WriteTo(writer); - } -} diff --git a/src/RestServer/Newtonsoft/Json/WitnessRuleJsonConverter.cs b/src/RestServer/Newtonsoft/Json/WitnessRuleJsonConverter.cs deleted file mode 100644 index f39590647..000000000 --- a/src/RestServer/Newtonsoft/Json/WitnessRuleJsonConverter.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Network.P2P.Payloads; -using Newtonsoft.Json; - -namespace Neo.Plugins.RestServer.Newtonsoft.Json; - -public class WitnessRuleJsonConverter : JsonConverter -{ - public override WitnessRule ReadJson(JsonReader reader, Type objectType, WitnessRule existingValue, bool hasExistingValue, JsonSerializer serializer) => throw new NotImplementedException(); - public override void WriteJson(JsonWriter writer, WitnessRule value, JsonSerializer serializer) - { - var j = RestServerUtility.WitnessRuleToJToken(value, serializer); - j.WriteTo(writer); - } -} diff --git a/src/RestServer/Providers/BlackListControllerFeatureProvider.cs b/src/RestServer/Providers/BlackListControllerFeatureProvider.cs deleted file mode 100644 index 44926ff80..000000000 --- a/src/RestServer/Providers/BlackListControllerFeatureProvider.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Controllers; -using System.Reflection; - -namespace Neo.Plugins.RestServer.Providers -{ - internal class BlackListControllerFeatureProvider : ControllerFeatureProvider - { - private readonly RestServerSettings _settings; - - public BlackListControllerFeatureProvider() - { - _settings = RestServerSettings.Current; - } - - protected override bool IsController(TypeInfo typeInfo) - { - if (typeInfo.IsDefined(typeof(ApiControllerAttribute)) == false) // Rest API - return false; - if (_settings.DisableControllers.Any(a => a.Equals(typeInfo.Name, StringComparison.OrdinalIgnoreCase))) // BlackList - return false; - return base.IsController(typeInfo); // Default check - } - } -} diff --git a/src/RestServer/RestServer.csproj b/src/RestServer/RestServer.csproj deleted file mode 100644 index e07ffa4e6..000000000 --- a/src/RestServer/RestServer.csproj +++ /dev/null @@ -1,25 +0,0 @@ - - - - Neo.Plugins.RestServer - Neo.Plugins.RestServer - net7.0 - enable - disable - true - $(NoWarn);1591 - - - - - - - - - - - - - - - diff --git a/src/RestServer/RestServerPlugin.Console.cs b/src/RestServer/RestServerPlugin.Console.cs deleted file mode 100644 index 667a153ae..000000000 --- a/src/RestServer/RestServerPlugin.Console.cs +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Plugins.RestServer.Controllers.v1; -using System.Text; - -namespace Neo.Plugins.RestServer -{ - public partial class RestServerPlugin - { - [ConsoleCommand("rest sessions", Category = "RestServer Commands", Description = "Shows all active wallet sessions.")] - private void OnShowWalletSessions() - { - - if (WalletController.WalletSessions.Any()) - ConsoleHelper.Info("---------", "Sessions", "---------"); - - foreach (var (key, value) in WalletController.WalletSessions) - { - TimeSpan expires = value.Expires.Subtract(DateTime.Now); - var wallet = value.Wallet; - ConsoleHelper.Info(" Name: ", wallet.Name ?? "\"\""); - ConsoleHelper.Info(" Path: ", wallet.Path); - ConsoleHelper.Info("Version: ", wallet.Version.ToString()); - ConsoleHelper.Info("Session: ", key.ToString("n")); - ConsoleHelper.Info("Expires: ", Math.Round(expires.TotalSeconds, 0).ToString(), " second(s)."); - - if (WalletController.WalletSessions.Count > 1) - ConsoleHelper.Info(); - } - - if (WalletController.WalletSessions.Any()) - ConsoleHelper.Info("--------------------------"); - - ConsoleHelper.Info(" Total: ", WalletController.WalletSessions.Count.ToString(), " session(s)."); - } - - [ConsoleCommand("rest kill", Category = "RestServer Commands", Description = "Kills an active wallet session.")] - private void OnKillWalletSession(string sessionId) - { - if (Guid.TryParse(sessionId, out var session) == false) - { - ConsoleHelper.Warning("Invalid session id."); - return; - } - - ConsoleHelper.Info($"You are about to kill ", session.ToString("n"), " session!"); - var answer = ReadUserInput($"Are you sure?"); - if (answer.Equals("yes", StringComparison.InvariantCultureIgnoreCase) || answer.Equals("y", StringComparison.InvariantCultureIgnoreCase)) - { - if (WalletController.WalletSessions.TryRemove(session, out _)) - ConsoleHelper.Info("Session ", session.ToString("n"), " has terminated."); - else - ConsoleHelper.Error($"Session {session:n} could not be terminated. Try again later."); - } - } - - [ConsoleCommand("rest killall", Category = "RestServer Commands", Description = "Kills all active wallet sessions.")] - public void OnKillallWalletSessions() - { - if (WalletController.WalletSessions.Any() == false) - { - ConsoleHelper.Info("No ", "active", " sessions."); - return; - } - - var answer = ReadUserInput($"Kill all active wallet sessions?"); - if (answer.Equals("yes", StringComparison.InvariantCultureIgnoreCase) || answer.Equals("y", StringComparison.InvariantCultureIgnoreCase)) - { - foreach (var (session, _) in WalletController.WalletSessions) - { - if (WalletController.WalletSessions.TryRemove(session, out _)) - ConsoleHelper.Info("Session ", session.ToString("n"), " has terminated."); - else - ConsoleHelper.Error($"Session {session:n} could not be terminated. Try again later."); - } - } - } - - private string ReadUserInput(string prompt, bool password = false) - { - const string t = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; - var sb = new StringBuilder(); - - if (!string.IsNullOrEmpty(prompt)) - { - Console.Write(prompt + ": "); - } - - var prevForeground = Console.ForegroundColor; - Console.ForegroundColor = ConsoleColor.Yellow; - - if (Console.IsInputRedirected) - { - // neo-gui Console require it - sb.Append(Console.ReadLine()); - } - else - { - ConsoleKeyInfo key; - do - { - key = Console.ReadKey(true); - - if (t.IndexOf(key.KeyChar) != -1) - { - sb.Append(key.KeyChar); - Console.Write(password ? '*' : key.KeyChar); - } - else if (key.Key == ConsoleKey.Backspace && sb.Length > 0) - { - sb.Length--; - Console.Write("\b \b"); - } - } while (key.Key != ConsoleKey.Enter); - } - - Console.ForegroundColor = prevForeground; - Console.WriteLine(); - return sb.ToString(); - } - } -} diff --git a/src/RestServer/RestServerPlugin.cs b/src/RestServer/RestServerPlugin.cs deleted file mode 100644 index cbab7d4e4..000000000 --- a/src/RestServer/RestServerPlugin.cs +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 Akka.Actor; -using Neo.ConsoleService; -using Neo.Network.P2P; - -namespace Neo.Plugins.RestServer -{ - public partial class RestServerPlugin : Plugin - { - public override string Name => "RestServer"; - public override string Description => "Enables REST Web Sevices for the node"; - - #region Globals - - private RestServerSettings _settings; - private RestWebServer _server; - - #endregion - - #region Static Globals - - internal static NeoSystem NeoSystem { get; private set; } - internal static LocalNode LocalNode { get; private set; } - - #endregion - - protected override void Configure() - { - RestServerSettings.Load(GetConfiguration()); - _settings = RestServerSettings.Current; - } - - protected override void OnSystemLoaded(NeoSystem system) - { - if (_settings.EnableCors && _settings.EnableBasicAuthentication && _settings.AllowOrigins.Length == 0) - { - ConsoleHelper.Warning("RestServer: CORS is misconfigured!"); - ConsoleHelper.Info($"You have {nameof(_settings.EnableCors)} and {nameof(_settings.EnableBasicAuthentication)} enabled but"); - ConsoleHelper.Info($"{nameof(_settings.AllowOrigins)} is empty in config.json for RestServer."); - ConsoleHelper.Info("You must add url origins to the list to have CORS work from"); - ConsoleHelper.Info($"browser with basic authentication enabled."); - ConsoleHelper.Info($"Example: \"AllowOrigins\": [\"http://{_settings.BindAddress}:{_settings.Port}\"]"); - } - if (system.Settings.Network == _settings.Network) - { - NeoSystem = system; - LocalNode = system.LocalNode.Ask(new LocalNode.GetInstance()).Result; - } - _server = new RestWebServer(); - _server.Start(); - } - } -} diff --git a/src/RestServer/RestServerSettings.cs b/src/RestServer/RestServerSettings.cs deleted file mode 100644 index 188abfeb9..000000000 --- a/src/RestServer/RestServerSettings.cs +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 Microsoft.Extensions.Configuration; -using Neo.Plugins.RestServer.Newtonsoft.Json; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; -using Newtonsoft.Json.Serialization; -using System.IO.Compression; -using System.Net; - -namespace Neo.Plugins.RestServer -{ - public class RestServerSettings - { - #region Settings - - public uint Network { get; init; } - public IPAddress BindAddress { get; init; } - public uint Port { get; init; } - public uint KeepAliveTimeout { get; init; } - public string SslCertFile { get; init; } - public string SslCertPassword { get; init; } - public string[] TrustedAuthorities { get; init; } - public bool EnableBasicAuthentication { get; init; } - public string RestUser { get; init; } - public string RestPass { get; init; } - public bool EnableCors { get; init; } - public string[] AllowOrigins { get; init; } - public string[] DisableControllers { get; init; } - public bool EnableCompression { get; init; } - public CompressionLevel CompressionLevel { get; init; } - public bool EnableForwardedHeaders { get; init; } - public bool EnableSwagger { get; init; } - public uint MaxPageSize { get; init; } - public long MaxConcurrentConnections { get; init; } - public long MaxTransactionFee { get; init; } - public long MaxGasInvoke { get; init; } - public uint MaxTransactionSize { get; init; } - public uint WalletSessionTimeout { get; init; } - public JsonSerializerSettings JsonSerializerSettings { get; init; } - - #endregion - - #region Static Functions - - public static RestServerSettings Current { get; private set; } - public static RestServerSettings Default { get; } = new() - { - Network = 860833102u, - BindAddress = IPAddress.Loopback, - Port = 10339u, - KeepAliveTimeout = 120u, - SslCertFile = "", - SslCertPassword = "", - TrustedAuthorities = Array.Empty(), - EnableBasicAuthentication = false, - RestUser = string.Empty, - RestPass = string.Empty, - EnableCors = false, - AllowOrigins = Array.Empty(), - DisableControllers = Array.Empty(), - EnableCompression = false, - CompressionLevel = CompressionLevel.SmallestSize, - EnableForwardedHeaders = false, - EnableSwagger = false, - MaxPageSize = 50u, - MaxConcurrentConnections = 40L, - MaxTransactionFee = 0_10000000L, - MaxGasInvoke = 0_20000000L, - MaxTransactionSize = 1024u, - WalletSessionTimeout = 120u, - JsonSerializerSettings = new JsonSerializerSettings() - { - ContractResolver = new CamelCasePropertyNamesContractResolver(), - MissingMemberHandling = MissingMemberHandling.Error, - NullValueHandling = NullValueHandling.Include, - Formatting = Formatting.None, - Converters = new JsonConverter[] - { - new StringEnumConverter(), - new BigDecimalJsonConverter(), - new BlockHeaderJsonConverter(), - new BlockJsonConverter(), - new ContractAbiJsonConverter(), - new ContractEventDescriptorJsonConverter(), - new ContractGroupJsonConverter(), - new ContractJsonConverter(), - new ContractManifestJsonConverter(), - new ContractMethodJsonConverter(), - new ContractMethodParametersJsonConverter(), - new ContractParameterDefinitionJsonConverter(), - new ContractParameterJsonConverter(), - new ContractPermissionDescriptorJsonConverter(), - new ContractPermissionJsonConverter(), - new ECPointJsonConverter(), - new GuidJsonConverter(), - new InteropInterfaceJsonConverter(), - new MethodTokenJsonConverter(), - new NefFileJsonConverter(), - new ReadOnlyMemoryBytesJsonConverter(), - new SignerJsonConverter(), - new StackItemJsonConverter(), - new TransactionAttributeJsonConverter(), - new TransactionJsonConverter(), - new UInt160JsonConverter(), - new UInt256JsonConverter(), - new VmArrayJsonConverter(), - new VmBooleanJsonConverter(), - new VmBufferJsonConverter(), - new VmByteStringJsonConverter(), - new VmIntegerJsonConverter(), - new VmMapJsonConverter(), - new VmNullJsonConverter(), - new VmPointerJsonConverter(), - new VmStructJsonConverter(), - new WitnessConditionJsonConverter(), - new WitnessJsonConverter(), - new WitnessRuleJsonConverter(), - }, - }, - }; - - public static void Load(IConfigurationSection section) => - Current = new() - { - Network = section.GetValue(nameof(Network), Default.Network), - BindAddress = IPAddress.Parse(section.GetSection(nameof(BindAddress)).Value), - Port = section.GetValue(nameof(Port), Default.Port), - KeepAliveTimeout = section.GetValue(nameof(KeepAliveTimeout), Default.KeepAliveTimeout), - SslCertFile = section.GetValue(nameof(SslCertFile), Default.SslCertFile), - SslCertPassword = section.GetValue(nameof(SslCertPassword), Default.SslCertPassword), - TrustedAuthorities = section.GetSection(nameof(TrustedAuthorities))?.Get() ?? Default.TrustedAuthorities, - EnableBasicAuthentication = section.GetValue(nameof(EnableBasicAuthentication), Default.EnableBasicAuthentication), - RestUser = section.GetValue(nameof(RestUser), Default.RestUser), - RestPass = section.GetValue(nameof(RestPass), Default.RestPass), - EnableCors = section.GetValue(nameof(EnableCors), Default.EnableCors), - AllowOrigins = section.GetSection(nameof(AllowOrigins))?.Get() ?? Default.AllowOrigins, - DisableControllers = section.GetSection(nameof(DisableControllers))?.Get() ?? Default.DisableControllers, - EnableCompression = section.GetValue(nameof(EnableCompression), Default.EnableCompression), - CompressionLevel = section.GetValue(nameof(CompressionLevel), Default.CompressionLevel), - EnableForwardedHeaders = section.GetValue(nameof(EnableForwardedHeaders), Default.EnableForwardedHeaders), - EnableSwagger = section.GetValue(nameof(EnableSwagger), Default.EnableSwagger), - MaxPageSize = section.GetValue(nameof(MaxPageSize), Default.MaxPageSize), - MaxConcurrentConnections = section.GetValue(nameof(MaxConcurrentConnections), Default.MaxConcurrentConnections), - MaxTransactionFee = section.GetValue(nameof(MaxTransactionFee), Default.MaxTransactionFee), - MaxGasInvoke = section.GetValue(nameof(MaxGasInvoke), Default.MaxGasInvoke), - MaxTransactionSize = section.GetValue(nameof(MaxTransactionSize), Default.MaxTransactionSize), - WalletSessionTimeout = section.GetValue(nameof(WalletSessionTimeout), Default.WalletSessionTimeout), - JsonSerializerSettings = Default.JsonSerializerSettings, - }; - - #endregion - } -} diff --git a/src/RestServer/RestServerUtility.JTokens.cs b/src/RestServer/RestServerUtility.JTokens.cs deleted file mode 100644 index 4f1d7262c..000000000 --- a/src/RestServer/RestServerUtility.JTokens.cs +++ /dev/null @@ -1,302 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Network.P2P.Payloads; -using Neo.Network.P2P.Payloads.Conditions; -using Neo.SmartContract; -using Neo.SmartContract.Manifest; -using Newtonsoft.Json.Linq; - -namespace Neo.Plugins.RestServer -{ - public static partial class RestServerUtility - { - public static JToken BlockHeaderToJToken(Header header, global::Newtonsoft.Json.JsonSerializer serializer) => - JToken.FromObject(new - { - header.Timestamp, - header.Version, - header.PrimaryIndex, - header.Index, - header.Nonce, - header.Hash, - header.MerkleRoot, - header.PrevHash, - header.NextConsensus, - Witness = WitnessToJToken(header.Witness, serializer), - header.Size, - }, serializer); - - public static JToken WitnessToJToken(Witness witness, global::Newtonsoft.Json.JsonSerializer serializer) => - JToken.FromObject(new - { - witness.InvocationScript, - witness.VerificationScript, - witness.ScriptHash, - }, serializer); - - public static JToken BlockToJToken(Block block, global::Newtonsoft.Json.JsonSerializer serializer) => - JToken.FromObject(new - { - block.Timestamp, - block.Version, - block.PrimaryIndex, - block.Index, - block.Nonce, - block.Hash, - block.MerkleRoot, - block.PrevHash, - block.NextConsensus, - Witness = WitnessToJToken(block.Witness, serializer), - block.Size, - Transactions = block.Transactions.Select(s => TransactionToJToken(s, serializer)), - }, serializer); - - public static JToken TransactionToJToken(Transaction tx, global::Newtonsoft.Json.JsonSerializer serializer) => - JToken.FromObject(new - { - tx.Hash, - tx.Sender, - tx.Script, - tx.FeePerByte, - tx.NetworkFee, - tx.SystemFee, - tx.Size, - tx.Nonce, - tx.Version, - tx.ValidUntilBlock, - Witnesses = tx.Witnesses.Select(s => WitnessToJToken(s, serializer)), - Signers = tx.Signers.Select(s => SignerToJToken(s, serializer)), - Attributes = tx.Attributes.Select(s => TransactionAttributeToJToken(s, serializer)), - }, serializer); - - public static JToken SignerToJToken(Signer signer, global::Newtonsoft.Json.JsonSerializer serializer) => - JToken.FromObject(new - { - Rules = signer.Rules.Select(s => WitnessRuleToJToken(s, serializer)), - signer.Account, - signer.AllowedContracts, - signer.AllowedGroups, - signer.Scopes, - }, serializer); - - public static JToken TransactionAttributeToJToken(TransactionAttribute attribute, global::Newtonsoft.Json.JsonSerializer serializer) => - JToken.FromObject(new - { - attribute.Type, - attribute.AllowMultiple, - }, serializer); - - public static JToken WitnessRuleToJToken(WitnessRule rule, global::Newtonsoft.Json.JsonSerializer serializer) => - JToken.FromObject(new - { - rule.Action, - Condition = WitnessConditionToJToken(rule.Condition, serializer), - }, serializer); - - public static JToken WitnessConditionToJToken(WitnessCondition condition, global::Newtonsoft.Json.JsonSerializer serializer) - { - JToken j = JValue.CreateNull(); - switch (condition.Type) - { - case WitnessConditionType.Boolean: - var b = condition as BooleanCondition; - j = JToken.FromObject(new - { - b.Type, - b.Expression, - }, serializer); - break; - case WitnessConditionType.Not: - var n = condition as NotCondition; - j = JToken.FromObject(new - { - n.Type, - Expression = WitnessConditionToJToken(n.Expression, serializer), - }, serializer); - break; - case WitnessConditionType.And: - var a = condition as AndCondition; - j = JToken.FromObject(new - { - a.Type, - Expressions = a.Expressions.Select(s => WitnessConditionToJToken(s, serializer)), - }, serializer); - break; - case WitnessConditionType.Or: - var o = condition as OrCondition; - j = JToken.FromObject(new - { - o.Type, - Expressions = o.Expressions.Select(s => WitnessConditionToJToken(s, serializer)), - }, serializer); - break; - case WitnessConditionType.ScriptHash: - var s = condition as ScriptHashCondition; - j = JToken.FromObject(new - { - s.Type, - s.Hash, - }, serializer); - break; - case WitnessConditionType.Group: - var g = condition as GroupCondition; - j = JToken.FromObject(new - { - g.Type, - g.Group, - }, serializer); - break; - case WitnessConditionType.CalledByEntry: - var e = condition as CalledByEntryCondition; - j = JToken.FromObject(new - { - e.Type, - }, serializer); - break; - case WitnessConditionType.CalledByContract: - var c = condition as CalledByContractCondition; - j = JToken.FromObject(new - { - c.Type, - c.Hash, - }, serializer); - break; - case WitnessConditionType.CalledByGroup: - var p = condition as CalledByGroupCondition; - j = JToken.FromObject(new - { - p.Type, - p.Group, - }, serializer); - break; - default: - break; - } - return j; - } - - public static JToken ContractStateToJToken(ContractState contract, global::Newtonsoft.Json.JsonSerializer serializer) => - JToken.FromObject(new - { - contract.Id, - contract.Manifest.Name, - contract.Hash, - Manifest = ContractManifestToJToken(contract.Manifest, serializer), - NefFile = ContractNefFileToJToken(contract.Nef, serializer), - }, serializer); - - public static JToken ContractManifestToJToken(ContractManifest manifest, global::Newtonsoft.Json.JsonSerializer serializer) => - JToken.FromObject(new - { - manifest.Name, - Abi = ContractAbiToJToken(manifest.Abi, serializer), - Groups = manifest.Groups.Select(s => ContractGroupToJToken(s, serializer)), - Permissions = manifest.Permissions.Select(s => ContractPermissionToJToken(s, serializer)), - Trusts = manifest.Trusts.Select(s => ContractPermissionDescriptorToJToken(s, serializer)), - manifest.SupportedStandards, - Extra = manifest.Extra.Count > 0 ? - new JObject(manifest.Extra.Properties.Select(s => new JProperty(s.Key.ToString(), s.Value.AsString()))) : - null, - }, serializer); - - public static JToken ContractAbiToJToken(ContractAbi abi, global::Newtonsoft.Json.JsonSerializer serializer) => - JToken.FromObject(new - { - Methods = abi.Methods.Select(s => ContractMethodToJToken(s, serializer)), - Events = abi.Events.Select(s => ContractEventToJToken(s, serializer)), - }, serializer); - - public static JToken ContractMethodToJToken(ContractMethodDescriptor method, global::Newtonsoft.Json.JsonSerializer serializer) => - JToken.FromObject(new - { - method.Name, - method.Safe, - method.Offset, - Parameters = method.Parameters.Select(s => ContractMethodParameterToJToken(s, serializer)), - method.ReturnType, - }, serializer); - - public static JToken ContractMethodParameterToJToken(ContractParameterDefinition parameter, global::Newtonsoft.Json.JsonSerializer serializer) => - JToken.FromObject(new - { - parameter.Type, - parameter.Name, - }, serializer); - - public static JToken ContractGroupToJToken(ContractGroup group, global::Newtonsoft.Json.JsonSerializer serializer) => - JToken.FromObject(new - { - group.PubKey, - group.Signature, - }, serializer); - - public static JToken ContractPermissionToJToken(ContractPermission permission, global::Newtonsoft.Json.JsonSerializer serializer) => - JToken.FromObject(new - { - Contract = ContractPermissionDescriptorToJToken(permission.Contract, serializer), - Methods = permission.Methods.Count > 0 ? - permission.Methods.Select(s => s).ToArray() : - (object)"*", - }, serializer); - - public static JToken ContractPermissionDescriptorToJToken(ContractPermissionDescriptor desc, global::Newtonsoft.Json.JsonSerializer serializer) - { - JToken j = JValue.CreateNull(); - if (desc.IsWildcard) - j = JValue.CreateString("*"); - else if (desc.IsGroup) - j = JToken.FromObject(new - { - desc.Group - }, serializer); - else if (desc.IsHash) - j = JToken.FromObject(new - { - desc.Hash, - }, serializer); - return j; - } - - public static JToken ContractEventToJToken(ContractEventDescriptor desc, global::Newtonsoft.Json.JsonSerializer serializer) => - JToken.FromObject(new - { - desc.Name, - Parameters = desc.Parameters.Select(s => ContractParameterDefinitionToJToken(s, serializer)), - }, serializer); - - public static JToken ContractParameterDefinitionToJToken(ContractParameterDefinition definition, global::Newtonsoft.Json.JsonSerializer serializer) => - JToken.FromObject(new - { - definition.Type, - definition.Name, - }, serializer); - - public static JToken ContractNefFileToJToken(NefFile nef, global::Newtonsoft.Json.JsonSerializer serializer) => - JToken.FromObject(new - { - Checksum = nef.CheckSum, - nef.Compiler, - nef.Script, - nef.Source, - Tokens = nef.Tokens.Select(s => MethodTokenToJToken(s, serializer)), - }, serializer); - - public static JToken MethodTokenToJToken(MethodToken token, global::Newtonsoft.Json.JsonSerializer serializer) => - JToken.FromObject(new - { - token.Hash, - token.Method, - token.CallFlags, - token.ParametersCount, - token.HasReturnValue, - }, serializer); - } -} diff --git a/src/RestServer/RestServerUtility.cs b/src/RestServer/RestServerUtility.cs deleted file mode 100644 index 82c6fb39f..000000000 --- a/src/RestServer/RestServerUtility.cs +++ /dev/null @@ -1,346 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Cryptography.ECC; -using Neo.SmartContract; -using Neo.VM.Types; -using Neo.Wallets; -using Newtonsoft.Json.Linq; -using System.Numerics; -using Array = Neo.VM.Types.Array; -using Boolean = Neo.VM.Types.Boolean; -using Buffer = Neo.VM.Types.Buffer; - -namespace Neo.Plugins.RestServer -{ - public static partial class RestServerUtility - { - public static UInt160 ConvertToScriptHash(string address, ProtocolSettings settings) - { - if (UInt160.TryParse(address, out var scriptHash)) - return scriptHash; - return address?.ToScriptHash(settings.AddressVersion); - } - - public static bool TryConvertToScriptHash(string address, ProtocolSettings settings, out UInt160 scriptHash) - { - try - { - if (UInt160.TryParse(address, out scriptHash)) - return true; - scriptHash = address.ToScriptHash(settings.AddressVersion); - return true; - } - catch - { - scriptHash = UInt160.Zero; - return false; - } - } - - public static StackItem StackItemFromJToken(JToken json) - { - if (json.Type == JTokenType.Object) - { - var jsonObject = json as JObject; - var props = jsonObject.Properties(); - var typeProp = props.SingleOrDefault(s => s.Name.Equals("type", StringComparison.InvariantCultureIgnoreCase)); - var valueProp = props.SingleOrDefault(s => s.Name.Equals("value", StringComparison.InvariantCultureIgnoreCase)); - - if (typeProp != null) - { - StackItem s = StackItem.Null; - var type = Enum.Parse(typeProp.ToObject(), true); - var value = valueProp.Value; - - switch (type) - { - case StackItemType.Struct: - if (value.Type == JTokenType.Array) - { - var st = new Struct(); - foreach (var item in (JArray)value) - st.Add(StackItemFromJToken(item)); - s = st; - } - break; - case StackItemType.Array: - if (value.Type == JTokenType.Array) - { - var a = new Array(); - foreach (var item in (JArray)value) - a.Add(StackItemFromJToken(item)); - s = a; - } - break; - case StackItemType.Map: - if (value.Type == JTokenType.Array) - { - var m = new Map(); - foreach (var item in (JArray)value) - { - if (item.Type != JTokenType.Object) - continue; - var vprops = ((JObject)item).Properties(); - var keyProps = vprops.SingleOrDefault(s => s.Name.Equals("key", StringComparison.InvariantCultureIgnoreCase)); - var keyValueProps = vprops.SingleOrDefault(s => s.Name.Equals("value", StringComparison.InvariantCultureIgnoreCase)); - if (keyProps == null && keyValueProps == null) - continue; - var key = (PrimitiveType)StackItemFromJToken(keyProps?.Value); - m[key] = StackItemFromJToken(keyValueProps?.Value); - } - s = m; - } - break; - case StackItemType.Boolean: - s = value.ToObject() ? StackItem.True : StackItem.False; - break; - case StackItemType.Buffer: - s = new Buffer(Convert.FromBase64String(value.ToObject())); - break; - case StackItemType.ByteString: - s = new ByteString(Convert.FromBase64String(value.ToObject())); - break; - case StackItemType.Integer: - s = value.ToObject(); - break; - case StackItemType.InteropInterface: - s = new InteropInterface(Convert.FromBase64String(value.ToObject())); - break; - case StackItemType.Pointer: - s = new Pointer(null, value.ToObject()); - break; - default: - break; - } - return s; - } - } - throw new FormatException(); - } - - public static JToken StackItemToJToken(StackItem item, IList<(StackItem, JToken)> context, global::Newtonsoft.Json.JsonSerializer serializer) - { - JToken o = null; - switch (item) - { - case Struct @struct: - if (context is null) - context = new List<(StackItem, JToken)>(); - else - (_, o) = context.FirstOrDefault(f => ReferenceEquals(f.Item1, item)); - if (o is null) - { - context.Add((item, o)); - var a = @struct.Select(s => StackItemToJToken(s, context, serializer)); - o = JToken.FromObject(new - { - Type = StackItemType.Struct.ToString(), - Value = JArray.FromObject(a), - }, serializer); - } - break; - case Array array: - if (context is null) - context = new List<(StackItem, JToken)>(); - else - (_, o) = context.FirstOrDefault(f => ReferenceEquals(f.Item1, item)); - if (o is null) - { - context.Add((item, o)); - var a = array.Select(s => StackItemToJToken(s, context, serializer)); - o = JToken.FromObject(new - { - Type = StackItemType.Array.ToString(), - Value = JArray.FromObject(a, serializer), - }, serializer); - } - break; - case Map map: - if (context is null) - context = new List<(StackItem, JToken)>(); - else - (_, o) = context.FirstOrDefault(f => ReferenceEquals(f.Item1, item)); - if (o is null) - { - context.Add((item, o)); - var kvp = map.Select(s => - new KeyValuePair( - StackItemToJToken(s.Key, context, serializer), - StackItemToJToken(s.Value, context, serializer))); - o = JToken.FromObject(new - { - Type = StackItemType.Map.ToString(), - Value = JArray.FromObject(kvp, serializer), - }, serializer); - } - break; - case Boolean: - o = JToken.FromObject(new - { - Type = StackItemType.Boolean.ToString(), - Value = item.GetBoolean(), - }, serializer); - break; - case Buffer: - o = JToken.FromObject(new - { - Type = StackItemType.Buffer.ToString(), - Value = Convert.ToBase64String(item.GetSpan()), - }, serializer); - break; - case ByteString: - o = JToken.FromObject(new - { - Type = StackItemType.ByteString.ToString(), - Value = Convert.ToBase64String(item.GetSpan()), - }, serializer); - break; - case Integer: - o = JToken.FromObject(new - { - Type = StackItemType.Integer.ToString(), - Value = item.GetInteger(), - }, serializer); - break; - case InteropInterface: - o = JToken.FromObject(new - { - Type = StackItemType.InteropInterface.ToString(), - Value = Convert.ToBase64String(item.GetSpan()), - }); - break; - case Pointer pointer: - o = JToken.FromObject(new - { - Type = StackItemType.Pointer.ToString(), - Value = pointer.Position, - }, serializer); - break; - case Null: - case null: - o = JToken.FromObject(new - { - Type = StackItemType.Any.ToString(), - Value = JValue.CreateNull(), - }, serializer); - break; - default: - throw new NotSupportedException($"StackItemType({item.Type}) is not supported to JSON."); - } - return o; - } - - public static ContractParameter ContractParameterFromJToken(JToken token) - { - if (token.Type != JTokenType.Object) - throw new FormatException(); - - var obj = (JObject)token; - var typeProp = obj - .Properties() - .SingleOrDefault(a => a.Name.Equals("type", StringComparison.InvariantCultureIgnoreCase)); - var valueProp = obj - .Properties() - .SingleOrDefault(a => a.Name.Equals("value", StringComparison.InvariantCultureIgnoreCase)); - - if (typeProp == null || valueProp == null) - throw new FormatException(); - - var typeValue = Enum.Parse(typeProp.ToObject()); - - switch (typeValue) - { - case ContractParameterType.Any: - return new ContractParameter(ContractParameterType.Any); - case ContractParameterType.ByteArray: - return new ContractParameter() - { - Type = ContractParameterType.ByteArray, - Value = Convert.FromBase64String(valueProp.ToObject()), - }; - case ContractParameterType.Signature: - return new ContractParameter() - { - Type = ContractParameterType.Signature, - Value = Convert.FromBase64String(valueProp.ToObject()), - }; - case ContractParameterType.Boolean: - return new ContractParameter() - { - Type = ContractParameterType.Boolean, - Value = valueProp.ToObject(), - }; - case ContractParameterType.Integer: - return new ContractParameter() - { - Type = ContractParameterType.Integer, - Value = BigInteger.Parse(valueProp.ToObject()), - }; - case ContractParameterType.String: - return new ContractParameter() - { - Type = ContractParameterType.String, - Value = valueProp.ToObject(), - }; - case ContractParameterType.Hash160: - return new ContractParameter() - { - Type = ContractParameterType.Hash160, - Value = UInt160.Parse(valueProp.ToObject()), - }; - case ContractParameterType.Hash256: - return new ContractParameter() - { - Type = ContractParameterType.Hash256, - Value = UInt256.Parse(valueProp.ToObject()), - }; - case ContractParameterType.PublicKey: - return new ContractParameter() - { - Type = ContractParameterType.PublicKey, - Value = ECPoint.Parse(valueProp.ToObject(), ECCurve.Secp256r1), - }; - case ContractParameterType.Array: - if (valueProp.Value?.Type != JTokenType.Array) - throw new FormatException(); - var array = valueProp.Value as JArray; - return new ContractParameter() - { - Type = ContractParameterType.Array, - Value = array.Select(ContractParameterFromJToken).ToList(), - }; - case ContractParameterType.Map: - if (valueProp.Value?.Type != JTokenType.Array) - throw new FormatException(); - var map = valueProp.Value as JArray; - return new ContractParameter() - { - Type = ContractParameterType.Map, - Value = map.Select(s => - { - if (s.Type != JTokenType.Object) - throw new FormatException(); - var mapProp = valueProp.Value as JObject; - var keyProp = mapProp - .Properties() - .SingleOrDefault(ss => ss.Name.Equals("key", StringComparison.InvariantCultureIgnoreCase)); - var keyValueProp = mapProp - .Properties() - .SingleOrDefault(ss => ss.Name.Equals("value", StringComparison.InvariantCultureIgnoreCase)); - return new KeyValuePair(ContractParameterFromJToken(keyProp.Value), ContractParameterFromJToken(keyValueProp.Value)); - }).ToList(), - }; - default: - throw new NotSupportedException($"ContractParameterType({typeValue}) is not supported to JSON."); - } - } - } -} diff --git a/src/RestServer/RestWebServer.cs b/src/RestServer/RestWebServer.cs deleted file mode 100644 index 7e722b761..000000000 --- a/src/RestServer/RestWebServer.cs +++ /dev/null @@ -1,417 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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 Microsoft.AspNetCore.Authentication; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Diagnostics; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Http; -using Microsoft.AspNetCore.HttpOverrides; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.Abstractions; -using Microsoft.AspNetCore.Mvc.ApiExplorer; -using Microsoft.AspNetCore.Mvc.ApplicationParts; -using Microsoft.AspNetCore.Mvc.Authorization; -using Microsoft.AspNetCore.Mvc.Controllers; -using Microsoft.AspNetCore.Mvc.Versioning; -using Microsoft.AspNetCore.ResponseCompression; -using Microsoft.AspNetCore.Server.Kestrel.Https; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.OpenApi.Models; -using Neo.Cryptography.ECC; -using Neo.Network.P2P.Payloads.Conditions; -using Neo.Plugins.RestServer.Binder; -using Neo.Plugins.RestServer.Middleware; -using Neo.Plugins.RestServer.Models.Error; -using Neo.Plugins.RestServer.Providers; -using Newtonsoft.Json; -using Newtonsoft.Json.Serialization; -using RestServer.Authentication; -using System.Net.Mime; -using System.Net.Security; -using System.Numerics; - -namespace Neo.Plugins.RestServer -{ - internal class RestWebServer - { - #region Globals - - private readonly RestServerSettings _settings; - private IWebHost _host; - - #endregion - - public static bool IsRunning { get; private set; } - - public RestWebServer() - { - _settings = RestServerSettings.Current; - } - - public void Start() - { - if (IsRunning) - return; - - IsRunning = true; - - _host = new WebHostBuilder() - .UseKestrel(options => - { - // Web server configuration - options.AddServerHeader = false; - options.Limits.MaxConcurrentConnections = _settings.MaxConcurrentConnections; - options.Limits.KeepAliveTimeout = TimeSpan.FromSeconds(_settings.KeepAliveTimeout); - options.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(15); - options.Listen(_settings.BindAddress, unchecked((int)_settings.Port), - listenOptions => - { - if (string.IsNullOrEmpty(_settings.SslCertFile)) - return; - listenOptions.UseHttps(_settings.SslCertFile, _settings.SslCertPassword, httpsOptions => - { - if (_settings.TrustedAuthorities.Length == 0) - { - httpsOptions.ClientCertificateMode = ClientCertificateMode.RequireCertificate; - httpsOptions.ClientCertificateValidation = (cert, chain, err) => - { - if (err != SslPolicyErrors.None) - return false; - var authority = chain.ChainElements[^1].Certificate; - return _settings.TrustedAuthorities.Any(a => a.Equals(authority.Thumbprint, StringComparison.OrdinalIgnoreCase)); - }; - } - }); - }); - }) - .ConfigureServices(services => - { - #region Add Basic auth - - if (_settings.EnableBasicAuthentication) - services.AddAuthentication() - .AddScheme("Basic", null); - - #endregion - - #region CORS - - // Server configuration - if (_settings.EnableCors) - { - if (_settings.AllowOrigins.Length == 0) - services.AddCors(options => - { - options.AddPolicy("All", policy => - { - policy.AllowAnyOrigin() - .AllowAnyHeader() - .WithMethods("GET", "POST"); - // The CORS specification states that setting origins to "*" (all origins) - // is invalid if the Access-Control-Allow-Credentials header is present. - //.AllowCredentials() - }); - }); - else - services.AddCors(options => - { - options.AddPolicy("All", policy => - { - policy.WithOrigins(_settings.AllowOrigins) - .AllowAnyHeader() - .AllowCredentials() - .WithMethods("GET", "POST"); - }); - }); - } - - #endregion - - services.AddRouting(options => options.LowercaseUrls = options.LowercaseQueryStrings = true); - - #region Compression Configuration - - if (_settings.EnableCompression) - services.AddResponseCompression(options => - { - options.EnableForHttps = false; - options.Providers.Add(); - options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Append(MediaTypeNames.Application.Json); - }); - - #endregion - - #region Controllers - - var controllers = services - .AddControllers(options => - { - options.EnableEndpointRouting = false; - - if (_settings.EnableBasicAuthentication) - { - var policy = new AuthorizationPolicyBuilder() - .RequireAuthenticatedUser() - .Build(); - options.Filters.Add(new AuthorizeFilter(policy)); - } - options.ModelBinderProviders.Insert(0, new NeoBinderProvider()); - }) - .ConfigureApiBehaviorOptions(options => - { - options.InvalidModelStateResponseFactory = context => - new BadRequestObjectResult( - new ParameterFormatExceptionModel(string.Join(' ', context.ModelState.Values.SelectMany(s => s.Errors).Select(s => s.ErrorMessage)))) - { - ContentTypes = - { - MediaTypeNames.Application.Json, - } - }; - }) - .ConfigureApplicationPartManager(manager => - { - var controllerFeatureProvider = manager.FeatureProviders.Single(p => p.GetType() == typeof(ControllerFeatureProvider)); - var index = manager.FeatureProviders.IndexOf(controllerFeatureProvider); - manager.FeatureProviders[index] = new BlackListControllerFeatureProvider(); - - foreach (var plugin in Plugin.Plugins) - manager.ApplicationParts.Add(new AssemblyPart(plugin.GetType().Assembly)); - }) - .AddNewtonsoftJson(options => - { - options.AllowInputFormatterExceptionMessages = true; - options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); - options.SerializerSettings.Formatting = Formatting.None; - - foreach (var converter in _settings.JsonSerializerSettings.Converters) - options.SerializerSettings.Converters.Add(converter); - }); - - #endregion - - #region API Versioning - - services.AddVersionedApiExplorer(setupAction => - { - setupAction.GroupNameFormat = "'v'VV"; - }); - - services.AddApiVersioning(options => - { - options.AssumeDefaultVersionWhenUnspecified = true; - options.DefaultApiVersion = new ApiVersion(1, 0); - options.ReportApiVersions = true; - }); - - #endregion - - #region Swagger Configuration - - if (_settings.EnableSwagger) - { - var apiVersionDescriptionProvider = services.BuildServiceProvider().GetRequiredService(); - services.AddSwaggerGen(options => - { - foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions) - { - options.SwaggerDoc(description.GroupName, new OpenApiInfo() - { - Title = "RestServer Plugin API", - Description = "RESTful Web Sevices for neo-cli.", - Version = description.ApiVersion.ToString(), - Contact = new OpenApiContact() - { - Name = "The Neo Project", - Url = new Uri("https://github.com/neo-project/neo-modules"), - Email = "dev@neo.org", - }, - License = new OpenApiLicense() - { - Name = "MIT", - Url = new Uri("http://www.opensource.org/licenses/mit-license.php"), - }, - }); - } - - #region Enable Basic Auth for Swagger - - if (_settings.EnableBasicAuthentication) - { - options.AddSecurityDefinition("basicAuth", new OpenApiSecurityScheme() - { - Type = SecuritySchemeType.Http, - Scheme = "basic", - Description = "Input your username and password to access this API.", - }); - options.AddSecurityRequirement(new OpenApiSecurityRequirement() - { - { - new OpenApiSecurityScheme() - { - Reference = new OpenApiReference() - { - Type = ReferenceType.SecurityScheme, - Id = "basicAuth", - }, - }, - new List() - } - }); - } - - #endregion - - options.DocInclusionPredicate((docmentName, apiDescription) => - { - var actionApiVersionModel = apiDescription.ActionDescriptor.GetApiVersionModel(ApiVersionMapping.Explicit | ApiVersionMapping.Implicit); - if (actionApiVersionModel == null) - return true; - if (actionApiVersionModel.DeclaredApiVersions.Any()) - return actionApiVersionModel.DeclaredApiVersions.Any(a => $"v{a}" == docmentName); - return actionApiVersionModel.ImplementedApiVersions.Any(a => $"v{a}" == docmentName); - }); - - options.UseOneOfForPolymorphism(); - options.SelectSubTypesUsing(baseType => - { - if (baseType == typeof(WitnessCondition)) - { - return new[] - { - typeof(BooleanCondition), - typeof(NotCondition), - typeof(AndCondition), - typeof(OrCondition), - typeof(ScriptHashCondition), - typeof(GroupCondition), - typeof(CalledByEntryCondition), - typeof(CalledByContractCondition), - typeof(CalledByGroupCondition), - }; - } - - return Enumerable.Empty(); - }); - options.MapType(() => new OpenApiSchema() - { - Type = "string", - Format = "hash256", - }); - options.MapType(() => new OpenApiSchema() - { - Type = "string", - Format = "hash160", - }); - options.MapType(() => new OpenApiSchema() - { - Type = "string", - Format = "hexstring", - }); - options.MapType(() => new OpenApiSchema() - { - Type = "integer", - Format = "bigint", - }); - options.MapType(() => new OpenApiSchema() - { - Type = "string", - Format = "base64", - }); - options.MapType>(() => new OpenApiSchema() - { - Type = "string", - Format = "base64", - }); - foreach (var plugin in Plugin.Plugins) - { - var assemblyName = plugin.GetType().Assembly.GetName().Name; - var xmlPathAndFilename = Path.Combine(AppContext.BaseDirectory, "Plugins", assemblyName, $"{assemblyName}.xml"); - if (File.Exists(xmlPathAndFilename)) - options.IncludeXmlComments(xmlPathAndFilename); - } - }); - services.AddSwaggerGenNewtonsoftSupport(); - } - - #endregion - - #region Forward Headers - - if (_settings.EnableForwardedHeaders) - services.Configure(options => options.ForwardedHeaders = ForwardedHeaders.All); - - #endregion - - #region Compression - - if (_settings.EnableCompression) - services.Configure(options => options.Level = _settings.CompressionLevel); - - #endregion - }) - .Configure(app => - { - app.UseMiddleware(); - - if (_settings.EnableForwardedHeaders) - app.UseForwardedHeaders(); - - app.UseRouting(); - - if (_settings.EnableCors) - app.UseCors("All"); - - if (_settings.EnableCompression) - app.UseResponseCompression(); - - if (_settings.EnableBasicAuthentication) - app.UseAuthentication(); - - app.UseExceptionHandler(config => - config.Run(async context => - { - var exception = context.Features - .Get() - .Error; - var response = new ErrorModel() - { - Code = exception.HResult, - Name = exception.GetType().Name, - Message = exception.InnerException?.Message ?? exception.Message, - }; - RestServerMiddleware.SetServerInfomationHeader(context.Response); - context.Response.StatusCode = 400; - await context.Response.WriteAsJsonAsync(response); - })); - - if (_settings.EnableSwagger) - { - app.UseSwagger(); - //app.UseSwaggerUI(options => options.DefaultModelsExpandDepth(-1)); - app.UseSwaggerUI(options => - { - var apiVersionDescriptionProvider = app.ApplicationServices.GetRequiredService(); - foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions) - { - options.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant()); - } - }); - } - - app.UseMvc(); - }) - .Build(); - _host.Start(); - } - } -} diff --git a/src/RestServer/Tokens/NEP11Token.cs b/src/RestServer/Tokens/NEP11Token.cs deleted file mode 100644 index 5d52506c3..000000000 --- a/src/RestServer/Tokens/NEP11Token.cs +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Persistence; -using Neo.Plugins.RestServer.Helpers; -using Neo.SmartContract; -using Neo.SmartContract.Iterators; -using Neo.SmartContract.Native; -using Neo.VM; -using Neo.VM.Types; -using System.Numerics; - -namespace Neo.Plugins.RestServer.Tokens -{ - internal class NEP11Token - { - public UInt160 ScriptHash { get; private set; } - public string Name { get; private set; } - public string Symbol { get; private set; } - public byte Decimals { get; private set; } - - private readonly NeoSystem _neosystem; - private readonly DataCache _snapshot; - private readonly ContractState _contract; - - public NEP11Token( - NeoSystem neoSystem, - UInt160 scriptHash) : this(neoSystem, null, scriptHash) { } - - public NEP11Token( - NeoSystem neoSystem, - DataCache snapshot, - UInt160 scriptHash) - { - ArgumentNullException.ThrowIfNull(neoSystem, nameof(neoSystem)); - ArgumentNullException.ThrowIfNull(scriptHash, nameof(scriptHash)); - _neosystem = neoSystem; - _snapshot = snapshot ?? _neosystem.GetSnapshot(); - _contract = NativeContract.ContractManagement.GetContract(_snapshot, scriptHash) ?? throw new ArgumentException(null, nameof(scriptHash)); - if (ContractHelper.IsNep11Supported(_contract) == false) - throw new NotSupportedException(nameof(scriptHash)); - Name = _contract.Manifest.Name; - ScriptHash = scriptHash; - Initialize(); - } - - private void Initialize() - { - byte[] scriptBytes; - using var sb = new ScriptBuilder(); - sb.EmitDynamicCall(_contract.Hash, "decimals", CallFlags.ReadOnly); - sb.EmitDynamicCall(_contract.Hash, "symbol", CallFlags.ReadOnly); - scriptBytes = sb.ToArray(); - - using var appEngine = ApplicationEngine.Run(scriptBytes, _snapshot, settings: _neosystem.Settings, gas: RestServerSettings.Current.MaxGasInvoke); - if (appEngine.State != VMState.HALT) - throw new NotSupportedException(nameof(ScriptHash)); - - Symbol = appEngine.ResultStack.Pop().GetString(); - Decimals = (byte)appEngine.ResultStack.Pop().GetInteger(); - } - - public BigDecimal TotalSupply() - { - if (ContractHelper.GetContractMethod(_snapshot, ScriptHash, "totalSupply", 0) == null) - throw new NotSupportedException(nameof(ScriptHash)); - if (ScriptHelper.InvokeMethod(_neosystem.Settings, _snapshot, ScriptHash, "totalSupply", out var results)) - return new(results[0].GetInteger(), Decimals); - return new(BigInteger.Zero, Decimals); - } - - public BigDecimal BalanceOf(UInt160 owner) - { - if (ContractHelper.GetContractMethod(_snapshot, ScriptHash, "balanceOf", 1) == null) - throw new NotSupportedException(nameof(ScriptHash)); - if (ScriptHelper.InvokeMethod(_neosystem.Settings, _snapshot, ScriptHash, "balanceOf", out var results, owner)) - return new(results[0].GetInteger(), Decimals); - return new(BigInteger.Zero, Decimals); - } - - public BigDecimal BalanceOf(UInt160 owner, byte[] tokenId) - { - if (Decimals == 0) - throw new InvalidOperationException(); - if (ContractHelper.GetContractMethod(_snapshot, ScriptHash, "balanceOf", 2) == null) - throw new NotSupportedException(nameof(ScriptHash)); - ArgumentNullException.ThrowIfNull(tokenId, nameof(tokenId)); - if (tokenId.Length > 64) - throw new ArgumentOutOfRangeException(nameof(tokenId)); - if (ScriptHelper.InvokeMethod(_neosystem.Settings, _snapshot, ScriptHash, "balanceOf", out var results, owner, tokenId)) - return new(results[0].GetInteger(), Decimals); - return new(BigInteger.Zero, Decimals); - } - - public IEnumerable TokensOf(UInt160 owner) - { - if (ContractHelper.GetContractMethod(_snapshot, ScriptHash, "tokensOf", 1) == null) - throw new NotSupportedException(nameof(ScriptHash)); - if (ScriptHelper.InvokeMethod(_neosystem.Settings, _snapshot, ScriptHash, "tokensOf", out var results, owner)) - { - if (results[0].GetInterface() is IIterator iterator) - { - var refCounter = new ReferenceCounter(); - while (iterator.Next()) - yield return iterator.Value(refCounter).GetSpan().ToArray(); - } - } - } - - public UInt160[] OwnerOf(byte[] tokenId) - { - if (ContractHelper.GetContractMethod(_snapshot, ScriptHash, "ownerOf", 1) == null) - throw new NotSupportedException(nameof(ScriptHash)); - ArgumentNullException.ThrowIfNull(tokenId, nameof(tokenId)); - if (tokenId.Length > 64) - throw new ArgumentOutOfRangeException(nameof(tokenId)); - if (Decimals == 0) - { - if (ScriptHelper.InvokeMethod(_neosystem.Settings, _snapshot, ScriptHash, "ownerOf", out var results, tokenId)) - return new[] { new UInt160(results[0].GetSpan()) }; - } - else if (Decimals > 0) - { - if (ScriptHelper.InvokeMethod(_neosystem.Settings, _snapshot, ScriptHash, "ownerOf", out var results, tokenId)) - { - if (results[0].GetInterface() is IIterator iterator) - { - var refCounter = new ReferenceCounter(); - var lstOwners = new List(); - while (iterator.Next()) - lstOwners.Add(new UInt160(iterator.Value(refCounter).GetSpan())); - return lstOwners.ToArray(); - } - } - } - return System.Array.Empty(); - } - - public IEnumerable Tokens() - { - if (ContractHelper.GetContractMethod(_snapshot, ScriptHash, "tokens", 0) == null) - throw new NotImplementedException(); - if (ScriptHelper.InvokeMethod(_neosystem.Settings, _snapshot, ScriptHash, "tokens", out var results)) - { - if (results[0].GetInterface() is IIterator iterator) - { - var refCounter = new ReferenceCounter(); - while (iterator.Next()) - yield return iterator.Value(refCounter).GetSpan().ToArray(); - } - } - } - - public IReadOnlyDictionary Properties(byte[] tokenId) - { - ArgumentNullException.ThrowIfNull(tokenId, nameof(tokenId)); - if (ContractHelper.GetContractMethod(_snapshot, ScriptHash, "properties", 1) == null) - throw new NotImplementedException(); - if (tokenId.Length > 64) - throw new ArgumentOutOfRangeException(nameof(tokenId)); - if (ScriptHelper.InvokeMethod(_neosystem.Settings, _snapshot, ScriptHash, "properties", out var results, tokenId)) - { - if (results[0] is Map map) - { - return map.ToDictionary(key => key.Key.GetString(), value => value.Value); - } - } - return default; - } - } -} diff --git a/src/RestServer/Tokens/NEP17Token.cs b/src/RestServer/Tokens/NEP17Token.cs deleted file mode 100644 index e0561afdc..000000000 --- a/src/RestServer/Tokens/NEP17Token.cs +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Persistence; -using Neo.Plugins.RestServer.Helpers; -using Neo.SmartContract; -using Neo.SmartContract.Native; -using Neo.VM; -using System.Numerics; - -namespace Neo.Plugins.RestServer.Tokens -{ - internal class NEP17Token - { - public UInt160 ScriptHash { get; private init; } - public string Name { get; private init; } - public string Symbol { get; private init; } - public byte Decimals { get; private init; } - - private readonly NeoSystem _neosystem; - private readonly DataCache _datacache; - - public NEP17Token( - NeoSystem neoSystem, - UInt160 scriptHash, - DataCache snapshot = null) - { - _datacache = snapshot ?? neoSystem.GetSnapshot(); - var contractState = NativeContract.ContractManagement.GetContract(_datacache, scriptHash) ?? throw new ArgumentException(null, nameof(scriptHash)); - if (ContractHelper.IsNep17Supported(contractState) == false) - throw new NotSupportedException(nameof(scriptHash)); - byte[] script; - using (var sb = new ScriptBuilder()) - { - sb.EmitDynamicCall(scriptHash, "decimals", CallFlags.ReadOnly); - sb.EmitDynamicCall(scriptHash, "symbol", CallFlags.ReadOnly); - script = sb.ToArray(); - } - using var engine = ApplicationEngine.Run(script, _datacache, settings: neoSystem.Settings, gas: RestServerSettings.Current.MaxGasInvoke); - if (engine.State != VMState.HALT) - throw new NotSupportedException(nameof(scriptHash)); - - _neosystem = neoSystem; - ScriptHash = scriptHash; - Name = contractState.Manifest.Name; - Symbol = engine.ResultStack.Pop().GetString(); - Decimals = (byte)engine.ResultStack.Pop().GetInteger(); - } - - public BigDecimal BalanceOf(UInt160 address) - { - if (ContractHelper.GetContractMethod(_datacache, ScriptHash, "balanceOf", 1) == null) - throw new NotSupportedException(nameof(ScriptHash)); - if (ScriptHelper.InvokeMethod(_neosystem.Settings, _datacache, ScriptHash, "balanceOf", out var result, address)) - return new BigDecimal(result[0].GetInteger(), Decimals); - return new BigDecimal(BigInteger.Zero, Decimals); - } - - public BigDecimal TotalSupply() - { - if (ContractHelper.GetContractMethod(_datacache, ScriptHash, "totalSupply", 0) == null) - throw new NotSupportedException(nameof(ScriptHash)); - if (ScriptHelper.InvokeMethod(_neosystem.Settings, _datacache, ScriptHash, "totalSupply", out var result)) - return new BigDecimal(result[0].GetInteger(), Decimals); - return new BigDecimal(BigInteger.Zero, Decimals); - } - } -} diff --git a/src/RestServer/WalletSessionManager.cs b/src/RestServer/WalletSessionManager.cs deleted file mode 100644 index 967863666..000000000 --- a/src/RestServer/WalletSessionManager.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Plugins.RestServer 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.Wallets; -using System.Collections.Concurrent; - -namespace Neo.Plugins.RestServer -{ - public class WalletSessionManager : ConcurrentDictionary - { - private readonly PeriodicTimer _timer; - - public WalletSessionManager() - { - _timer = new(TimeSpan.FromSeconds(1)); - _ = Task.Run(SessionTimeout); - } - - private async Task SessionTimeout() - { - while (await _timer.WaitForNextTickAsync()) - { - var killAll = this.Where(w => w.Value.Expires <= DateTime.Now) - .Select(s => Task.Run(() => - { - TryRemove(s); - })); - await Task.WhenAll(killAll); - } - } - } - - public class WalletSession - { - public Wallet Wallet { get; private init; } - public DateTime Expires { get; private set; } - - public WalletSession(Wallet wallet) - { - Wallet = wallet; - ResetExpiration(); - } - - public void ResetExpiration() => - Expires = DateTime.Now.AddSeconds(RestServerSettings.Current.WalletSessionTimeout); - } -} diff --git a/src/RestServer/config.json b/src/RestServer/config.json deleted file mode 100644 index de8eb9599..000000000 --- a/src/RestServer/config.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "PluginConfiguration": { - "Network": 860833102, - "BindAddress": "127.0.0.1", - "Port": 10339, - "KeepAliveTimeout": 120, - "SslCertFile": "", - "SslCertPassword": "", - "TrustedAuthorities": [], // Example: "aec13cdd5ea6a3998aec14ac331ad96bedbb770f" (Thumbprint) - "EnableBasicAuthentication": false, - "RestUser": "", - "RestPass": "", - "EnableCors": true, - "AllowOrigins": [], // Example: "http://www.example.com" - "DisableControllers": [ "WalletController" ], - "EnableCompression": true, - "CompressionLevel": "SmallestSize", // "Fastest" or "Optimal" or "NoCompression" or "SmallestSize" - "EnableForwardedHeaders": false, - "EnableSwagger": true, - "MaxPageSize": 50, - "MaxConcurrentConnections": 40, - "MaxTransactionFee": 10000000, - "MaxGasInvoke": 20000000, - "MaxTransactionSize": 1024, - "WalletSessionTimeout": 120 - } -} From 3f19028c30faa6c303ff2786095b54e724323549 Mon Sep 17 00:00:00 2001 From: Shargon Date: Wed, 8 Nov 2023 09:46:21 +0100 Subject: [PATCH 14/30] MaxParamsDepth and MaxRequestBodySize in RpcServer (#827) * Reducing risks metioned in https://github.com/neo-project/neo-modules/issues/820 * Also check in GET * Clean --------- Co-authored-by: Jimmy Co-authored-by: Owen Zhang <38493437+superboyiii@users.noreply.github.com> --- src/RpcServer/RpcServer.cs | 9 +++++++-- src/RpcServer/Settings.cs | 3 +++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/src/RpcServer/RpcServer.cs b/src/RpcServer/RpcServer.cs index d28e07e57..3a199ad3b 100644 --- a/src/RpcServer/RpcServer.cs +++ b/src/RpcServer/RpcServer.cs @@ -32,6 +32,8 @@ namespace Neo.Plugins { public partial class RpcServer : IDisposable { + private const int MaxParamsDepth = 32; + private readonly Dictionary> methods = new(); private IWebHost host; @@ -105,6 +107,9 @@ public void StartRpcServer() { host = new WebHostBuilder().UseKestrel(options => options.Listen(settings.BindAddress, settings.Port, listenOptions => { + // Default value is 5Mb + options.Limits.MaxRequestBodySize = settings.MaxRequestBodySize; + options.Limits.MaxRequestLineSize = Math.Min(settings.MaxRequestBodySize, options.Limits.MaxRequestLineSize); // Default value is 40 options.Limits.MaxConcurrentConnections = settings.MaxConcurrentConnections; // Default value is 1 minutes @@ -182,7 +187,7 @@ public async Task ProcessAsync(HttpContext context) request["jsonrpc"] = jsonrpc; request["id"] = id; request["method"] = method; - request["params"] = JToken.Parse(_params); + request["params"] = JToken.Parse(_params, MaxParamsDepth); } } else if (context.Request.Method == "POST") @@ -190,7 +195,7 @@ public async Task ProcessAsync(HttpContext context) using StreamReader reader = new(context.Request.Body); try { - request = JToken.Parse(await reader.ReadToEndAsync()); + request = JToken.Parse(await reader.ReadToEndAsync(), MaxParamsDepth); } catch (FormatException) { } } diff --git a/src/RpcServer/Settings.cs b/src/RpcServer/Settings.cs index 6d5b1202a..ff93b0cc7 100644 --- a/src/RpcServer/Settings.cs +++ b/src/RpcServer/Settings.cs @@ -36,6 +36,7 @@ public record RpcServerSettings public string SslCertPassword { get; init; } public string[] TrustedAuthorities { get; init; } public int MaxConcurrentConnections { get; init; } + public int MaxRequestBodySize { get; init; } public string RpcUser { get; init; } public string RpcPass { get; init; } public long MaxGasInvoke { get; init; } @@ -60,6 +61,7 @@ public record RpcServerSettings MaxStackSize = ushort.MaxValue, DisabledMethods = Array.Empty(), MaxConcurrentConnections = 40, + MaxRequestBodySize = 5 * 1024 * 1024, SessionEnabled = false, SessionExpirationTime = TimeSpan.FromSeconds(60), FindStoragePageSize = 50 @@ -81,6 +83,7 @@ public record RpcServerSettings MaxStackSize = section.GetValue("MaxStackSize", Default.MaxStackSize), DisabledMethods = section.GetSection("DisabledMethods").GetChildren().Select(p => p.Get()).ToArray(), MaxConcurrentConnections = section.GetValue("MaxConcurrentConnections", Default.MaxConcurrentConnections), + MaxRequestBodySize = section.GetValue("MaxRequestBodySize", Default.MaxRequestBodySize), SessionEnabled = section.GetValue("SessionEnabled", Default.SessionEnabled), SessionExpirationTime = TimeSpan.FromSeconds(section.GetValue("SessionExpirationTime", (int)Default.SessionExpirationTime.TotalSeconds)), FindStoragePageSize = section.GetValue("FindStoragePageSize", Default.FindStoragePageSize) From 2d7fb2778ca7ad11815e438534916103859e36ac Mon Sep 17 00:00:00 2001 From: Anna Shaleva Date: Wed, 8 Nov 2023 12:16:46 +0300 Subject: [PATCH 15/30] DBFTPlugin: adapt new Conflicts attribute storage scheme (#828) * DBFTPlugin: adapt new Conflicts attribute storage scheme Upgrade neo-modules to use https://github.com/neo-project/neo/pull/2913. Signed-off-by: Anna Shaleva * Update neo * Fix version * Fix NativeHistory --------- Signed-off-by: Anna Shaleva Co-authored-by: Jimmy Co-authored-by: Shargon --- src/DBFTPlugin/Consensus/ConsensusService.OnMessage.cs | 4 ++-- src/Directory.Build.props | 2 +- src/RpcServer/Utility.cs | 3 +-- 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/DBFTPlugin/Consensus/ConsensusService.OnMessage.cs b/src/DBFTPlugin/Consensus/ConsensusService.OnMessage.cs index cac84a8d4..4dc9f534d 100644 --- a/src/DBFTPlugin/Consensus/ConsensusService.OnMessage.cs +++ b/src/DBFTPlugin/Consensus/ConsensusService.OnMessage.cs @@ -127,7 +127,7 @@ private void OnPrepareRequestReceived(ExtensiblePayload payload, PrepareRequest { if (mempoolVerified.TryGetValue(hash, out Transaction tx)) { - if (NativeContract.Ledger.ContainsConflictHash(context.Snapshot, hash, tx.Signers.Select(s => s.Account))) + if (NativeContract.Ledger.ContainsConflictHash(context.Snapshot, hash, tx.Signers.Select(s => s.Account), neoSystem.Settings.MaxTraceableBlocks)) { Log($"Invalid request: transaction has on-chain conflict", LogLevel.Warning); return; @@ -140,7 +140,7 @@ private void OnPrepareRequestReceived(ExtensiblePayload payload, PrepareRequest { if (neoSystem.MemPool.TryGetValue(hash, out tx)) { - if (NativeContract.Ledger.ContainsConflictHash(context.Snapshot, hash, tx.Signers.Select(s => s.Account))) + if (NativeContract.Ledger.ContainsConflictHash(context.Snapshot, hash, tx.Signers.Select(s => s.Account), neoSystem.Settings.MaxTraceableBlocks)) { Log($"Invalid request: transaction has on-chain conflict", LogLevel.Warning); return; diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 717700b72..150e436ec 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -21,7 +21,7 @@ - + diff --git a/src/RpcServer/Utility.cs b/src/RpcServer/Utility.cs index 33750c4c9..e92a4a53f 100644 --- a/src/RpcServer/Utility.cs +++ b/src/RpcServer/Utility.cs @@ -39,8 +39,7 @@ public static JObject NativeContractToJson(this NativeContract contract, Protoco ["id"] = contract.Id, ["hash"] = contract.Hash.ToString(), ["nef"] = contract.Nef.ToJson(), - ["manifest"] = contract.Manifest.ToJson(), - ["updatehistory"] = settings.NativeUpdateHistory[contract.Name].Select(p => (JToken)p).ToArray() + ["manifest"] = contract.Manifest.ToJson() }; } } From 64a1ae4c27b2a8d1285976231142b39bde49cc02 Mon Sep 17 00:00:00 2001 From: Owen Zhang <38493437+superboyiii@users.noreply.github.com> Date: Fri, 17 Nov 2023 11:25:24 +0800 Subject: [PATCH 16/30] v3.6.2 (#844) --- src/Directory.Build.props | 4 ++-- .../Neo.Cryptography.MPTTrie.Tests.csproj | 2 +- .../Neo.Plugins.OracleService.Tests.csproj | 6 +++--- .../Neo.Plugins.RpcServer.Tests.csproj | 2 +- .../Neo.Plugins.Storage.Tests.csproj | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 150e436ec..94e2979c9 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -2,7 +2,7 @@ - 3.6.1 + 3.6.2 net7.0 Neo.Plugins The Neo Project @@ -21,7 +21,7 @@ - + diff --git a/tests/Neo.Cryptography.MPTTrie.Tests/Neo.Cryptography.MPTTrie.Tests.csproj b/tests/Neo.Cryptography.MPTTrie.Tests/Neo.Cryptography.MPTTrie.Tests.csproj index aec30cd98..a2d6822c5 100644 --- a/tests/Neo.Cryptography.MPTTrie.Tests/Neo.Cryptography.MPTTrie.Tests.csproj +++ b/tests/Neo.Cryptography.MPTTrie.Tests/Neo.Cryptography.MPTTrie.Tests.csproj @@ -9,7 +9,7 @@ - + diff --git a/tests/Neo.Plugins.OracleService.Tests/Neo.Plugins.OracleService.Tests.csproj b/tests/Neo.Plugins.OracleService.Tests/Neo.Plugins.OracleService.Tests.csproj index f2a836e3c..1584f425f 100644 --- a/tests/Neo.Plugins.OracleService.Tests/Neo.Plugins.OracleService.Tests.csproj +++ b/tests/Neo.Plugins.OracleService.Tests/Neo.Plugins.OracleService.Tests.csproj @@ -6,8 +6,8 @@ - - + + @@ -15,7 +15,7 @@ - + diff --git a/tests/Neo.Plugins.RpcServer.Tests/Neo.Plugins.RpcServer.Tests.csproj b/tests/Neo.Plugins.RpcServer.Tests/Neo.Plugins.RpcServer.Tests.csproj index 6105eaf11..9508d750e 100644 --- a/tests/Neo.Plugins.RpcServer.Tests/Neo.Plugins.RpcServer.Tests.csproj +++ b/tests/Neo.Plugins.RpcServer.Tests/Neo.Plugins.RpcServer.Tests.csproj @@ -14,7 +14,7 @@ - + diff --git a/tests/Neo.Plugins.Storage.Tests/Neo.Plugins.Storage.Tests.csproj b/tests/Neo.Plugins.Storage.Tests/Neo.Plugins.Storage.Tests.csproj index 2cdcc8345..1366e66f8 100644 --- a/tests/Neo.Plugins.Storage.Tests/Neo.Plugins.Storage.Tests.csproj +++ b/tests/Neo.Plugins.Storage.Tests/Neo.Plugins.Storage.Tests.csproj @@ -10,7 +10,7 @@ - + From 0a3f812d67ed5cd10609677439d3e407ed3ce030 Mon Sep 17 00:00:00 2001 From: Shargon Date: Wed, 29 Nov 2023 13:33:01 +0700 Subject: [PATCH 17/30] Fix RpcNativeContract (#851) * Fix RpcNativeContract Close https://github.com/neo-project/neo-modules/issues/850 * Fix UT --- src/RpcClient/Models/RpcNativeContract.cs | 7 ++---- tests/Neo.Network.RPC.Tests/RpcTestCases.json | 24 +++++++------------ 2 files changed, 10 insertions(+), 21 deletions(-) diff --git a/src/RpcClient/Models/RpcNativeContract.cs b/src/RpcClient/Models/RpcNativeContract.cs index f103a418e..5c85efa7c 100644 --- a/src/RpcClient/Models/RpcNativeContract.cs +++ b/src/RpcClient/Models/RpcNativeContract.cs @@ -21,7 +21,6 @@ public class RpcNativeContract public UInt160 Hash { get; set; } public NefFile Nef { get; set; } public ContractManifest Manifest { get; set; } - public uint[] UpdateHistory { get; set; } public static RpcNativeContract FromJson(JObject json) { @@ -30,8 +29,7 @@ public static RpcNativeContract FromJson(JObject json) Id = (int)json["id"].AsNumber(), Hash = UInt160.Parse(json["hash"].AsString()), Nef = RpcNefFile.FromJson((JObject)json["nef"]), - Manifest = ContractManifest.FromJson((JObject)json["manifest"]), - UpdateHistory = ((JArray)json["updatehistory"]).Select(u => (uint)u.GetInt32()).ToArray() + Manifest = ContractManifest.FromJson((JObject)json["manifest"]) }; } @@ -42,8 +40,7 @@ public JObject ToJson() ["id"] = Id, ["hash"] = Hash.ToString(), ["nef"] = Nef.ToJson(), - ["manifest"] = Manifest.ToJson(), - ["updatehistory"] = new JArray(UpdateHistory.Select(u => new JNumber(u)).ToArray()) + ["manifest"] = Manifest.ToJson() }; } } diff --git a/tests/Neo.Network.RPC.Tests/RpcTestCases.json b/tests/Neo.Network.RPC.Tests/RpcTestCases.json index 903d48307..c1f89bf37 100644 --- a/tests/Neo.Network.RPC.Tests/RpcTestCases.json +++ b/tests/Neo.Network.RPC.Tests/RpcTestCases.json @@ -1202,8 +1202,7 @@ ], "trusts": [], "extra": null - }, - "updatehistory": [ 0 ] + } }, { "id": -2, @@ -1300,8 +1299,7 @@ ], "trusts": [], "extra": null - }, - "updatehistory": [ 0 ] + } }, { "id": -3, @@ -1505,8 +1503,7 @@ ], "trusts": [], "extra": null - }, - "updatehistory": [ 0 ] + } }, { "id": -4, @@ -1614,8 +1611,7 @@ ], "trusts": [], "extra": null - }, - "updatehistory": [ 0 ] + } }, { "id": -5, @@ -1796,8 +1792,7 @@ ], "trusts": [], "extra": null - }, - "updatehistory": [ 0 ] + } }, { "id": -6, @@ -1860,8 +1855,7 @@ ], "trusts": [], "extra": null - }, - "updatehistory": [ 0 ] + } }, { "id": -7, @@ -1969,8 +1963,7 @@ ], "trusts": [], "extra": null - }, - "updatehistory": [ 0 ] + } }, { "id": -8, @@ -2263,8 +2256,7 @@ ], "trusts": [], "extra": null - }, - "updatehistory": [ 0 ] + } } ] } From f84cd59ddc3a7941147fb6d37b79fc4f711760d6 Mon Sep 17 00:00:00 2001 From: Owen Zhang <38493437+superboyiii@users.noreply.github.com> Date: Wed, 29 Nov 2023 17:23:02 +0800 Subject: [PATCH 18/30] Hotfix for https://github.com/neo-project/neo-modules/issues/850 (#853) --- src/Directory.Build.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 94e2979c9..9191a7a1e 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -2,7 +2,7 @@ - 3.6.2 + 3.6.3 net7.0 Neo.Plugins The Neo Project From b7c03f05e335cd97c073338cb98d9032fcc3a6e0 Mon Sep 17 00:00:00 2001 From: Shine Li Date: Tue, 5 Dec 2023 20:01:04 +0800 Subject: [PATCH 19/30] Refac build configs (#846) * refac build props * remove AdditionalProperties * remove IncludeSettingsFileOutput --------- Co-authored-by: Owen Zhang <38493437+superboyiii@users.noreply.github.com> Co-authored-by: Jimmy --- Directory.Build.props | 17 ++++++++++ src/ApplicationLogs/ApplicationLogs.csproj | 11 +++---- src/DBFTPlugin/DBFTPlugin.csproj | 2 +- src/Directory.Build.props | 33 +++++-------------- src/OracleService/OracleService.csproj | 29 ++++++++-------- src/RpcServer/RpcServer.csproj | 1 - src/StateService/StateService.csproj | 32 +++++++++--------- src/StatesDumper/StatesDumper.csproj | 2 +- src/StorageDumper/StorageDumper.csproj | 2 +- src/TokensTracker/TokensTracker.csproj | 21 ++++++------ tests/Directory.Build.props | 16 ++++----- .../Neo.Cryptography.MPTTrie.Tests.csproj | 10 +----- .../Neo.Network.RPC.Tests.csproj | 19 +++-------- .../Neo.Plugins.OracleService.Tests.csproj | 18 ++++------ .../Neo.Plugins.RpcServer.Tests.csproj | 12 +------ .../Neo.Plugins.Storage.Tests.csproj | 11 +------ 16 files changed, 93 insertions(+), 143 deletions(-) create mode 100644 Directory.Build.props diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 000000000..f0d4f85a6 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,17 @@ + + + + 3.6.2 + net7.0 + Neo.Plugins + The Neo Project + NEO;Blockchain + https://github.com/neo-project/neo-modules + MIT + git + https://github.com/neo-project/neo-modules.git + + + + + \ No newline at end of file diff --git a/src/ApplicationLogs/ApplicationLogs.csproj b/src/ApplicationLogs/ApplicationLogs.csproj index c2b42fec8..61ce39219 100644 --- a/src/ApplicationLogs/ApplicationLogs.csproj +++ b/src/ApplicationLogs/ApplicationLogs.csproj @@ -1,12 +1,11 @@ - Neo.Plugins.ApplicationLogs - Neo.Plugins - - + + false + runtime + - - + \ No newline at end of file diff --git a/src/DBFTPlugin/DBFTPlugin.csproj b/src/DBFTPlugin/DBFTPlugin.csproj index f169d5eba..74daed38a 100644 --- a/src/DBFTPlugin/DBFTPlugin.csproj +++ b/src/DBFTPlugin/DBFTPlugin.csproj @@ -6,7 +6,7 @@ - + diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 9191a7a1e..b173f4db2 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -1,27 +1,10 @@ - - - 3.6.3 - net7.0 - Neo.Plugins - The Neo Project - NEO;Blockchain - https://github.com/neo-project/neo-modules - MIT - git - https://github.com/neo-project/neo-modules.git - - - - - PreserveNewest - PreserveNewest - - - - - - - - + + + + PreserveNewest + PreserveNewest + + + \ No newline at end of file diff --git a/src/OracleService/OracleService.csproj b/src/OracleService/OracleService.csproj index 5afa10cbe..1e4f29e8a 100644 --- a/src/OracleService/OracleService.csproj +++ b/src/OracleService/OracleService.csproj @@ -1,16 +1,15 @@ - - - Neo.Plugins.OracleService - - - - - - - - - - - - + + Neo.Plugins.OracleService + + + + + + + + false + runtime + + + \ No newline at end of file diff --git a/src/RpcServer/RpcServer.csproj b/src/RpcServer/RpcServer.csproj index 77a4c158e..af5dc619c 100644 --- a/src/RpcServer/RpcServer.csproj +++ b/src/RpcServer/RpcServer.csproj @@ -2,7 +2,6 @@ Neo.Plugins.RpcServer - Neo.Plugins diff --git a/src/StateService/StateService.csproj b/src/StateService/StateService.csproj index 4f6902f20..b438508f8 100644 --- a/src/StateService/StateService.csproj +++ b/src/StateService/StateService.csproj @@ -1,18 +1,16 @@ - - - Neo.Plugins.StateService - Neo.Plugins - true - - - - - - - - - - - - + + Neo.Plugins.StateService + true + + + + + + + + false + runtime + + + \ No newline at end of file diff --git a/src/StatesDumper/StatesDumper.csproj b/src/StatesDumper/StatesDumper.csproj index ab9aaa9dd..02d67dbe3 100644 --- a/src/StatesDumper/StatesDumper.csproj +++ b/src/StatesDumper/StatesDumper.csproj @@ -5,7 +5,7 @@ - + diff --git a/src/StorageDumper/StorageDumper.csproj b/src/StorageDumper/StorageDumper.csproj index 6ba3c63ea..a291fda32 100644 --- a/src/StorageDumper/StorageDumper.csproj +++ b/src/StorageDumper/StorageDumper.csproj @@ -7,6 +7,6 @@ - + diff --git a/src/TokensTracker/TokensTracker.csproj b/src/TokensTracker/TokensTracker.csproj index f4a8482ee..28ac9bf3d 100644 --- a/src/TokensTracker/TokensTracker.csproj +++ b/src/TokensTracker/TokensTracker.csproj @@ -1,12 +1,11 @@ - - - Neo.Plugins.TokensTracker - Neo.Plugins - - - - - - - + + Neo.Plugins.TokensTracker + + + + false + runtime + + + \ No newline at end of file diff --git a/tests/Directory.Build.props b/tests/Directory.Build.props index bfbc4d574..6ff47a7c2 100644 --- a/tests/Directory.Build.props +++ b/tests/Directory.Build.props @@ -1,15 +1,15 @@ - + - net7.0 false - - - - + + + - - + + + + \ No newline at end of file diff --git a/tests/Neo.Cryptography.MPTTrie.Tests/Neo.Cryptography.MPTTrie.Tests.csproj b/tests/Neo.Cryptography.MPTTrie.Tests/Neo.Cryptography.MPTTrie.Tests.csproj index a2d6822c5..17392da61 100644 --- a/tests/Neo.Cryptography.MPTTrie.Tests/Neo.Cryptography.MPTTrie.Tests.csproj +++ b/tests/Neo.Cryptography.MPTTrie.Tests/Neo.Cryptography.MPTTrie.Tests.csproj @@ -1,16 +1,8 @@ - Neo.Cryptography.MPT.Tests - - - - - - - - + \ No newline at end of file diff --git a/tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj b/tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj index 9815f51e9..38851f4a9 100644 --- a/tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj +++ b/tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj @@ -1,32 +1,21 @@ - Neo.Network.RPC.Tests - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive + + all + runtime; build; native; contentfiles; analyzers; buildtransitive - - PreserveNewest - - - - - - - - + \ No newline at end of file diff --git a/tests/Neo.Plugins.OracleService.Tests/Neo.Plugins.OracleService.Tests.csproj b/tests/Neo.Plugins.OracleService.Tests/Neo.Plugins.OracleService.Tests.csproj index 1584f425f..cb4dd1c6c 100644 --- a/tests/Neo.Plugins.OracleService.Tests/Neo.Plugins.OracleService.Tests.csproj +++ b/tests/Neo.Plugins.OracleService.Tests/Neo.Plugins.OracleService.Tests.csproj @@ -1,23 +1,17 @@ - OracleService.Tests Neo.Plugins - - - + + + false + runtime + - - - - - - - - + \ No newline at end of file diff --git a/tests/Neo.Plugins.RpcServer.Tests/Neo.Plugins.RpcServer.Tests.csproj b/tests/Neo.Plugins.RpcServer.Tests/Neo.Plugins.RpcServer.Tests.csproj index 9508d750e..9b3fcaed4 100644 --- a/tests/Neo.Plugins.RpcServer.Tests/Neo.Plugins.RpcServer.Tests.csproj +++ b/tests/Neo.Plugins.RpcServer.Tests/Neo.Plugins.RpcServer.Tests.csproj @@ -1,22 +1,12 @@ - Neo.Plugins.RpcServer.Tests Neo.Plugins.RpcServer.Tests - - - - - - - - - - + \ No newline at end of file diff --git a/tests/Neo.Plugins.Storage.Tests/Neo.Plugins.Storage.Tests.csproj b/tests/Neo.Plugins.Storage.Tests/Neo.Plugins.Storage.Tests.csproj index 1366e66f8..10f373f5e 100644 --- a/tests/Neo.Plugins.Storage.Tests/Neo.Plugins.Storage.Tests.csproj +++ b/tests/Neo.Plugins.Storage.Tests/Neo.Plugins.Storage.Tests.csproj @@ -1,18 +1,9 @@ - Neo.Plugins.Storage.Tests - - - - - - - - - + \ No newline at end of file From 3e60a1f241e8044f250de9c931586320f9a7e559 Mon Sep 17 00:00:00 2001 From: Shine Li Date: Wed, 6 Dec 2023 14:21:57 +0800 Subject: [PATCH 20/30] update workflow (#856) --- .github/workflows/main.yml | 2 +- Directory.Build.props | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 396a66ba2..a99cbf8ab 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -46,7 +46,7 @@ jobs: id: get_version run: | sudo apt install xmlstarlet - find src -name Directory.Build.props | xargs xmlstarlet sel -N i=http://schemas.microsoft.com/developer/msbuild/2003 -t -v "concat('::set-output name=version::v',//i:VersionPrefix/text())" | xargs echo + find -name Directory.Build.props | xargs xmlstarlet sel -N i=http://schemas.microsoft.com/developer/msbuild/2003 -t -v "concat('::set-output name=version::v',//i:VersionPrefix/text())" | xargs echo - name: Check tag id: check_tag run: curl -s -I ${{ format('https://github.com/{0}/releases/tag/{1}', github.repository, steps.get_version.outputs.version) }} | head -n 1 | cut -d$' ' -f2 | xargs printf "::set-output name=statusCode::%s" | xargs echo diff --git a/Directory.Build.props b/Directory.Build.props index f0d4f85a6..4c77ef351 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,7 +1,7 @@ - 3.6.2 + 3.6.3 net7.0 Neo.Plugins The Neo Project From f4a570526a5ffbc7882ed72ff0036035c8968620 Mon Sep 17 00:00:00 2001 From: Owen Zhang <38493437+superboyiii@users.noreply.github.com> Date: Wed, 6 Dec 2023 14:42:56 +0800 Subject: [PATCH 21/30] Fix stack exception name (#855) * Fix stack exception name * fix stack * show all type and value of stack item * fix for GetInvokeResult * catch all exceptions * fix-message --------- Co-authored-by: Shargon --- src/ApplicationLogs/LogReader.cs | 34 +++++++++------ src/RpcServer/RpcServer.SmartContract.cs | 17 +++++--- .../Neo.Network.RPC.Tests.csproj | 42 +++++++++---------- 3 files changed, 54 insertions(+), 39 deletions(-) diff --git a/src/ApplicationLogs/LogReader.cs b/src/ApplicationLogs/LogReader.cs index 71a9253f0..4d5c7bbc8 100644 --- a/src/ApplicationLogs/LogReader.cs +++ b/src/ApplicationLogs/LogReader.cs @@ -90,14 +90,19 @@ public static JObject TxLogToJson(Blockchain.ApplicationExecuted appExec) trigger["vmstate"] = appExec.VMState; trigger["exception"] = GetExceptionMessage(appExec.Exception); trigger["gasconsumed"] = appExec.GasConsumed.ToString(); - try + var stack = new JArray(); + foreach (var item in appExec.Stack) { - trigger["stack"] = appExec.Stack.Select(q => q.ToJson(Settings.Default.MaxStackSize)).ToArray(); - } - catch (Exception ex) - { - trigger["exception"] = ex.Message; + try + { + stack.Add(item.ToJson(Settings.Default.MaxStackSize)); + } + catch (Exception ex) + { + stack.Add("error: " + ex.Message); + } } + trigger["stack"] = stack; trigger["notifications"] = appExec.Notifications.Select(q => { JObject notification = new JObject(); @@ -133,14 +138,19 @@ public static JObject BlockLogToJson(Block block, IReadOnlyList q.ToJson(Settings.Default.MaxStackSize)).ToArray(); - } - catch (Exception ex) - { - trigger["exception"] = ex.Message; + try + { + stack.Add(item.ToJson(Settings.Default.MaxStackSize)); + } + catch (Exception ex) + { + stack.Add("error: " + ex.Message); + } } + trigger["stack"] = stack; trigger["notifications"] = appExec.Notifications.Select(q => { JObject notification = new JObject(); diff --git a/src/RpcServer/RpcServer.SmartContract.cs b/src/RpcServer/RpcServer.SmartContract.cs index 1a7c24c17..eb5af98f4 100644 --- a/src/RpcServer/RpcServer.SmartContract.cs +++ b/src/RpcServer/RpcServer.SmartContract.cs @@ -93,14 +93,19 @@ private JObject GetInvokeResult(byte[] script, Signer[] signers = null, Witness[ ["storagechanges"] = ToJson(session.Engine.Snapshot.GetChangeSet()) }; } - try + var stack = new JArray(); + foreach (var item in session.Engine.ResultStack) { - json["stack"] = new JArray(session.Engine.ResultStack.Select(p => ToJson(p, session))); - } - catch (InvalidOperationException) - { - json["stack"] = "error: invalid operation"; + try + { + stack.Add(ToJson(item, session)); + } + catch (Exception ex) + { + stack.Add("error: " + ex.Message); + } } + json["stack"] = stack; if (session.Engine.State != VMState.FAULT) { ProcessInvokeWithWallet(json, signers); diff --git a/tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj b/tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj index 38851f4a9..0887cd319 100644 --- a/tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj +++ b/tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj @@ -1,21 +1,21 @@ - - - Neo.Network.RPC.Tests - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - PreserveNewest - - - \ No newline at end of file + + + Neo.Network.RPC.Tests + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + PreserveNewest + + + From cde29160873fd8c669ad5d086e84602049c5fd47 Mon Sep 17 00:00:00 2001 From: Shine Li Date: Wed, 6 Dec 2023 18:30:53 +0800 Subject: [PATCH 22/30] Fix workflow (#857) * update workflow * update depth --- .github/workflows/main.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index a99cbf8ab..4712a2a84 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -46,7 +46,7 @@ jobs: id: get_version run: | sudo apt install xmlstarlet - find -name Directory.Build.props | xargs xmlstarlet sel -N i=http://schemas.microsoft.com/developer/msbuild/2003 -t -v "concat('::set-output name=version::v',//i:VersionPrefix/text())" | xargs echo + find -maxdepth 1 -name Directory.Build.props | xargs xmlstarlet sel -N i=http://schemas.microsoft.com/developer/msbuild/2003 -t -v "concat('::set-output name=version::v',//i:VersionPrefix/text())" | xargs echo - name: Check tag id: check_tag run: curl -s -I ${{ format('https://github.com/{0}/releases/tag/{1}', github.repository, steps.get_version.outputs.version) }} | head -n 1 | cut -d$' ' -f2 | xargs printf "::set-output name=statusCode::%s" | xargs echo From ca8ec52321d25d892ff7507e5f97d6279c9152d2 Mon Sep 17 00:00:00 2001 From: Christopher Schuchardt Date: Thu, 4 Jan 2024 04:13:10 -0500 Subject: [PATCH 23/30] Local dev setup (#861) * Local dev setup * Fix format? * updated file format --- NuGet.Config | 17 +++++++++-------- deps/.gitkeep | 0 global.json | 7 +++++++ 3 files changed, 16 insertions(+), 8 deletions(-) create mode 100644 deps/.gitkeep create mode 100644 global.json diff --git a/NuGet.Config b/NuGet.Config index 5b8642861..897e874c9 100644 --- a/NuGet.Config +++ b/NuGet.Config @@ -1,8 +1,9 @@ - - - - - - - - \ No newline at end of file + + + + + + + + + diff --git a/deps/.gitkeep b/deps/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/global.json b/global.json new file mode 100644 index 000000000..423c2e226 --- /dev/null +++ b/global.json @@ -0,0 +1,7 @@ +{ + "sdk": { + "version": "7.0.404", + "rollForward": "latestFeature", + "allowPrerelease": false + } +} From c4f50a9a226b59207fe1d97a8c266eaa2c863c53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vitor=20Naz=C3=A1rio=20Coelho?= Date: Thu, 4 Jan 2024 06:32:14 -0300 Subject: [PATCH 24/30] Fix response from getversion due to WS removal (#859) * Update RpcServer.Node.cs * Remove more --------- Co-authored-by: Fernando Diaz Toledano --- src/RpcClient/Models/RpcVersion.cs | 4 ---- src/RpcServer/RpcServer.Node.cs | 1 - tests/Neo.Network.RPC.Tests/RpcTestCases.json | 1 - 3 files changed, 6 deletions(-) diff --git a/src/RpcClient/Models/RpcVersion.cs b/src/RpcClient/Models/RpcVersion.cs index 286006fb0..0da7774ed 100644 --- a/src/RpcClient/Models/RpcVersion.cs +++ b/src/RpcClient/Models/RpcVersion.cs @@ -81,8 +81,6 @@ private static string StripPrefix(string s, string prefix) public int TcpPort { get; set; } - public int WsPort { get; set; } - public uint Nonce { get; set; } public string UserAgent { get; set; } @@ -94,7 +92,6 @@ public JObject ToJson() JObject json = new(); json["network"] = Protocol.Network; // Obsolete json["tcpport"] = TcpPort; - json["wsport"] = WsPort; json["nonce"] = Nonce; json["useragent"] = UserAgent; json["protocol"] = Protocol.ToJson(); @@ -106,7 +103,6 @@ public static RpcVersion FromJson(JObject json) return new() { TcpPort = (int)json["tcpport"].AsNumber(), - WsPort = (int)json["wsport"].AsNumber(), Nonce = (uint)json["nonce"].AsNumber(), UserAgent = json["useragent"].AsString(), Protocol = RpcProtocol.FromJson((JObject)json["protocol"]) diff --git a/src/RpcServer/RpcServer.Node.cs b/src/RpcServer/RpcServer.Node.cs index 519f85498..2b0c6f1d2 100644 --- a/src/RpcServer/RpcServer.Node.cs +++ b/src/RpcServer/RpcServer.Node.cs @@ -69,7 +69,6 @@ protected virtual JToken GetVersion(JArray _params) { JObject json = new(); json["tcpport"] = localNode.ListenerTcpPort; - json["wsport"] = localNode.ListenerWsPort; json["nonce"] = LocalNode.Nonce; json["useragent"] = LocalNode.UserAgent; json["protocol"] = new JObject(); diff --git a/tests/Neo.Network.RPC.Tests/RpcTestCases.json b/tests/Neo.Network.RPC.Tests/RpcTestCases.json index c1f89bf37..4e36c98f8 100644 --- a/tests/Neo.Network.RPC.Tests/RpcTestCases.json +++ b/tests/Neo.Network.RPC.Tests/RpcTestCases.json @@ -2471,7 +2471,6 @@ "result": { "network": 0, "tcpport": 20333, - "wsport": 20334, "nonce": 592651621, "useragent": "/Neo:3.0.0-rc1/", "protocol": { From 1a77a6d2d9c282794d1762c07a8ab647d891f96d Mon Sep 17 00:00:00 2001 From: Christopher Schuchardt Date: Thu, 4 Jan 2024 07:21:10 -0500 Subject: [PATCH 25/30] RcpServer: Fixed CORS and Basic Auth (#812) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fixed basic auth to work now, and popup auth window in browser Fixed CORS with basic auth Added AllowOrigins for basic auth to work * Update Settings.cs Fixed a typo with EnableCors using SessionEnabled for default value if no value is present for EnableCors. >Copy and paste isn't your friend sometimes. * Changed from allow all header in CORS to only use the previous specified header for CORS ("Content-Type") * Add "KeepAliveTimeout" and "RequestHeadersTimeout" to config.json and implemented in Settings.cs, RcpServer.cs Changed "KeepAliveTimeout" TimeSpan to seconds. * Update src/RpcServer/RpcServer.cs * Fixed defaults for rpc server settings * Added disable KeepAliveTimeout in rpc server per shargon request --------- Co-authored-by: Christopher R. Schuchardt Co-authored-by: Jimmy Co-authored-by: Vitor Nazário Coelho Co-authored-by: Shargon --- src/RpcServer/RpcServer.cs | 51 +++++++++++++++++++++++++++----- src/RpcServer/RpcServerPlugin.cs | 10 +++++++ src/RpcServer/Settings.cs | 12 ++++++++ src/RpcServer/config.json | 4 +++ 4 files changed, 69 insertions(+), 8 deletions(-) diff --git a/src/RpcServer/RpcServer.cs b/src/RpcServer/RpcServer.cs index 3a199ad3b..c724ae441 100644 --- a/src/RpcServer/RpcServer.cs +++ b/src/RpcServer/RpcServer.cs @@ -54,9 +54,14 @@ private bool CheckAuth(HttpContext context) { if (string.IsNullOrEmpty(settings.RpcUser)) return true; - context.Response.Headers["WWW-Authenticate"] = "Basic realm=\"Restricted\""; - string reqauth = context.Request.Headers["Authorization"]; + if (string.IsNullOrEmpty(reqauth)) + { + context.Response.Headers["WWW-Authenticate"] = "Basic realm=\"Restricted\""; + context.Response.StatusCode = 401; + return false; + } + string authstring; try { @@ -112,10 +117,14 @@ public void StartRpcServer() options.Limits.MaxRequestLineSize = Math.Min(settings.MaxRequestBodySize, options.Limits.MaxRequestLineSize); // Default value is 40 options.Limits.MaxConcurrentConnections = settings.MaxConcurrentConnections; + // Default value is 1 minutes - options.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(1); + options.Limits.KeepAliveTimeout = settings.KeepAliveTimeout == -1 ? + TimeSpan.MaxValue : + TimeSpan.FromSeconds(settings.KeepAliveTimeout); + // Default value is 15 seconds - options.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(15); + options.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(settings.RequestHeadersTimeout); if (string.IsNullOrEmpty(settings.SslCert)) return; listenOptions.UseHttps(settings.SslCert, settings.SslCertPassword, httpsConnectionAdapterOptions => @@ -134,11 +143,41 @@ public void StartRpcServer() })) .Configure(app => { + if (settings.EnableCors) + app.UseCors("All"); + app.UseResponseCompression(); app.Run(ProcessAsync); }) .ConfigureServices(services => { + if (settings.EnableCors) + { + if (settings.AllowOrigins.Length == 0) + services.AddCors(options => + { + options.AddPolicy("All", policy => + { + policy.AllowAnyOrigin() + .WithHeaders("Content-Type") + .WithMethods("GET", "POST"); + // The CORS specification states that setting origins to "*" (all origins) + // is invalid if the Access-Control-Allow-Credentials header is present. + }); + }); + else + services.AddCors(options => + { + options.AddPolicy("All", policy => + { + policy.WithOrigins(settings.AllowOrigins) + .WithHeaders("Content-Type") + .AllowCredentials() + .WithMethods("GET", "POST"); + }); + }); + } + services.AddResponseCompression(options => { // options.EnableForHttps = false; @@ -163,10 +202,6 @@ internal void UpdateSettings(RpcServerSettings settings) public async Task ProcessAsync(HttpContext context) { - context.Response.Headers["Access-Control-Allow-Origin"] = "*"; - context.Response.Headers["Access-Control-Allow-Methods"] = "GET, POST"; - context.Response.Headers["Access-Control-Allow-Headers"] = "Content-Type"; - context.Response.Headers["Access-Control-Max-Age"] = "31536000"; if (context.Request.Method != "GET" && context.Request.Method != "POST") return; JToken request = null; if (context.Request.Method == "GET") diff --git a/src/RpcServer/RpcServerPlugin.cs b/src/RpcServer/RpcServerPlugin.cs index 6e148f4da..92db90d8b 100644 --- a/src/RpcServer/RpcServerPlugin.cs +++ b/src/RpcServer/RpcServerPlugin.cs @@ -42,6 +42,16 @@ protected override void OnSystemLoaded(NeoSystem system) RpcServerSettings s = settings.Servers.FirstOrDefault(p => p.Network == system.Settings.Network); if (s is null) return; + if (s.EnableCors && string.IsNullOrEmpty(s.RpcUser) == false && s.AllowOrigins.Length == 0) + { + Log("RcpServer: CORS is misconfigured!", LogLevel.Warning); + Log($"You have {nameof(s.EnableCors)} and Basic Authentication enabled but " + + $"{nameof(s.AllowOrigins)} is empty in config.json for RcpServer. " + + "You must add url origins to the list to have CORS work from " + + $"browser with basic authentication enabled. " + + $"Example: \"AllowOrigins\": [\"http://{s.BindAddress}:{s.Port}\"]", LogLevel.Info); + } + RpcServer server = new(system, s); if (handlers.Remove(s.Network, out var list)) diff --git a/src/RpcServer/Settings.cs b/src/RpcServer/Settings.cs index ff93b0cc7..b5504df1a 100644 --- a/src/RpcServer/Settings.cs +++ b/src/RpcServer/Settings.cs @@ -39,6 +39,10 @@ public record RpcServerSettings public int MaxRequestBodySize { get; init; } public string RpcUser { get; init; } public string RpcPass { get; init; } + public bool EnableCors { get; init; } + public string[] AllowOrigins { get; init; } + public int KeepAliveTimeout { get; init; } + public uint RequestHeadersTimeout { get; init; } public long MaxGasInvoke { get; init; } public long MaxFee { get; init; } public int MaxIteratorResultItems { get; init; } @@ -57,6 +61,10 @@ public record RpcServerSettings MaxGasInvoke = (long)new BigDecimal(10M, NativeContract.GAS.Decimals).Value, MaxFee = (long)new BigDecimal(0.1M, NativeContract.GAS.Decimals).Value, TrustedAuthorities = Array.Empty(), + EnableCors = true, + AllowOrigins = Array.Empty(), + KeepAliveTimeout = 60, + RequestHeadersTimeout = 15, MaxIteratorResultItems = 100, MaxStackSize = ushort.MaxValue, DisabledMethods = Array.Empty(), @@ -77,6 +85,10 @@ public record RpcServerSettings TrustedAuthorities = section.GetSection("TrustedAuthorities").GetChildren().Select(p => p.Get()).ToArray(), RpcUser = section.GetSection("RpcUser").Value, RpcPass = section.GetSection("RpcPass").Value, + EnableCors = section.GetValue(nameof(EnableCors), Default.EnableCors), + AllowOrigins = section.GetSection(nameof(AllowOrigins)).GetChildren().Select(p => p.Get()).ToArray(), + KeepAliveTimeout = section.GetValue(nameof(KeepAliveTimeout), Default.KeepAliveTimeout), + RequestHeadersTimeout = section.GetValue(nameof(RequestHeadersTimeout), Default.RequestHeadersTimeout), MaxGasInvoke = (long)new BigDecimal(section.GetValue("MaxGasInvoke", Default.MaxGasInvoke), NativeContract.GAS.Decimals).Value, MaxFee = (long)new BigDecimal(section.GetValue("MaxFee", Default.MaxFee), NativeContract.GAS.Decimals).Value, MaxIteratorResultItems = section.GetValue("MaxIteratorResultItems", Default.MaxIteratorResultItems), diff --git a/src/RpcServer/config.json b/src/RpcServer/config.json index cfb60752f..8f6905dea 100644 --- a/src/RpcServer/config.json +++ b/src/RpcServer/config.json @@ -10,6 +10,10 @@ "TrustedAuthorities": [], "RpcUser": "", "RpcPass": "", + "EnableCors": true, + "AllowOrigins": [], + "KeepAliveTimeout": 60, + "RequestHeadersTimeout": 15, "MaxGasInvoke": 20, "MaxFee": 0.1, "MaxConcurrentConnections": 40, From e9e7a07a3e170852b32784c5a48456c63fe55498 Mon Sep 17 00:00:00 2001 From: Christopher Schuchardt Date: Sat, 6 Jan 2024 10:08:32 -0500 Subject: [PATCH 26/30] Added AspNetCore (#863) --- src/RpcServer/RpcServer.csproj | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/RpcServer/RpcServer.csproj b/src/RpcServer/RpcServer.csproj index af5dc619c..68f6e62ed 100644 --- a/src/RpcServer/RpcServer.csproj +++ b/src/RpcServer/RpcServer.csproj @@ -4,4 +4,7 @@ Neo.Plugins.RpcServer + + + From 99b62d4f937381ef2966c9ac896723ecaa37692c Mon Sep 17 00:00:00 2001 From: Christopher Schuchardt Date: Wed, 10 Jan 2024 03:09:55 -0500 Subject: [PATCH 27/30] Update .editorconfig and run code analyze (#866) --- .editorconfig | 289 +++++++- .gitattributes | 64 ++ .gitignore | 660 +++++++++--------- LICENSE | 42 +- SpellingExclusions.dic | 0 src/ApplicationLogs/LogReader.cs | 9 +- src/ApplicationLogs/Settings.cs | 9 +- .../Consensus/ConsensusContext.Get.cs | 9 +- .../Consensus/ConsensusContext.MakePayload.cs | 9 +- src/DBFTPlugin/Consensus/ConsensusContext.cs | 9 +- .../Consensus/ConsensusService.Check.cs | 9 +- .../Consensus/ConsensusService.OnMessage.cs | 9 +- src/DBFTPlugin/Consensus/ConsensusService.cs | 9 +- src/DBFTPlugin/DBFTPlugin.cs | 9 +- src/DBFTPlugin/Messages/ChangeView.cs | 9 +- src/DBFTPlugin/Messages/Commit.cs | 9 +- src/DBFTPlugin/Messages/ConsensusMessage.cs | 9 +- src/DBFTPlugin/Messages/PrepareRequest.cs | 9 +- src/DBFTPlugin/Messages/PrepareResponse.cs | 9 +- ...ecoveryMessage.ChangeViewPayloadCompact.cs | 9 +- .../RecoveryMessage.CommitPayloadCompact.cs | 9 +- ...coveryMessage.PreparationPayloadCompact.cs | 9 +- .../RecoveryMessage/RecoveryMessage.cs | 9 +- .../RecoveryMessage/RecoveryRequest.cs | 9 +- src/DBFTPlugin/Settings.cs | 9 +- src/DBFTPlugin/Types/ChangeViewReason.cs | 9 +- src/DBFTPlugin/Types/ConsensusMessageType.cs | 9 +- src/LevelDBStore/IO/Data/LevelDB/DB.cs | 9 +- src/LevelDBStore/IO/Data/LevelDB/Helper.cs | 9 +- src/LevelDBStore/IO/Data/LevelDB/Iterator.cs | 9 +- .../IO/Data/LevelDB/LevelDBException.cs | 9 +- src/LevelDBStore/IO/Data/LevelDB/Native.cs | 9 +- src/LevelDBStore/IO/Data/LevelDB/Options.cs | 9 +- .../IO/Data/LevelDB/ReadOptions.cs | 9 +- src/LevelDBStore/IO/Data/LevelDB/Snapshot.cs | 9 +- .../IO/Data/LevelDB/WriteBatch.cs | 9 +- .../IO/Data/LevelDB/WriteOptions.cs | 9 +- .../Plugins/Storage/LevelDBStore.cs | 9 +- src/LevelDBStore/Plugins/Storage/Snapshot.cs | 9 +- src/LevelDBStore/Plugins/Storage/Store.cs | 9 +- src/MPTTrie/Cryptography/MPTTrie/Cache.cs | 9 +- src/MPTTrie/Cryptography/MPTTrie/Helper.cs | 9 +- .../Cryptography/MPTTrie/Node.Branch.cs | 9 +- .../Cryptography/MPTTrie/Node.Extension.cs | 9 +- src/MPTTrie/Cryptography/MPTTrie/Node.Hash.cs | 9 +- src/MPTTrie/Cryptography/MPTTrie/Node.Leaf.cs | 9 +- src/MPTTrie/Cryptography/MPTTrie/Node.cs | 9 +- src/MPTTrie/Cryptography/MPTTrie/NodeType.cs | 9 +- .../Cryptography/MPTTrie/Trie.Delete.cs | 9 +- src/MPTTrie/Cryptography/MPTTrie/Trie.Find.cs | 9 +- src/MPTTrie/Cryptography/MPTTrie/Trie.Get.cs | 9 +- .../Cryptography/MPTTrie/Trie.Proof.cs | 9 +- src/MPTTrie/Cryptography/MPTTrie/Trie.Put.cs | 9 +- src/MPTTrie/Cryptography/MPTTrie/Trie.cs | 9 +- src/MPTTrie/IO/ByteArrayEqualityComparer.cs | 9 +- src/MPTTrie/MPTTrie.csproj | 18 +- src/OracleService/Helper.cs | 9 +- src/OracleService/OracleService.cs | 9 +- .../Protocols/IOracleProtocol.cs | 9 +- .../Protocols/OracleHttpsProtocol.cs | 9 +- .../Protocols/OracleNeoFSProtocol.cs | 21 +- src/OracleService/Settings.cs | 9 +- src/RocksDBStore/Plugins/Storage/Options.cs | 9 +- .../Plugins/Storage/RocksDBStore.cs | 9 +- src/RocksDBStore/Plugins/Storage/Snapshot.cs | 9 +- src/RocksDBStore/Plugins/Storage/Store.cs | 9 +- src/RpcClient/ContractClient.cs | 9 +- src/RpcClient/Models/RpcAccount.cs | 9 +- src/RpcClient/Models/RpcApplicationLog.cs | 9 +- src/RpcClient/Models/RpcBlock.cs | 9 +- src/RpcClient/Models/RpcBlockHeader.cs | 9 +- src/RpcClient/Models/RpcContractState.cs | 9 +- src/RpcClient/Models/RpcFoundStates.cs | 9 +- src/RpcClient/Models/RpcInvokeResult.cs | 9 +- src/RpcClient/Models/RpcMethodToken.cs | 9 +- src/RpcClient/Models/RpcNativeContract.cs | 10 +- src/RpcClient/Models/RpcNefFile.cs | 9 +- src/RpcClient/Models/RpcNep17Balances.cs | 9 +- src/RpcClient/Models/RpcNep17TokenInfo.cs | 9 +- src/RpcClient/Models/RpcNep17Transfers.cs | 9 +- src/RpcClient/Models/RpcPeers.cs | 9 +- src/RpcClient/Models/RpcPlugin.cs | 9 +- src/RpcClient/Models/RpcRawMemPool.cs | 9 +- src/RpcClient/Models/RpcRequest.cs | 9 +- src/RpcClient/Models/RpcResponse.cs | 9 +- src/RpcClient/Models/RpcStateRoot.cs | 9 +- src/RpcClient/Models/RpcTransaction.cs | 9 +- src/RpcClient/Models/RpcTransferOut.cs | 9 +- src/RpcClient/Models/RpcUnclaimedGas.cs | 9 +- .../Models/RpcValidateAddressResult.cs | 9 +- src/RpcClient/Models/RpcValidator.cs | 9 +- src/RpcClient/Models/RpcVersion.cs | 9 +- src/RpcClient/Nep17API.cs | 9 +- src/RpcClient/PolicyAPI.cs | 9 +- src/RpcClient/Properties/AssemblyInfo.cs | 9 +- src/RpcClient/RpcClient.cs | 9 +- src/RpcClient/RpcException.cs | 9 +- src/RpcClient/StateAPI.cs | 11 +- src/RpcClient/TransactionManager.cs | 9 +- src/RpcClient/TransactionManagerFactory.cs | 9 +- src/RpcClient/Utility.cs | 9 +- src/RpcClient/WalletAPI.cs | 9 +- src/RpcServer/Diagnostic.cs | 9 +- src/RpcServer/RpcException.cs | 9 +- src/RpcServer/RpcMethodAttribute.cs | 9 +- src/RpcServer/RpcServer.Blockchain.cs | 9 +- src/RpcServer/RpcServer.Node.cs | 9 +- src/RpcServer/RpcServer.SmartContract.cs | 9 +- src/RpcServer/RpcServer.Utilities.cs | 9 +- src/RpcServer/RpcServer.Wallet.cs | 9 +- src/RpcServer/RpcServer.cs | 9 +- src/RpcServer/RpcServerPlugin.cs | 9 +- src/RpcServer/Session.cs | 9 +- src/RpcServer/Settings.cs | 9 +- src/RpcServer/Tree.cs | 9 +- src/RpcServer/TreeNode.cs | 9 +- src/RpcServer/Utility.cs | 9 +- src/SQLiteWallet/Account.cs | 13 +- src/SQLiteWallet/Address.cs | 13 +- src/SQLiteWallet/Contract.cs | 13 +- src/SQLiteWallet/Key.cs | 13 +- src/SQLiteWallet/SQLiteWallet.cs | 13 +- src/SQLiteWallet/SQLiteWallet.csproj | 26 +- src/SQLiteWallet/SQLiteWalletAccount.cs | 13 +- src/SQLiteWallet/SQLiteWalletFactory.cs | 13 +- src/SQLiteWallet/VerificationContract.cs | 13 +- src/SQLiteWallet/WalletDataContext.cs | 13 +- src/StateService/Network/MessageType.cs | 9 +- src/StateService/Network/StateRoot.cs | 9 +- src/StateService/Network/Vote.cs | 9 +- src/StateService/Settings.cs | 9 +- src/StateService/StatePlugin.cs | 9 +- src/StateService/Storage/Keys.cs | 9 +- src/StateService/Storage/StateSnapshot.cs | 9 +- src/StateService/Storage/StateStore.cs | 9 +- .../Verification/VerificationContext.cs | 9 +- .../Verification/VerificationService.cs | 9 +- src/StatesDumper/PersistActions.cs | 9 +- src/StatesDumper/Settings.cs | 9 +- src/StatesDumper/StatesDumper.cs | 9 +- src/StorageDumper/Settings.cs | 13 +- src/StorageDumper/StorageDumper.cs | 17 +- src/TokensTracker/Extensions.cs | 15 +- src/TokensTracker/TokensTracker.cs | 9 +- .../Trackers/NEP-11/Nep11BalanceKey.cs | 9 +- .../Trackers/NEP-11/Nep11Tracker.cs | 9 +- .../Trackers/NEP-11/Nep11TransferKey.cs | 9 +- .../Trackers/NEP-17/Nep17BalanceKey.cs | 9 +- .../Trackers/NEP-17/Nep17Tracker.cs | 9 +- .../Trackers/NEP-17/Nep17TransferKey.cs | 11 +- src/TokensTracker/Trackers/TokenBalance.cs | 9 +- src/TokensTracker/Trackers/TokenTransfer.cs | 9 +- .../Trackers/TokenTransferKey.cs | 9 +- src/TokensTracker/Trackers/TrackerBase.cs | 9 +- .../Cryptography/MPTTrie/Helper.cs | 11 + .../Cryptography/MPTTrie/UT_Cache.cs | 11 + .../Cryptography/MPTTrie/UT_Helper.cs | 11 + .../Cryptography/MPTTrie/UT_Node.cs | 11 + .../Cryptography/MPTTrie/UT_Trie.cs | 11 + .../Neo.Network.RPC.Tests.csproj | 42 +- tests/Neo.Network.RPC.Tests/TestUtils.cs | 11 + .../UT_ContractClient.cs | 11 + tests/Neo.Network.RPC.Tests/UT_Nep17API.cs | 19 +- tests/Neo.Network.RPC.Tests/UT_PolicyAPI.cs | 11 + tests/Neo.Network.RPC.Tests/UT_RpcClient.cs | 11 + tests/Neo.Network.RPC.Tests/UT_RpcModels.cs | 11 + .../UT_TransactionManager.cs | 11 + tests/Neo.Network.RPC.Tests/UT_Utility.cs | 11 + tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs | 11 + .../TestBlockchain.cs | 11 + .../TestUtils.cs | 11 + .../UT_OracleService.cs | 13 +- .../UT_RpcServer.cs | 11 + tests/Neo.Plugins.Storage.Tests/StoreTest.cs | 11 + 174 files changed, 1726 insertions(+), 1028 deletions(-) create mode 100644 .gitattributes create mode 100644 SpellingExclusions.dic diff --git a/.editorconfig b/.editorconfig index 5acd074d2..269a7e444 100644 --- a/.editorconfig +++ b/.editorconfig @@ -6,12 +6,297 @@ # dotnet tool update -g dotnet-format # remember to have: git config --global core.autocrlf false #(which is usually default) +# top-most EditorConfig file root = true -# Every file - +# Don't use tabs for indentation. [*] +indent_style = space insert_final_newline = true trim_trailing_whitespace = true charset = utf-8 end_of_line = lf + +# (Please don't specify an indent_size here; that has too many unintended consequences.) +spelling_exclusion_path = SpellingExclusions.dic + +# Code files +[*.{cs,csx,vb,vbx}] +indent_size = 4 +insert_final_newline = true +trim_trailing_whitespace = true +charset = utf-8 + +# XML project files +[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}] +indent_size = 2 + +# XML config files +[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}] +indent_size = 2 + +# JSON files +[*.json] +indent_size = 2 + +# Powershell files +[*.ps1] +indent_size = 2 + +# Shell script files +[*.sh] +end_of_line = lf +indent_size = 2 + +# Dotnet code style settings: +[*.{cs,vb}] +# Member can be made 'readonly' +csharp_style_prefer_readonly_struct_member = true +dotnet_diagnostic.IDE0251.severity = warning +dotnet_diagnostic.IDE0044.severity = warning + +dotnet_diagnostic.CS1591.severity = silent + +# Sort using and Import directives with System.* appearing first +dotnet_sort_system_directives_first = false +dotnet_separate_import_directive_groups = false +# Avoid "this." and "Me." if not necessary +dotnet_style_qualification_for_field = false:refactoring +dotnet_style_qualification_for_property = false:refactoring +dotnet_style_qualification_for_method = false:refactoring +dotnet_style_qualification_for_event = false:refactoring + +# Use language keywords instead of framework type names for type references +dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion +dotnet_style_predefined_type_for_member_access = true:suggestion + +# Suggest more modern language features when available +dotnet_style_object_initializer = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion + +# Whitespace options +dotnet_style_allow_multiple_blank_lines_experimental = false + +# Non-private static fields are PascalCase +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.symbols = non_private_static_fields +dotnet_naming_rule.non_private_static_fields_should_be_pascal_case.style = non_private_static_field_style + +dotnet_naming_symbols.non_private_static_fields.applicable_kinds = field +dotnet_naming_symbols.non_private_static_fields.applicable_accessibilities = public, protected, internal, protected_internal, private_protected +dotnet_naming_symbols.non_private_static_fields.required_modifiers = static + +dotnet_naming_style.non_private_static_field_style.capitalization = pascal_case + +# Non-private readonly fields are PascalCase +dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.symbols = non_private_readonly_fields +dotnet_naming_rule.non_private_readonly_fields_should_be_pascal_case.style = non_private_readonly_field_style + +dotnet_naming_symbols.non_private_readonly_fields.applicable_kinds = field +dotnet_naming_symbols.non_private_readonly_fields.applicable_accessibilities = public, protected, internal, protected_internal, private_protected +dotnet_naming_symbols.non_private_readonly_fields.required_modifiers = readonly + +dotnet_naming_style.non_private_readonly_field_style.capitalization = pascal_case + +# Constants are PascalCase +dotnet_naming_rule.constants_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.constants_should_be_pascal_case.symbols = constants +dotnet_naming_rule.constants_should_be_pascal_case.style = constant_style + +dotnet_naming_symbols.constants.applicable_kinds = field, local +dotnet_naming_symbols.constants.required_modifiers = const + +dotnet_naming_style.constant_style.capitalization = pascal_case + +# Static fields are camelCase and start with s_ +dotnet_naming_rule.static_fields_should_be_camel_case.severity = suggestion +dotnet_naming_rule.static_fields_should_be_camel_case.symbols = static_fields +dotnet_naming_rule.static_fields_should_be_camel_case.style = static_field_style + +dotnet_naming_symbols.static_fields.applicable_kinds = field +dotnet_naming_symbols.static_fields.required_modifiers = static + +dotnet_naming_style.static_field_style.capitalization = camel_case +dotnet_naming_style.static_field_style.required_prefix = s_ + +# Instance fields are camelCase and start with _ +dotnet_naming_rule.instance_fields_should_be_camel_case.severity = suggestion +dotnet_naming_rule.instance_fields_should_be_camel_case.symbols = instance_fields +dotnet_naming_rule.instance_fields_should_be_camel_case.style = instance_field_style + +dotnet_naming_symbols.instance_fields.applicable_kinds = field + +dotnet_naming_style.instance_field_style.capitalization = camel_case +dotnet_naming_style.instance_field_style.required_prefix = _ + +# Locals and parameters are camelCase +dotnet_naming_rule.locals_should_be_camel_case.severity = suggestion +dotnet_naming_rule.locals_should_be_camel_case.symbols = locals_and_parameters +dotnet_naming_rule.locals_should_be_camel_case.style = camel_case_style + +dotnet_naming_symbols.locals_and_parameters.applicable_kinds = parameter, local + +dotnet_naming_style.camel_case_style.capitalization = camel_case + +# Local functions are PascalCase +dotnet_naming_rule.local_functions_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.local_functions_should_be_pascal_case.symbols = local_functions +dotnet_naming_rule.local_functions_should_be_pascal_case.style = local_function_style + +dotnet_naming_symbols.local_functions.applicable_kinds = local_function + +dotnet_naming_style.local_function_style.capitalization = pascal_case + +# By default, name items with PascalCase +dotnet_naming_rule.members_should_be_pascal_case.severity = suggestion +dotnet_naming_rule.members_should_be_pascal_case.symbols = all_members +dotnet_naming_rule.members_should_be_pascal_case.style = pascal_case_style + +dotnet_naming_symbols.all_members.applicable_kinds = * + +dotnet_naming_style.pascal_case_style.capitalization = pascal_case + +file_header_template = Copyright (C) 2015-2024 The Neo Project.\n\n{fileName} file belongs to the neo project and is free\nsoftware distributed under the MIT software license, see the\naccompanying file LICENSE in the main directory of the\nrepository or http://www.opensource.org/licenses/mit-license.php\nfor more details.\n\nRedistribution and use in source and binary forms with or without\nmodifications are permitted. + +# Require file header +dotnet_diagnostic.IDE0073.severity = error + +# RS0016: Only enable if API files are present +dotnet_public_api_analyzer.require_api_files = true + +# IDE0055: Fix formatting +# Workaround for https://github.com/dotnet/roslyn/issues/70570 +dotnet_diagnostic.IDE0055.severity = warning + +# CSharp code style settings: +[*.cs] +# Newline settings +csharp_new_line_before_open_brace = all +csharp_new_line_before_else = true +csharp_new_line_before_catch = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_between_query_expression_clauses = true + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_switch_labels = true +csharp_indent_labels = flush_left + +# Whitespace options +csharp_style_allow_embedded_statements_on_same_line_experimental = false +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = false +csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = false +csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = false + +# Prefer "var" everywhere +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion +csharp_style_var_elsewhere = true:suggestion + +# Prefer method-like constructs to have a block body +csharp_style_expression_bodied_methods = false:none +csharp_style_expression_bodied_constructors = false:none +csharp_style_expression_bodied_operators = false:none + +# Prefer property-like constructs to have an expression-body +csharp_style_expression_bodied_properties = true:none +csharp_style_expression_bodied_indexers = true:none +csharp_style_expression_bodied_accessors = true:none + +# Suggest more modern language features when available +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_throw_expression = true:suggestion +csharp_style_conditional_delegate_call = true:suggestion +csharp_style_prefer_extended_property_pattern = true:suggestion + +# Space preferences +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = do_not_ignore +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false + +# Blocks are allowed +csharp_prefer_braces = true:silent +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = true + +# IDE0060: Remove unused parameter +dotnet_diagnostic.IDE0060.severity = none + +[src/{Analyzers,CodeStyle,Features,Workspaces,EditorFeatures,VisualStudio}/**/*.{cs,vb}] + +# IDE0011: Add braces +csharp_prefer_braces = when_multiline:warning +# NOTE: We need the below severity entry for Add Braces due to https://github.com/dotnet/roslyn/issues/44201 +dotnet_diagnostic.IDE0011.severity = warning + +# IDE0040: Add accessibility modifiers +dotnet_diagnostic.IDE0040.severity = warning + +# IDE0052: Remove unread private member +dotnet_diagnostic.IDE0052.severity = warning + +# IDE0059: Unnecessary assignment to a value +dotnet_diagnostic.IDE0059.severity = warning + +# CA1012: Abstract types should not have public constructors +dotnet_diagnostic.CA1012.severity = warning + +# CA1822: Make member static +dotnet_diagnostic.CA1822.severity = warning + +# Prefer "var" everywhere +dotnet_diagnostic.IDE0007.severity = warning +csharp_style_var_for_built_in_types = true:warning +csharp_style_var_when_type_is_apparent = true:warning +csharp_style_var_elsewhere = true:warning + +# csharp_style_allow_embedded_statements_on_same_line_experimental +dotnet_diagnostic.IDE2001.severity = warning + +# csharp_style_allow_blank_lines_between_consecutive_braces_experimental +dotnet_diagnostic.IDE2002.severity = warning + +# csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental +dotnet_diagnostic.IDE2004.severity = warning + +# csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental +dotnet_diagnostic.IDE2005.severity = warning + +# csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental +dotnet_diagnostic.IDE2006.severity = warning + +[src/{VisualStudio}/**/*.{cs,vb}] +# CA1822: Make member static +# There is a risk of accidentally breaking an internal API that partners rely on though IVT. +dotnet_code_quality.CA1822.api_surface = private \ No newline at end of file diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..0c37abbc2 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,64 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text eol=lf + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +*.sln text eol=crlf +#*.csproj text eol=crlf +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +*.jpg binary +*.png binary +*.gif binary +*.ico binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore index 29c559f83..3e759b75b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,330 +1,330 @@ -## Ignore Visual Studio temporary files, build results, and -## files generated by popular Visual Studio add-ons. -## -## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore - -# User-specific files -*.suo -*.user -*.userosscache -*.sln.docstates - -# User-specific files (MonoDevelop/Xamarin Studio) -*.userprefs - -# Build results -[Dd]ebug/ -[Dd]ebugPublic/ -[Rr]elease/ -[Rr]eleases/ -x64/ -x86/ -bld/ -[Bb]in/ -[Oo]bj/ -[Ll]og/ - -# Visual Studio 2015/2017 cache/options directory -.vs/ -# Uncomment if you have tasks that create the project's static files in wwwroot -#wwwroot/ - -# Visual Studio 2017 auto generated files -Generated\ Files/ - -# MSTest test Results -[Tt]est[Rr]esult*/ -[Bb]uild[Ll]og.* - -# NUNIT -*.VisualState.xml -TestResult.xml - -# Build Results of an ATL Project -[Dd]ebugPS/ -[Rr]eleasePS/ -dlldata.c - -# Benchmark Results -BenchmarkDotNet.Artifacts/ - -# .NET Core -project.lock.json -project.fragment.lock.json -artifacts/ -**/Properties/launchSettings.json - -# StyleCop -StyleCopReport.xml - -# Files built by Visual Studio -*_i.c -*_p.c -*_i.h -*.ilk -*.meta -*.obj -*.iobj -*.pch -*.pdb -*.ipdb -*.pgc -*.pgd -*.rsp -*.sbr -*.tlb -*.tli -*.tlh -*.tmp -*.tmp_proj -*.log -*.vspscc -*.vssscc -.builds -*.pidb -*.svclog -*.scc - -# Chutzpah Test files -_Chutzpah* - -# Visual C++ cache files -ipch/ -*.aps -*.ncb -*.opendb -*.opensdf -*.sdf -*.cachefile -*.VC.db -*.VC.VC.opendb - -# Visual Studio profiler -*.psess -*.vsp -*.vspx -*.sap - -# Visual Studio Trace Files -*.e2e - -# TFS 2012 Local Workspace -$tf/ - -# Guidance Automation Toolkit -*.gpState - -# ReSharper is a .NET coding add-in -_ReSharper*/ -*.[Rr]e[Ss]harper -*.DotSettings.user - -# JustCode is a .NET coding add-in -.JustCode - -# TeamCity is a build add-in -_TeamCity* - -# DotCover is a Code Coverage Tool -*.dotCover - -# AxoCover is a Code Coverage Tool -.axoCover/* -!.axoCover/settings.json - -# Visual Studio code coverage results -*.coverage -*.coveragexml - -# NCrunch -_NCrunch_* -.*crunch*.local.xml -nCrunchTemp_* - -# MightyMoose -*.mm.* -AutoTest.Net/ - -# Web workbench (sass) -.sass-cache/ - -# Installshield output folder -[Ee]xpress/ - -# DocProject is a documentation generator add-in -DocProject/buildhelp/ -DocProject/Help/*.HxT -DocProject/Help/*.HxC -DocProject/Help/*.hhc -DocProject/Help/*.hhk -DocProject/Help/*.hhp -DocProject/Help/Html2 -DocProject/Help/html - -# Click-Once directory -publish/ - -# Publish Web Output -*.[Pp]ublish.xml -*.azurePubxml -# Note: Comment the next line if you want to checkin your web deploy settings, -# but database connection strings (with potential passwords) will be unencrypted -*.pubxml -*.publishproj - -# Microsoft Azure Web App publish settings. Comment the next line if you want to -# checkin your Azure Web App publish settings, but sensitive information contained -# in these scripts will be unencrypted -PublishScripts/ - -# NuGet Packages -*.nupkg -# The packages folder can be ignored because of Package Restore -**/[Pp]ackages/* -# except build/, which is used as an MSBuild target. -!**/[Pp]ackages/build/ -# Uncomment if necessary however generally it will be regenerated when needed -#!**/[Pp]ackages/repositories.config -# NuGet v3's project.json files produces more ignorable files -*.nuget.props -*.nuget.targets - -# Microsoft Azure Build Output -csx/ -*.build.csdef - -# Microsoft Azure Emulator -ecf/ -rcf/ - -# Windows Store app package directories and files -AppPackages/ -BundleArtifacts/ -Package.StoreAssociation.xml -_pkginfo.txt -*.appx - -# Visual Studio cache files -# files ending in .cache can be ignored -*.[Cc]ache -# but keep track of directories ending in .cache -!*.[Cc]ache/ - -# Others -ClientBin/ -~$* -*~ -*.dbmdl -*.dbproj.schemaview -*.jfm -*.pfx -*.publishsettings -orleans.codegen.cs - -# Including strong name files can present a security risk -# (https://github.com/github/gitignore/pull/2483#issue-259490424) -#*.snk - -# Since there are multiple workflows, uncomment next line to ignore bower_components -# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) -#bower_components/ - -# RIA/Silverlight projects -Generated_Code/ - -# Backup & report files from converting an old project file -# to a newer Visual Studio version. Backup files are not needed, -# because we have git ;-) -_UpgradeReport_Files/ -Backup*/ -UpgradeLog*.XML -UpgradeLog*.htm -ServiceFabricBackup/ -*.rptproj.bak - -# SQL Server files -*.mdf -*.ldf -*.ndf - -# Business Intelligence projects -*.rdl.data -*.bim.layout -*.bim_*.settings -*.rptproj.rsuser - -# Microsoft Fakes -FakesAssemblies/ - -# GhostDoc plugin setting file -*.GhostDoc.xml - -# Node.js Tools for Visual Studio -.ntvs_analysis.dat -node_modules/ - -# Visual Studio 6 build log -*.plg - -# Visual Studio 6 workspace options file -*.opt - -# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) -*.vbw - -# Visual Studio LightSwitch build output -**/*.HTMLClient/GeneratedArtifacts -**/*.DesktopClient/GeneratedArtifacts -**/*.DesktopClient/ModelManifest.xml -**/*.Server/GeneratedArtifacts -**/*.Server/ModelManifest.xml -_Pvt_Extensions - -# Paket dependency manager -.paket/paket.exe -paket-files/ - -# FAKE - F# Make -.fake/ - -# JetBrains Rider -.idea/ -*.sln.iml - -# CodeRush -.cr/ - -# Python Tools for Visual Studio (PTVS) -__pycache__/ -*.pyc - -# Cake - Uncomment if you are using it -# tools/** -# !tools/packages.config - -# Tabs Studio -*.tss - -# Telerik's JustMock configuration file -*.jmconfig - -# BizTalk build output -*.btp.cs -*.btm.cs -*.odx.cs -*.xsd.cs - -# OpenCover UI analysis results -OpenCover/ - -# Azure Stream Analytics local run output -ASALocalRun/ - -# MSBuild Binary and Structured Log -*.binlog - -# NVidia Nsight GPU debugger configuration file -*.nvuser - -# MFractors (Xamarin productivity tool) working folder -.mfractor/ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ +**/Properties/launchSettings.json + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ diff --git a/LICENSE b/LICENSE index 93691646b..914d5c70d 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,21 @@ -MIT License - -Copyright (c) 2018 The Neo Project - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +MIT License + +Copyright (c) 2018 The Neo Project + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/SpellingExclusions.dic b/SpellingExclusions.dic new file mode 100644 index 000000000..e69de29bb diff --git a/src/ApplicationLogs/LogReader.cs b/src/ApplicationLogs/LogReader.cs index 4d5c7bbc8..5c42d6a0d 100644 --- a/src/ApplicationLogs/LogReader.cs +++ b/src/ApplicationLogs/LogReader.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.ApplicationLogs 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 +// LogReader.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/ApplicationLogs/Settings.cs b/src/ApplicationLogs/Settings.cs index 3e1c3ef79..4a32a117a 100644 --- a/src/ApplicationLogs/Settings.cs +++ b/src/ApplicationLogs/Settings.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.ApplicationLogs 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 +// Settings.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/DBFTPlugin/Consensus/ConsensusContext.Get.cs b/src/DBFTPlugin/Consensus/ConsensusContext.Get.cs index d9242f05c..b54b6eca1 100644 --- a/src/DBFTPlugin/Consensus/ConsensusContext.Get.cs +++ b/src/DBFTPlugin/Consensus/ConsensusContext.Get.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Consensus.DBFT 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 +// ConsensusContext.Get.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/DBFTPlugin/Consensus/ConsensusContext.MakePayload.cs b/src/DBFTPlugin/Consensus/ConsensusContext.MakePayload.cs index 80ddc0a94..a761cbafb 100644 --- a/src/DBFTPlugin/Consensus/ConsensusContext.MakePayload.cs +++ b/src/DBFTPlugin/Consensus/ConsensusContext.MakePayload.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Consensus.DBFT 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 +// ConsensusContext.MakePayload.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/DBFTPlugin/Consensus/ConsensusContext.cs b/src/DBFTPlugin/Consensus/ConsensusContext.cs index ebf406b4c..a224e31d2 100644 --- a/src/DBFTPlugin/Consensus/ConsensusContext.cs +++ b/src/DBFTPlugin/Consensus/ConsensusContext.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Consensus.DBFT 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 +// ConsensusContext.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/DBFTPlugin/Consensus/ConsensusService.Check.cs b/src/DBFTPlugin/Consensus/ConsensusService.Check.cs index f6813f101..3b15bcd8f 100644 --- a/src/DBFTPlugin/Consensus/ConsensusService.Check.cs +++ b/src/DBFTPlugin/Consensus/ConsensusService.Check.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Consensus.DBFT 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 +// ConsensusService.Check.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/DBFTPlugin/Consensus/ConsensusService.OnMessage.cs b/src/DBFTPlugin/Consensus/ConsensusService.OnMessage.cs index 4dc9f534d..ecc31f7ba 100644 --- a/src/DBFTPlugin/Consensus/ConsensusService.OnMessage.cs +++ b/src/DBFTPlugin/Consensus/ConsensusService.OnMessage.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Consensus.DBFT 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 +// ConsensusService.OnMessage.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/DBFTPlugin/Consensus/ConsensusService.cs b/src/DBFTPlugin/Consensus/ConsensusService.cs index dcf17f84f..bd32c3ce5 100644 --- a/src/DBFTPlugin/Consensus/ConsensusService.cs +++ b/src/DBFTPlugin/Consensus/ConsensusService.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Consensus.DBFT 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 +// ConsensusService.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/DBFTPlugin/DBFTPlugin.cs b/src/DBFTPlugin/DBFTPlugin.cs index 1a332fb9b..7fa29ce0d 100644 --- a/src/DBFTPlugin/DBFTPlugin.cs +++ b/src/DBFTPlugin/DBFTPlugin.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Consensus.DBFT 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 +// DBFTPlugin.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/DBFTPlugin/Messages/ChangeView.cs b/src/DBFTPlugin/Messages/ChangeView.cs index 54dca646c..e7be40075 100644 --- a/src/DBFTPlugin/Messages/ChangeView.cs +++ b/src/DBFTPlugin/Messages/ChangeView.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Consensus.DBFT 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 +// ChangeView.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/DBFTPlugin/Messages/Commit.cs b/src/DBFTPlugin/Messages/Commit.cs index 6a8fa988d..6e8fe93d8 100644 --- a/src/DBFTPlugin/Messages/Commit.cs +++ b/src/DBFTPlugin/Messages/Commit.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Consensus.DBFT 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 +// Commit.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/DBFTPlugin/Messages/ConsensusMessage.cs b/src/DBFTPlugin/Messages/ConsensusMessage.cs index 370e7da86..93e3c7d6f 100644 --- a/src/DBFTPlugin/Messages/ConsensusMessage.cs +++ b/src/DBFTPlugin/Messages/ConsensusMessage.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Consensus.DBFT 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 +// ConsensusMessage.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/DBFTPlugin/Messages/PrepareRequest.cs b/src/DBFTPlugin/Messages/PrepareRequest.cs index 2a5516465..2bce609f7 100644 --- a/src/DBFTPlugin/Messages/PrepareRequest.cs +++ b/src/DBFTPlugin/Messages/PrepareRequest.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Consensus.DBFT 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 +// PrepareRequest.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/DBFTPlugin/Messages/PrepareResponse.cs b/src/DBFTPlugin/Messages/PrepareResponse.cs index 781c78ece..7510ff99b 100644 --- a/src/DBFTPlugin/Messages/PrepareResponse.cs +++ b/src/DBFTPlugin/Messages/PrepareResponse.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Consensus.DBFT 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 +// PrepareResponse.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.ChangeViewPayloadCompact.cs b/src/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.ChangeViewPayloadCompact.cs index 810624c1a..6a7734e56 100644 --- a/src/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.ChangeViewPayloadCompact.cs +++ b/src/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.ChangeViewPayloadCompact.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Consensus.DBFT 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 +// RecoveryMessage.ChangeViewPayloadCompact.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.CommitPayloadCompact.cs b/src/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.CommitPayloadCompact.cs index fd2e01b47..2dfa16597 100644 --- a/src/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.CommitPayloadCompact.cs +++ b/src/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.CommitPayloadCompact.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Consensus.DBFT 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 +// RecoveryMessage.CommitPayloadCompact.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.PreparationPayloadCompact.cs b/src/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.PreparationPayloadCompact.cs index d252b7eb8..80b2a48b6 100644 --- a/src/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.PreparationPayloadCompact.cs +++ b/src/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.PreparationPayloadCompact.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Consensus.DBFT 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 +// RecoveryMessage.PreparationPayloadCompact.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.cs b/src/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.cs index eaae0c688..fc688d6a1 100644 --- a/src/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.cs +++ b/src/DBFTPlugin/Messages/RecoveryMessage/RecoveryMessage.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Consensus.DBFT 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 +// RecoveryMessage.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/DBFTPlugin/Messages/RecoveryMessage/RecoveryRequest.cs b/src/DBFTPlugin/Messages/RecoveryMessage/RecoveryRequest.cs index d1c5ce7a2..84cd381ad 100644 --- a/src/DBFTPlugin/Messages/RecoveryMessage/RecoveryRequest.cs +++ b/src/DBFTPlugin/Messages/RecoveryMessage/RecoveryRequest.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Consensus.DBFT 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 +// RecoveryRequest.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/DBFTPlugin/Settings.cs b/src/DBFTPlugin/Settings.cs index c19921ff1..d0ecbb63f 100644 --- a/src/DBFTPlugin/Settings.cs +++ b/src/DBFTPlugin/Settings.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Consensus.DBFT 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 +// Settings.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/DBFTPlugin/Types/ChangeViewReason.cs b/src/DBFTPlugin/Types/ChangeViewReason.cs index 6c62388dc..4c0a3c110 100644 --- a/src/DBFTPlugin/Types/ChangeViewReason.cs +++ b/src/DBFTPlugin/Types/ChangeViewReason.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Consensus.DBFT 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 +// ChangeViewReason.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/DBFTPlugin/Types/ConsensusMessageType.cs b/src/DBFTPlugin/Types/ConsensusMessageType.cs index 00fdde096..f325133f0 100644 --- a/src/DBFTPlugin/Types/ConsensusMessageType.cs +++ b/src/DBFTPlugin/Types/ConsensusMessageType.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Consensus.DBFT 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 +// ConsensusMessageType.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/LevelDBStore/IO/Data/LevelDB/DB.cs b/src/LevelDBStore/IO/Data/LevelDB/DB.cs index e53b0c0e7..60e0e24e5 100644 --- a/src/LevelDBStore/IO/Data/LevelDB/DB.cs +++ b/src/LevelDBStore/IO/Data/LevelDB/DB.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.Storage.LevelDBStore 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 +// DB.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/LevelDBStore/IO/Data/LevelDB/Helper.cs b/src/LevelDBStore/IO/Data/LevelDB/Helper.cs index 7fb14d9cf..2ac3a0005 100644 --- a/src/LevelDBStore/IO/Data/LevelDB/Helper.cs +++ b/src/LevelDBStore/IO/Data/LevelDB/Helper.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.Storage.LevelDBStore 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 +// Helper.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/LevelDBStore/IO/Data/LevelDB/Iterator.cs b/src/LevelDBStore/IO/Data/LevelDB/Iterator.cs index 79731de7c..6c025380f 100644 --- a/src/LevelDBStore/IO/Data/LevelDB/Iterator.cs +++ b/src/LevelDBStore/IO/Data/LevelDB/Iterator.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.Storage.LevelDBStore 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 +// Iterator.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/LevelDBStore/IO/Data/LevelDB/LevelDBException.cs b/src/LevelDBStore/IO/Data/LevelDB/LevelDBException.cs index 86dfbadc0..c9cca4207 100644 --- a/src/LevelDBStore/IO/Data/LevelDB/LevelDBException.cs +++ b/src/LevelDBStore/IO/Data/LevelDB/LevelDBException.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.Storage.LevelDBStore 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 +// LevelDBException.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/LevelDBStore/IO/Data/LevelDB/Native.cs b/src/LevelDBStore/IO/Data/LevelDB/Native.cs index 8f1a8d7d0..acf8fa82b 100644 --- a/src/LevelDBStore/IO/Data/LevelDB/Native.cs +++ b/src/LevelDBStore/IO/Data/LevelDB/Native.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.Storage.LevelDBStore 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 +// Native.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/LevelDBStore/IO/Data/LevelDB/Options.cs b/src/LevelDBStore/IO/Data/LevelDB/Options.cs index 4c3d29c5f..989987eee 100644 --- a/src/LevelDBStore/IO/Data/LevelDB/Options.cs +++ b/src/LevelDBStore/IO/Data/LevelDB/Options.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.Storage.LevelDBStore 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 +// Options.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/LevelDBStore/IO/Data/LevelDB/ReadOptions.cs b/src/LevelDBStore/IO/Data/LevelDB/ReadOptions.cs index 03c6053c8..727ae9f02 100644 --- a/src/LevelDBStore/IO/Data/LevelDB/ReadOptions.cs +++ b/src/LevelDBStore/IO/Data/LevelDB/ReadOptions.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.Storage.LevelDBStore 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 +// ReadOptions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/LevelDBStore/IO/Data/LevelDB/Snapshot.cs b/src/LevelDBStore/IO/Data/LevelDB/Snapshot.cs index 81c9f54b5..ed5d9fb55 100644 --- a/src/LevelDBStore/IO/Data/LevelDB/Snapshot.cs +++ b/src/LevelDBStore/IO/Data/LevelDB/Snapshot.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.Storage.LevelDBStore 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 +// Snapshot.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/LevelDBStore/IO/Data/LevelDB/WriteBatch.cs b/src/LevelDBStore/IO/Data/LevelDB/WriteBatch.cs index 06491f87b..ad82dad45 100644 --- a/src/LevelDBStore/IO/Data/LevelDB/WriteBatch.cs +++ b/src/LevelDBStore/IO/Data/LevelDB/WriteBatch.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.Storage.LevelDBStore 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 +// WriteBatch.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/LevelDBStore/IO/Data/LevelDB/WriteOptions.cs b/src/LevelDBStore/IO/Data/LevelDB/WriteOptions.cs index b0e2390ef..48915ba48 100644 --- a/src/LevelDBStore/IO/Data/LevelDB/WriteOptions.cs +++ b/src/LevelDBStore/IO/Data/LevelDB/WriteOptions.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.Storage.LevelDBStore 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 +// WriteOptions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/LevelDBStore/Plugins/Storage/LevelDBStore.cs b/src/LevelDBStore/Plugins/Storage/LevelDBStore.cs index 95cbda05d..9c676e8a7 100644 --- a/src/LevelDBStore/Plugins/Storage/LevelDBStore.cs +++ b/src/LevelDBStore/Plugins/Storage/LevelDBStore.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.Storage.LevelDBStore 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 +// LevelDBStore.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/LevelDBStore/Plugins/Storage/Snapshot.cs b/src/LevelDBStore/Plugins/Storage/Snapshot.cs index 07fce9f20..8da1c6334 100644 --- a/src/LevelDBStore/Plugins/Storage/Snapshot.cs +++ b/src/LevelDBStore/Plugins/Storage/Snapshot.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.Storage.LevelDBStore 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 +// Snapshot.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/LevelDBStore/Plugins/Storage/Store.cs b/src/LevelDBStore/Plugins/Storage/Store.cs index 16f136430..809858dda 100644 --- a/src/LevelDBStore/Plugins/Storage/Store.cs +++ b/src/LevelDBStore/Plugins/Storage/Store.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.Storage.LevelDBStore 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 +// Store.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/MPTTrie/Cryptography/MPTTrie/Cache.cs b/src/MPTTrie/Cryptography/MPTTrie/Cache.cs index 732818970..d8baef852 100644 --- a/src/MPTTrie/Cryptography/MPTTrie/Cache.cs +++ b/src/MPTTrie/Cryptography/MPTTrie/Cache.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Cryptography.MPT 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 +// Cache.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/MPTTrie/Cryptography/MPTTrie/Helper.cs b/src/MPTTrie/Cryptography/MPTTrie/Helper.cs index fb9406d32..5c93afd65 100644 --- a/src/MPTTrie/Cryptography/MPTTrie/Helper.cs +++ b/src/MPTTrie/Cryptography/MPTTrie/Helper.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Cryptography.MPT 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 +// Helper.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/MPTTrie/Cryptography/MPTTrie/Node.Branch.cs b/src/MPTTrie/Cryptography/MPTTrie/Node.Branch.cs index e6e9d863e..c8ff04dfc 100644 --- a/src/MPTTrie/Cryptography/MPTTrie/Node.Branch.cs +++ b/src/MPTTrie/Cryptography/MPTTrie/Node.Branch.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Cryptography.MPT 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 +// Node.Branch.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/MPTTrie/Cryptography/MPTTrie/Node.Extension.cs b/src/MPTTrie/Cryptography/MPTTrie/Node.Extension.cs index 78f73aa3b..510db4925 100644 --- a/src/MPTTrie/Cryptography/MPTTrie/Node.Extension.cs +++ b/src/MPTTrie/Cryptography/MPTTrie/Node.Extension.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Cryptography.MPT 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 +// Node.Extension.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/MPTTrie/Cryptography/MPTTrie/Node.Hash.cs b/src/MPTTrie/Cryptography/MPTTrie/Node.Hash.cs index fac66dde3..e0190dd14 100644 --- a/src/MPTTrie/Cryptography/MPTTrie/Node.Hash.cs +++ b/src/MPTTrie/Cryptography/MPTTrie/Node.Hash.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Cryptography.MPT 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 +// Node.Hash.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/MPTTrie/Cryptography/MPTTrie/Node.Leaf.cs b/src/MPTTrie/Cryptography/MPTTrie/Node.Leaf.cs index a48835b29..024a07f8c 100644 --- a/src/MPTTrie/Cryptography/MPTTrie/Node.Leaf.cs +++ b/src/MPTTrie/Cryptography/MPTTrie/Node.Leaf.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Cryptography.MPT 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 +// Node.Leaf.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/MPTTrie/Cryptography/MPTTrie/Node.cs b/src/MPTTrie/Cryptography/MPTTrie/Node.cs index 8ac4c1dfc..1795ec7f0 100644 --- a/src/MPTTrie/Cryptography/MPTTrie/Node.cs +++ b/src/MPTTrie/Cryptography/MPTTrie/Node.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Cryptography.MPT 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 +// Node.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/MPTTrie/Cryptography/MPTTrie/NodeType.cs b/src/MPTTrie/Cryptography/MPTTrie/NodeType.cs index ba3948430..9c676ff2f 100644 --- a/src/MPTTrie/Cryptography/MPTTrie/NodeType.cs +++ b/src/MPTTrie/Cryptography/MPTTrie/NodeType.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Cryptography.MPT 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 +// NodeType.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/MPTTrie/Cryptography/MPTTrie/Trie.Delete.cs b/src/MPTTrie/Cryptography/MPTTrie/Trie.Delete.cs index ba364bbf5..2041100a1 100644 --- a/src/MPTTrie/Cryptography/MPTTrie/Trie.Delete.cs +++ b/src/MPTTrie/Cryptography/MPTTrie/Trie.Delete.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Cryptography.MPT 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 +// Trie.Delete.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/MPTTrie/Cryptography/MPTTrie/Trie.Find.cs b/src/MPTTrie/Cryptography/MPTTrie/Trie.Find.cs index 1d3ad77c4..b3922e8ce 100644 --- a/src/MPTTrie/Cryptography/MPTTrie/Trie.Find.cs +++ b/src/MPTTrie/Cryptography/MPTTrie/Trie.Find.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Cryptography.MPT 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 +// Trie.Find.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/MPTTrie/Cryptography/MPTTrie/Trie.Get.cs b/src/MPTTrie/Cryptography/MPTTrie/Trie.Get.cs index f68fda763..da69407ac 100644 --- a/src/MPTTrie/Cryptography/MPTTrie/Trie.Get.cs +++ b/src/MPTTrie/Cryptography/MPTTrie/Trie.Get.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Cryptography.MPT 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 +// Trie.Get.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/MPTTrie/Cryptography/MPTTrie/Trie.Proof.cs b/src/MPTTrie/Cryptography/MPTTrie/Trie.Proof.cs index 066ab6573..e0925452e 100644 --- a/src/MPTTrie/Cryptography/MPTTrie/Trie.Proof.cs +++ b/src/MPTTrie/Cryptography/MPTTrie/Trie.Proof.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Cryptography.MPT 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 +// Trie.Proof.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/MPTTrie/Cryptography/MPTTrie/Trie.Put.cs b/src/MPTTrie/Cryptography/MPTTrie/Trie.Put.cs index 37076e370..5de6f3fc8 100644 --- a/src/MPTTrie/Cryptography/MPTTrie/Trie.Put.cs +++ b/src/MPTTrie/Cryptography/MPTTrie/Trie.Put.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Cryptography.MPT 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 +// Trie.Put.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/MPTTrie/Cryptography/MPTTrie/Trie.cs b/src/MPTTrie/Cryptography/MPTTrie/Trie.cs index 4f33f13d4..36a3528ab 100644 --- a/src/MPTTrie/Cryptography/MPTTrie/Trie.cs +++ b/src/MPTTrie/Cryptography/MPTTrie/Trie.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Cryptography.MPT 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 +// Trie.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/MPTTrie/IO/ByteArrayEqualityComparer.cs b/src/MPTTrie/IO/ByteArrayEqualityComparer.cs index 5f3400710..590306d56 100644 --- a/src/MPTTrie/IO/ByteArrayEqualityComparer.cs +++ b/src/MPTTrie/IO/ByteArrayEqualityComparer.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Cryptography.MPT 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 +// ByteArrayEqualityComparer.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/MPTTrie/MPTTrie.csproj b/src/MPTTrie/MPTTrie.csproj index 89d987a31..ed047488f 100644 --- a/src/MPTTrie/MPTTrie.csproj +++ b/src/MPTTrie/MPTTrie.csproj @@ -1,9 +1,9 @@ - - - - Neo.Cryptography.MPT - Neo.Cryptography - true - - - + + + + Neo.Cryptography.MPT + Neo.Cryptography + true + + + diff --git a/src/OracleService/Helper.cs b/src/OracleService/Helper.cs index 608dfa73d..35611e869 100644 --- a/src/OracleService/Helper.cs +++ b/src/OracleService/Helper.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.OracleService 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 +// Helper.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/OracleService/OracleService.cs b/src/OracleService/OracleService.cs index 1fb66ac61..8959b028c 100644 --- a/src/OracleService/OracleService.cs +++ b/src/OracleService/OracleService.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.OracleService 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 +// OracleService.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/OracleService/Protocols/IOracleProtocol.cs b/src/OracleService/Protocols/IOracleProtocol.cs index 27b88694c..3532a6945 100644 --- a/src/OracleService/Protocols/IOracleProtocol.cs +++ b/src/OracleService/Protocols/IOracleProtocol.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.OracleService 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 +// IOracleProtocol.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/OracleService/Protocols/OracleHttpsProtocol.cs b/src/OracleService/Protocols/OracleHttpsProtocol.cs index 485296bf8..29d3eedc4 100644 --- a/src/OracleService/Protocols/OracleHttpsProtocol.cs +++ b/src/OracleService/Protocols/OracleHttpsProtocol.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.OracleService 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 +// OracleHttpsProtocol.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/OracleService/Protocols/OracleNeoFSProtocol.cs b/src/OracleService/Protocols/OracleNeoFSProtocol.cs index 4f5edc275..bd068c855 100644 --- a/src/OracleService/Protocols/OracleNeoFSProtocol.cs +++ b/src/OracleService/Protocols/OracleNeoFSProtocol.cs @@ -1,25 +1,26 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.OracleService 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 +// OracleNeoFSProtocol.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without // modifications are permitted. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using System.Web; using Neo.Cryptography.ECC; using Neo.FileStorage.API.Client; using Neo.FileStorage.API.Cryptography; using Neo.FileStorage.API.Refs; using Neo.Network.P2P.Payloads; using Neo.Wallets; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using System.Web; using Object = Neo.FileStorage.API.Object.Object; using Range = Neo.FileStorage.API.Object.Range; diff --git a/src/OracleService/Settings.cs b/src/OracleService/Settings.cs index 4353f9755..c66010cb5 100644 --- a/src/OracleService/Settings.cs +++ b/src/OracleService/Settings.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.OracleService 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 +// Settings.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RocksDBStore/Plugins/Storage/Options.cs b/src/RocksDBStore/Plugins/Storage/Options.cs index 765e0947b..26dd6c63a 100644 --- a/src/RocksDBStore/Plugins/Storage/Options.cs +++ b/src/RocksDBStore/Plugins/Storage/Options.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.Storage.RocksDBStore 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 +// Options.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RocksDBStore/Plugins/Storage/RocksDBStore.cs b/src/RocksDBStore/Plugins/Storage/RocksDBStore.cs index 2a5e00ef7..079a012f6 100644 --- a/src/RocksDBStore/Plugins/Storage/RocksDBStore.cs +++ b/src/RocksDBStore/Plugins/Storage/RocksDBStore.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.Storage.RocksDBStore 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 +// RocksDBStore.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RocksDBStore/Plugins/Storage/Snapshot.cs b/src/RocksDBStore/Plugins/Storage/Snapshot.cs index 26d487baf..437a5f5d2 100644 --- a/src/RocksDBStore/Plugins/Storage/Snapshot.cs +++ b/src/RocksDBStore/Plugins/Storage/Snapshot.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.Storage.RocksDBStore 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 +// Snapshot.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RocksDBStore/Plugins/Storage/Store.cs b/src/RocksDBStore/Plugins/Storage/Store.cs index 419f63f09..ebf160dab 100644 --- a/src/RocksDBStore/Plugins/Storage/Store.cs +++ b/src/RocksDBStore/Plugins/Storage/Store.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.Storage.RocksDBStore 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 +// Store.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/ContractClient.cs b/src/RpcClient/ContractClient.cs index 18a1820f2..f4ec020ab 100644 --- a/src/RpcClient/ContractClient.cs +++ b/src/RpcClient/ContractClient.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// ContractClient.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcAccount.cs b/src/RpcClient/Models/RpcAccount.cs index c6cf005f9..2afe18b0e 100644 --- a/src/RpcClient/Models/RpcAccount.cs +++ b/src/RpcClient/Models/RpcAccount.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcAccount.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcApplicationLog.cs b/src/RpcClient/Models/RpcApplicationLog.cs index 1ea337491..b641f9df0 100644 --- a/src/RpcClient/Models/RpcApplicationLog.cs +++ b/src/RpcClient/Models/RpcApplicationLog.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcApplicationLog.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcBlock.cs b/src/RpcClient/Models/RpcBlock.cs index 1958bc5fb..46f54a723 100644 --- a/src/RpcClient/Models/RpcBlock.cs +++ b/src/RpcClient/Models/RpcBlock.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcBlock.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcBlockHeader.cs b/src/RpcClient/Models/RpcBlockHeader.cs index 708800482..e30a6a64a 100644 --- a/src/RpcClient/Models/RpcBlockHeader.cs +++ b/src/RpcClient/Models/RpcBlockHeader.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcBlockHeader.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcContractState.cs b/src/RpcClient/Models/RpcContractState.cs index 0d0e5a7f0..b77a2d3a8 100644 --- a/src/RpcClient/Models/RpcContractState.cs +++ b/src/RpcClient/Models/RpcContractState.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcContractState.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcFoundStates.cs b/src/RpcClient/Models/RpcFoundStates.cs index 718661118..a3a1c1f10 100644 --- a/src/RpcClient/Models/RpcFoundStates.cs +++ b/src/RpcClient/Models/RpcFoundStates.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcFoundStates.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcInvokeResult.cs b/src/RpcClient/Models/RpcInvokeResult.cs index f3c7ddeb9..568eb4ca6 100644 --- a/src/RpcClient/Models/RpcInvokeResult.cs +++ b/src/RpcClient/Models/RpcInvokeResult.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcInvokeResult.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcMethodToken.cs b/src/RpcClient/Models/RpcMethodToken.cs index 1b7fe6546..f426950de 100644 --- a/src/RpcClient/Models/RpcMethodToken.cs +++ b/src/RpcClient/Models/RpcMethodToken.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcMethodToken.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcNativeContract.cs b/src/RpcClient/Models/RpcNativeContract.cs index 5c85efa7c..c28251f9c 100644 --- a/src/RpcClient/Models/RpcNativeContract.cs +++ b/src/RpcClient/Models/RpcNativeContract.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcNativeContract.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without @@ -11,7 +12,6 @@ using Neo.Json; using Neo.SmartContract; using Neo.SmartContract.Manifest; -using System.Linq; namespace Neo.Network.RPC.Models { diff --git a/src/RpcClient/Models/RpcNefFile.cs b/src/RpcClient/Models/RpcNefFile.cs index 4be45e5ac..4b33f2b6a 100644 --- a/src/RpcClient/Models/RpcNefFile.cs +++ b/src/RpcClient/Models/RpcNefFile.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcNefFile.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcNep17Balances.cs b/src/RpcClient/Models/RpcNep17Balances.cs index a90ccb091..f7f8b00db 100644 --- a/src/RpcClient/Models/RpcNep17Balances.cs +++ b/src/RpcClient/Models/RpcNep17Balances.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcNep17Balances.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcNep17TokenInfo.cs b/src/RpcClient/Models/RpcNep17TokenInfo.cs index 10b5242bd..a7cb6d0ef 100644 --- a/src/RpcClient/Models/RpcNep17TokenInfo.cs +++ b/src/RpcClient/Models/RpcNep17TokenInfo.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcNep17TokenInfo.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcNep17Transfers.cs b/src/RpcClient/Models/RpcNep17Transfers.cs index 2aca0dd24..3a3226b9a 100644 --- a/src/RpcClient/Models/RpcNep17Transfers.cs +++ b/src/RpcClient/Models/RpcNep17Transfers.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcNep17Transfers.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcPeers.cs b/src/RpcClient/Models/RpcPeers.cs index 38b32b0b1..6659ffe0d 100644 --- a/src/RpcClient/Models/RpcPeers.cs +++ b/src/RpcClient/Models/RpcPeers.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcPeers.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcPlugin.cs b/src/RpcClient/Models/RpcPlugin.cs index 3d8c3d504..12a8669de 100644 --- a/src/RpcClient/Models/RpcPlugin.cs +++ b/src/RpcClient/Models/RpcPlugin.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcPlugin.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcRawMemPool.cs b/src/RpcClient/Models/RpcRawMemPool.cs index 31372c323..4474e0b6b 100644 --- a/src/RpcClient/Models/RpcRawMemPool.cs +++ b/src/RpcClient/Models/RpcRawMemPool.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcRawMemPool.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcRequest.cs b/src/RpcClient/Models/RpcRequest.cs index f64360df7..1c4b67415 100644 --- a/src/RpcClient/Models/RpcRequest.cs +++ b/src/RpcClient/Models/RpcRequest.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcRequest.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcResponse.cs b/src/RpcClient/Models/RpcResponse.cs index a649561c2..25e3212fc 100644 --- a/src/RpcClient/Models/RpcResponse.cs +++ b/src/RpcClient/Models/RpcResponse.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcResponse.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcStateRoot.cs b/src/RpcClient/Models/RpcStateRoot.cs index cbf1009fc..095b054a3 100644 --- a/src/RpcClient/Models/RpcStateRoot.cs +++ b/src/RpcClient/Models/RpcStateRoot.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcStateRoot.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcTransaction.cs b/src/RpcClient/Models/RpcTransaction.cs index d3ff92387..cb674316d 100644 --- a/src/RpcClient/Models/RpcTransaction.cs +++ b/src/RpcClient/Models/RpcTransaction.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcTransaction.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcTransferOut.cs b/src/RpcClient/Models/RpcTransferOut.cs index 6ce653d82..d5e82a846 100644 --- a/src/RpcClient/Models/RpcTransferOut.cs +++ b/src/RpcClient/Models/RpcTransferOut.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcTransferOut.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcUnclaimedGas.cs b/src/RpcClient/Models/RpcUnclaimedGas.cs index 1a0f38e3a..c25f527d3 100644 --- a/src/RpcClient/Models/RpcUnclaimedGas.cs +++ b/src/RpcClient/Models/RpcUnclaimedGas.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcUnclaimedGas.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcValidateAddressResult.cs b/src/RpcClient/Models/RpcValidateAddressResult.cs index 2de69d388..6f49e08f0 100644 --- a/src/RpcClient/Models/RpcValidateAddressResult.cs +++ b/src/RpcClient/Models/RpcValidateAddressResult.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcValidateAddressResult.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcValidator.cs b/src/RpcClient/Models/RpcValidator.cs index c5cbef8ef..27031631e 100644 --- a/src/RpcClient/Models/RpcValidator.cs +++ b/src/RpcClient/Models/RpcValidator.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcValidator.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Models/RpcVersion.cs b/src/RpcClient/Models/RpcVersion.cs index 0da7774ed..430d659f7 100644 --- a/src/RpcClient/Models/RpcVersion.cs +++ b/src/RpcClient/Models/RpcVersion.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcVersion.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Nep17API.cs b/src/RpcClient/Nep17API.cs index f0aa19dfd..518f47092 100644 --- a/src/RpcClient/Nep17API.cs +++ b/src/RpcClient/Nep17API.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// Nep17API.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/PolicyAPI.cs b/src/RpcClient/PolicyAPI.cs index ceab5382a..60e749a79 100644 --- a/src/RpcClient/PolicyAPI.cs +++ b/src/RpcClient/PolicyAPI.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// PolicyAPI.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Properties/AssemblyInfo.cs b/src/RpcClient/Properties/AssemblyInfo.cs index 28d86664a..d464f67da 100644 --- a/src/RpcClient/Properties/AssemblyInfo.cs +++ b/src/RpcClient/Properties/AssemblyInfo.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// AssemblyInfo.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/RpcClient.cs b/src/RpcClient/RpcClient.cs index 6291ce044..8cd8a717a 100644 --- a/src/RpcClient/RpcClient.cs +++ b/src/RpcClient/RpcClient.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcClient.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/RpcException.cs b/src/RpcClient/RpcException.cs index 6554899dc..d0f2e5e64 100644 --- a/src/RpcClient/RpcException.cs +++ b/src/RpcClient/RpcException.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcException.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/StateAPI.cs b/src/RpcClient/StateAPI.cs index 5ee1683d0..6a926fe02 100644 --- a/src/RpcClient/StateAPI.cs +++ b/src/RpcClient/StateAPI.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// StateAPI.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without @@ -53,7 +54,7 @@ public async Task VerifyProofAsync(UInt256 rootHash, byte[] proofBytes) return (localRootIndex, validatedRootIndex); } - static uint? ToNullableUint(JToken json) => (json == null) ? (uint?)null : (uint?)json.AsNumber(); + static uint? ToNullableUint(JToken json) => (json == null) ? null : (uint?)json.AsNumber(); public static JToken[] MakeFindStatesParams(UInt256 rootHash, UInt160 scriptHash, ReadOnlySpan prefix, ReadOnlySpan from = default, int? count = null) { diff --git a/src/RpcClient/TransactionManager.cs b/src/RpcClient/TransactionManager.cs index 82694fd2d..08e9f31e3 100644 --- a/src/RpcClient/TransactionManager.cs +++ b/src/RpcClient/TransactionManager.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// TransactionManager.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/TransactionManagerFactory.cs b/src/RpcClient/TransactionManagerFactory.cs index 8fea000ff..3fe9e3ded 100644 --- a/src/RpcClient/TransactionManagerFactory.cs +++ b/src/RpcClient/TransactionManagerFactory.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// TransactionManagerFactory.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/Utility.cs b/src/RpcClient/Utility.cs index 24b7b8551..659942f8f 100644 --- a/src/RpcClient/Utility.cs +++ b/src/RpcClient/Utility.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// Utility.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcClient/WalletAPI.cs b/src/RpcClient/WalletAPI.cs index 8cac51763..bbf684f75 100644 --- a/src/RpcClient/WalletAPI.cs +++ b/src/RpcClient/WalletAPI.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// WalletAPI.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcServer/Diagnostic.cs b/src/RpcServer/Diagnostic.cs index 6115d6c67..a8cba4af9 100644 --- a/src/RpcServer/Diagnostic.cs +++ b/src/RpcServer/Diagnostic.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// Diagnostic.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcServer/RpcException.cs b/src/RpcServer/RpcException.cs index 2c2f929e3..827dc6210 100644 --- a/src/RpcServer/RpcException.cs +++ b/src/RpcServer/RpcException.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcException.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcServer/RpcMethodAttribute.cs b/src/RpcServer/RpcMethodAttribute.cs index 1578f53d4..89edccdd5 100644 --- a/src/RpcServer/RpcMethodAttribute.cs +++ b/src/RpcServer/RpcMethodAttribute.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcMethodAttribute.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcServer/RpcServer.Blockchain.cs b/src/RpcServer/RpcServer.Blockchain.cs index 5fc81fb5f..be60508e6 100644 --- a/src/RpcServer/RpcServer.Blockchain.cs +++ b/src/RpcServer/RpcServer.Blockchain.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcServer.Blockchain.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcServer/RpcServer.Node.cs b/src/RpcServer/RpcServer.Node.cs index 2b0c6f1d2..b28820f2f 100644 --- a/src/RpcServer/RpcServer.Node.cs +++ b/src/RpcServer/RpcServer.Node.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcServer.Node.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcServer/RpcServer.SmartContract.cs b/src/RpcServer/RpcServer.SmartContract.cs index eb5af98f4..e09268581 100644 --- a/src/RpcServer/RpcServer.SmartContract.cs +++ b/src/RpcServer/RpcServer.SmartContract.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcServer.SmartContract.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcServer/RpcServer.Utilities.cs b/src/RpcServer/RpcServer.Utilities.cs index 39d9282ca..28da86829 100644 --- a/src/RpcServer/RpcServer.Utilities.cs +++ b/src/RpcServer/RpcServer.Utilities.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcServer.Utilities.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcServer/RpcServer.Wallet.cs b/src/RpcServer/RpcServer.Wallet.cs index 097dafcd3..288533cb4 100644 --- a/src/RpcServer/RpcServer.Wallet.cs +++ b/src/RpcServer/RpcServer.Wallet.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcServer.Wallet.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcServer/RpcServer.cs b/src/RpcServer/RpcServer.cs index c724ae441..8023622f5 100644 --- a/src/RpcServer/RpcServer.cs +++ b/src/RpcServer/RpcServer.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcServer.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcServer/RpcServerPlugin.cs b/src/RpcServer/RpcServerPlugin.cs index 92db90d8b..bc51d6394 100644 --- a/src/RpcServer/RpcServerPlugin.cs +++ b/src/RpcServer/RpcServerPlugin.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// RpcServerPlugin.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcServer/Session.cs b/src/RpcServer/Session.cs index 564ba6530..2b4213c28 100644 --- a/src/RpcServer/Session.cs +++ b/src/RpcServer/Session.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// Session.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcServer/Settings.cs b/src/RpcServer/Settings.cs index b5504df1a..f4aef116c 100644 --- a/src/RpcServer/Settings.cs +++ b/src/RpcServer/Settings.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// Settings.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcServer/Tree.cs b/src/RpcServer/Tree.cs index a4de74127..77ca1fc2a 100644 --- a/src/RpcServer/Tree.cs +++ b/src/RpcServer/Tree.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// Tree.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcServer/TreeNode.cs b/src/RpcServer/TreeNode.cs index 05407a25b..82785277b 100644 --- a/src/RpcServer/TreeNode.cs +++ b/src/RpcServer/TreeNode.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// TreeNode.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/RpcServer/Utility.cs b/src/RpcServer/Utility.cs index e92a4a53f..ccbae34db 100644 --- a/src/RpcServer/Utility.cs +++ b/src/RpcServer/Utility.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Network.RPC 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 +// Utility.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/SQLiteWallet/Account.cs b/src/SQLiteWallet/Account.cs index 2eba9008d..e7ae09af9 100644 --- a/src/SQLiteWallet/Account.cs +++ b/src/SQLiteWallet/Account.cs @@ -1,10 +1,11 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Wallets.SQLite 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 +// Copyright (C) 2015-2024 The Neo Project. +// +// Account.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. -// +// // Redistribution and use in source and binary forms with or without // modifications are permitted. diff --git a/src/SQLiteWallet/Address.cs b/src/SQLiteWallet/Address.cs index ca43b244a..6f2b73e42 100644 --- a/src/SQLiteWallet/Address.cs +++ b/src/SQLiteWallet/Address.cs @@ -1,10 +1,11 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Wallets.SQLite 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 +// Copyright (C) 2015-2024 The Neo Project. +// +// Address.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. -// +// // Redistribution and use in source and binary forms with or without // modifications are permitted. diff --git a/src/SQLiteWallet/Contract.cs b/src/SQLiteWallet/Contract.cs index 827be9349..2da432a63 100644 --- a/src/SQLiteWallet/Contract.cs +++ b/src/SQLiteWallet/Contract.cs @@ -1,10 +1,11 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Wallets.SQLite 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 +// Copyright (C) 2015-2024 The Neo Project. +// +// Contract.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. -// +// // Redistribution and use in source and binary forms with or without // modifications are permitted. diff --git a/src/SQLiteWallet/Key.cs b/src/SQLiteWallet/Key.cs index 24107a3c8..81a8a6daf 100644 --- a/src/SQLiteWallet/Key.cs +++ b/src/SQLiteWallet/Key.cs @@ -1,10 +1,11 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Wallets.SQLite 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 +// Copyright (C) 2015-2024 The Neo Project. +// +// Key.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. -// +// // Redistribution and use in source and binary forms with or without // modifications are permitted. diff --git a/src/SQLiteWallet/SQLiteWallet.cs b/src/SQLiteWallet/SQLiteWallet.cs index 7c1edd1bc..1a99c1672 100644 --- a/src/SQLiteWallet/SQLiteWallet.cs +++ b/src/SQLiteWallet/SQLiteWallet.cs @@ -1,10 +1,11 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Wallets.SQLite 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 +// Copyright (C) 2015-2024 The Neo Project. +// +// SQLiteWallet.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. -// +// // Redistribution and use in source and binary forms with or without // modifications are permitted. diff --git a/src/SQLiteWallet/SQLiteWallet.csproj b/src/SQLiteWallet/SQLiteWallet.csproj index e1d77a3f1..f48e3f403 100644 --- a/src/SQLiteWallet/SQLiteWallet.csproj +++ b/src/SQLiteWallet/SQLiteWallet.csproj @@ -1,13 +1,13 @@ - - - - Neo.Wallets.SQLite - Neo.Wallets.SQLite - enable - - - - - - - + + + + Neo.Wallets.SQLite + Neo.Wallets.SQLite + enable + + + + + + + diff --git a/src/SQLiteWallet/SQLiteWalletAccount.cs b/src/SQLiteWallet/SQLiteWalletAccount.cs index 7c96ce1c3..88526f7e5 100644 --- a/src/SQLiteWallet/SQLiteWalletAccount.cs +++ b/src/SQLiteWallet/SQLiteWalletAccount.cs @@ -1,10 +1,11 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Wallets.SQLite 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 +// Copyright (C) 2015-2024 The Neo Project. +// +// SQLiteWalletAccount.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. -// +// // Redistribution and use in source and binary forms with or without // modifications are permitted. diff --git a/src/SQLiteWallet/SQLiteWalletFactory.cs b/src/SQLiteWallet/SQLiteWalletFactory.cs index 54a506a9a..d952fd0fc 100644 --- a/src/SQLiteWallet/SQLiteWalletFactory.cs +++ b/src/SQLiteWallet/SQLiteWalletFactory.cs @@ -1,10 +1,11 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Wallets.SQLite 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 +// Copyright (C) 2015-2024 The Neo Project. +// +// SQLiteWalletFactory.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. -// +// // Redistribution and use in source and binary forms with or without // modifications are permitted. diff --git a/src/SQLiteWallet/VerificationContract.cs b/src/SQLiteWallet/VerificationContract.cs index 60712225f..e128045ad 100644 --- a/src/SQLiteWallet/VerificationContract.cs +++ b/src/SQLiteWallet/VerificationContract.cs @@ -1,10 +1,11 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Wallets.SQLite 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 +// Copyright (C) 2015-2024 The Neo Project. +// +// VerificationContract.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. -// +// // Redistribution and use in source and binary forms with or without // modifications are permitted. diff --git a/src/SQLiteWallet/WalletDataContext.cs b/src/SQLiteWallet/WalletDataContext.cs index 10a3c4434..79ca538cd 100644 --- a/src/SQLiteWallet/WalletDataContext.cs +++ b/src/SQLiteWallet/WalletDataContext.cs @@ -1,10 +1,11 @@ -// Copyright (C) 2015-2023 The Neo Project. -// -// The Neo.Wallets.SQLite 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 +// Copyright (C) 2015-2024 The Neo Project. +// +// WalletDataContext.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. -// +// // Redistribution and use in source and binary forms with or without // modifications are permitted. diff --git a/src/StateService/Network/MessageType.cs b/src/StateService/Network/MessageType.cs index 4cda8e35e..88ed5b2e9 100644 --- a/src/StateService/Network/MessageType.cs +++ b/src/StateService/Network/MessageType.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.StateService 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 +// MessageType.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/StateService/Network/StateRoot.cs b/src/StateService/Network/StateRoot.cs index 4a2b2cd65..5b4e8610f 100644 --- a/src/StateService/Network/StateRoot.cs +++ b/src/StateService/Network/StateRoot.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.StateService 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 +// StateRoot.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/StateService/Network/Vote.cs b/src/StateService/Network/Vote.cs index 2950a8cf9..e6840c7a9 100644 --- a/src/StateService/Network/Vote.cs +++ b/src/StateService/Network/Vote.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.StateService 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 +// Vote.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/StateService/Settings.cs b/src/StateService/Settings.cs index c48e6d1f8..8557866bc 100644 --- a/src/StateService/Settings.cs +++ b/src/StateService/Settings.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.StateService 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 +// Settings.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/StateService/StatePlugin.cs b/src/StateService/StatePlugin.cs index e71b69b67..b760eed79 100644 --- a/src/StateService/StatePlugin.cs +++ b/src/StateService/StatePlugin.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.StateService 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 +// StatePlugin.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/StateService/Storage/Keys.cs b/src/StateService/Storage/Keys.cs index e7a0a66a1..4ffecef48 100644 --- a/src/StateService/Storage/Keys.cs +++ b/src/StateService/Storage/Keys.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.StateService 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 +// Keys.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/StateService/Storage/StateSnapshot.cs b/src/StateService/Storage/StateSnapshot.cs index 8c4dcffb7..70ec00622 100644 --- a/src/StateService/Storage/StateSnapshot.cs +++ b/src/StateService/Storage/StateSnapshot.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.StateService 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 +// StateSnapshot.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/StateService/Storage/StateStore.cs b/src/StateService/Storage/StateStore.cs index 9a54dabd6..e0bc4ed78 100644 --- a/src/StateService/Storage/StateStore.cs +++ b/src/StateService/Storage/StateStore.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.StateService 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 +// StateStore.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/StateService/Verification/VerificationContext.cs b/src/StateService/Verification/VerificationContext.cs index f5b08946d..53743c134 100644 --- a/src/StateService/Verification/VerificationContext.cs +++ b/src/StateService/Verification/VerificationContext.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.StateService 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 +// VerificationContext.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/StateService/Verification/VerificationService.cs b/src/StateService/Verification/VerificationService.cs index 646607883..c6730e790 100644 --- a/src/StateService/Verification/VerificationService.cs +++ b/src/StateService/Verification/VerificationService.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.StateService 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 +// VerificationService.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/StatesDumper/PersistActions.cs b/src/StatesDumper/PersistActions.cs index 360f42cde..9c1aa2210 100644 --- a/src/StatesDumper/PersistActions.cs +++ b/src/StatesDumper/PersistActions.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.StatesDumper 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 +// PersistActions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/StatesDumper/Settings.cs b/src/StatesDumper/Settings.cs index ad1fcfee0..ffe472674 100644 --- a/src/StatesDumper/Settings.cs +++ b/src/StatesDumper/Settings.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.StatesDumper 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 +// Settings.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/StatesDumper/StatesDumper.cs b/src/StatesDumper/StatesDumper.cs index a9f9f9fc4..a74bda155 100644 --- a/src/StatesDumper/StatesDumper.cs +++ b/src/StatesDumper/StatesDumper.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.StatesDumper 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 +// StatesDumper.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/StorageDumper/Settings.cs b/src/StorageDumper/Settings.cs index 841b2a3c4..eccb04f66 100644 --- a/src/StorageDumper/Settings.cs +++ b/src/StorageDumper/Settings.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.StatesDumper 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 +// Settings.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without @@ -10,8 +11,6 @@ using Microsoft.Extensions.Configuration; using Neo.SmartContract.Native; -using System.Collections.Generic; -using System.Linq; namespace Neo.Plugins { @@ -28,7 +27,7 @@ internal class Settings public IReadOnlyList Exclude { get; } - public static Settings Default { get; private set; } + public static Settings? Default { get; private set; } private Settings(IConfigurationSection section) { diff --git a/src/StorageDumper/StorageDumper.cs b/src/StorageDumper/StorageDumper.cs index 4eb3b434f..9f377b8ef 100644 --- a/src/StorageDumper/StorageDumper.cs +++ b/src/StorageDumper/StorageDumper.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.StatesDumper 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 +// StorageDumper.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without @@ -15,10 +16,6 @@ using Neo.Network.P2P.Payloads; using Neo.Persistence; using Neo.SmartContract.Native; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; namespace Neo.Plugins { @@ -59,11 +56,11 @@ protected override void OnSystemLoaded(NeoSystem system) /// Process "dump contract-storage" command /// [ConsoleCommand("dump contract-storage", Category = "Storage", Description = "You can specify the contract script hash or use null to get the corresponding information from the storage")] - private void OnDumpStorage(uint network, UInt160 contractHash = null) + private void OnDumpStorage(uint network, UInt160? contractHash = null) { if (!systems.ContainsKey(network)) throw new InvalidOperationException("invalid network"); string path = $"dump_{network}.json"; - byte[] prefix = null; + byte[]? prefix = null; if (contractHash is not null) { var contract = NativeContract.ContractManagement.GetContract(systems[network].StoreView, contractHash); diff --git a/src/TokensTracker/Extensions.cs b/src/TokensTracker/Extensions.cs index 3b8fe6f50..780505628 100644 --- a/src/TokensTracker/Extensions.cs +++ b/src/TokensTracker/Extensions.cs @@ -1,19 +1,20 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.TokensTracker 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 +// Extensions.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without // modifications are permitted. -using System; -using System.Collections.Generic; -using System.Numerics; using Neo.IO; using Neo.Persistence; using Neo.VM.Types; +using System; +using System.Collections.Generic; +using System.Numerics; namespace Neo.Plugins { diff --git a/src/TokensTracker/TokensTracker.cs b/src/TokensTracker/TokensTracker.cs index 3960aeb95..5567d7d1f 100644 --- a/src/TokensTracker/TokensTracker.cs +++ b/src/TokensTracker/TokensTracker.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.TokensTracker 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 +// TokensTracker.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/TokensTracker/Trackers/NEP-11/Nep11BalanceKey.cs b/src/TokensTracker/Trackers/NEP-11/Nep11BalanceKey.cs index 8f9763165..1f375f33d 100644 --- a/src/TokensTracker/Trackers/NEP-11/Nep11BalanceKey.cs +++ b/src/TokensTracker/Trackers/NEP-11/Nep11BalanceKey.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.TokensTracker 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 +// Nep11BalanceKey.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/TokensTracker/Trackers/NEP-11/Nep11Tracker.cs b/src/TokensTracker/Trackers/NEP-11/Nep11Tracker.cs index b7c785c6a..bc80d77aa 100644 --- a/src/TokensTracker/Trackers/NEP-11/Nep11Tracker.cs +++ b/src/TokensTracker/Trackers/NEP-11/Nep11Tracker.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.TokensTracker 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 +// Nep11Tracker.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/TokensTracker/Trackers/NEP-11/Nep11TransferKey.cs b/src/TokensTracker/Trackers/NEP-11/Nep11TransferKey.cs index 07e5d0032..5c999e8e0 100644 --- a/src/TokensTracker/Trackers/NEP-11/Nep11TransferKey.cs +++ b/src/TokensTracker/Trackers/NEP-11/Nep11TransferKey.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.TokensTracker 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 +// Nep11TransferKey.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/TokensTracker/Trackers/NEP-17/Nep17BalanceKey.cs b/src/TokensTracker/Trackers/NEP-17/Nep17BalanceKey.cs index 1501c0f79..bbceabec2 100644 --- a/src/TokensTracker/Trackers/NEP-17/Nep17BalanceKey.cs +++ b/src/TokensTracker/Trackers/NEP-17/Nep17BalanceKey.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.TokensTracker 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 +// Nep17BalanceKey.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/TokensTracker/Trackers/NEP-17/Nep17Tracker.cs b/src/TokensTracker/Trackers/NEP-17/Nep17Tracker.cs index 38a613149..989bc6a41 100644 --- a/src/TokensTracker/Trackers/NEP-17/Nep17Tracker.cs +++ b/src/TokensTracker/Trackers/NEP-17/Nep17Tracker.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.TokensTracker 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 +// Nep17Tracker.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/TokensTracker/Trackers/NEP-17/Nep17TransferKey.cs b/src/TokensTracker/Trackers/NEP-17/Nep17TransferKey.cs index 89e616e3c..8f48195fc 100644 --- a/src/TokensTracker/Trackers/NEP-17/Nep17TransferKey.cs +++ b/src/TokensTracker/Trackers/NEP-17/Nep17TransferKey.cs @@ -1,15 +1,16 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.TokensTracker 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 +// Nep17TransferKey.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without // modifications are permitted. -using System; using Neo.IO; +using System; namespace Neo.Plugins.Trackers.NEP_17 { diff --git a/src/TokensTracker/Trackers/TokenBalance.cs b/src/TokensTracker/Trackers/TokenBalance.cs index 8e19b7d13..f54a7c985 100644 --- a/src/TokensTracker/Trackers/TokenBalance.cs +++ b/src/TokensTracker/Trackers/TokenBalance.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.TokensTracker 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 +// TokenBalance.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/TokensTracker/Trackers/TokenTransfer.cs b/src/TokensTracker/Trackers/TokenTransfer.cs index e79403a82..0a221850f 100644 --- a/src/TokensTracker/Trackers/TokenTransfer.cs +++ b/src/TokensTracker/Trackers/TokenTransfer.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.TokensTracker 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 +// TokenTransfer.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/TokensTracker/Trackers/TokenTransferKey.cs b/src/TokensTracker/Trackers/TokenTransferKey.cs index 3aed7197a..252eb20af 100644 --- a/src/TokensTracker/Trackers/TokenTransferKey.cs +++ b/src/TokensTracker/Trackers/TokenTransferKey.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.TokensTracker 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 +// TokenTransferKey.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/src/TokensTracker/Trackers/TrackerBase.cs b/src/TokensTracker/Trackers/TrackerBase.cs index a4d03c93a..471362b01 100644 --- a/src/TokensTracker/Trackers/TrackerBase.cs +++ b/src/TokensTracker/Trackers/TrackerBase.cs @@ -1,8 +1,9 @@ -// Copyright (C) 2015-2023 The Neo Project. +// Copyright (C) 2015-2024 The Neo Project. // -// The Neo.Plugins.TokensTracker 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 +// TrackerBase.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php // for more details. // // Redistribution and use in source and binary forms with or without diff --git a/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/Helper.cs b/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/Helper.cs index 7f87051e1..15f796046 100644 --- a/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/Helper.cs +++ b/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/Helper.cs @@ -1,3 +1,14 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// Helper.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + using System.IO; namespace Neo.Cryptography.MPTTrie.Tests diff --git a/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/UT_Cache.cs b/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/UT_Cache.cs index 2ed2d5d86..3a3496205 100644 --- a/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/UT_Cache.cs +++ b/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/UT_Cache.cs @@ -1,3 +1,14 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UT_Cache.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.IO; using Neo.Persistence; diff --git a/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/UT_Helper.cs b/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/UT_Helper.cs index 77ee3b08e..980e7a429 100644 --- a/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/UT_Helper.cs +++ b/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/UT_Helper.cs @@ -1,3 +1,14 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UT_Helper.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + using Microsoft.VisualStudio.TestTools.UnitTesting; using System; diff --git a/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/UT_Node.cs b/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/UT_Node.cs index 1aedc2051..8f46fbec2 100644 --- a/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/UT_Node.cs +++ b/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/UT_Node.cs @@ -1,3 +1,14 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UT_Node.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.IO; using System; diff --git a/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/UT_Trie.cs b/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/UT_Trie.cs index bc0a821fc..372de6a73 100644 --- a/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/UT_Trie.cs +++ b/tests/Neo.Cryptography.MPTTrie.Tests/Cryptography/MPTTrie/UT_Trie.cs @@ -1,3 +1,14 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UT_Trie.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.IO; using Neo.Persistence; diff --git a/tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj b/tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj index 0887cd319..5b290d034 100644 --- a/tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj +++ b/tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj @@ -1,21 +1,21 @@ - - - Neo.Network.RPC.Tests - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - PreserveNewest - - - + + + Neo.Network.RPC.Tests + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + PreserveNewest + + + diff --git a/tests/Neo.Network.RPC.Tests/TestUtils.cs b/tests/Neo.Network.RPC.Tests/TestUtils.cs index 74380f613..068de3388 100644 --- a/tests/Neo.Network.RPC.Tests/TestUtils.cs +++ b/tests/Neo.Network.RPC.Tests/TestUtils.cs @@ -1,3 +1,14 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// TestUtils.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + using Neo.Json; using Neo.Network.P2P.Payloads; using Neo.Network.RPC.Models; diff --git a/tests/Neo.Network.RPC.Tests/UT_ContractClient.cs b/tests/Neo.Network.RPC.Tests/UT_ContractClient.cs index b46289f8a..c3cf226a3 100644 --- a/tests/Neo.Network.RPC.Tests/UT_ContractClient.cs +++ b/tests/Neo.Network.RPC.Tests/UT_ContractClient.cs @@ -1,3 +1,14 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UT_ContractClient.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Neo.SmartContract; diff --git a/tests/Neo.Network.RPC.Tests/UT_Nep17API.cs b/tests/Neo.Network.RPC.Tests/UT_Nep17API.cs index 315f573e7..3bfb4e87f 100644 --- a/tests/Neo.Network.RPC.Tests/UT_Nep17API.cs +++ b/tests/Neo.Network.RPC.Tests/UT_Nep17API.cs @@ -1,3 +1,14 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UT_Nep17API.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Neo.Json; @@ -104,13 +115,13 @@ public async Task TestGetTokenInfo() { var result = await nep17API.GetTokenInfoAsync(NativeContract.GAS.Name.ToLower()); Assert.AreEqual(NativeContract.GAS.Symbol, result.Symbol); - Assert.AreEqual(8, (int)result.Decimals); + Assert.AreEqual(8, result.Decimals); Assert.AreEqual(1_00000000, (int)result.TotalSupply); Assert.AreEqual("GasToken", result.Name); result = await nep17API.GetTokenInfoAsync(NativeContract.GAS.Hash); Assert.AreEqual(NativeContract.GAS.Symbol, result.Symbol); - Assert.AreEqual(8, (int)result.Decimals); + Assert.AreEqual(8, result.Decimals); Assert.AreEqual(1_00000000, (int)result.TotalSupply); Assert.AreEqual("GasToken", result.Name); haveGasTokenUT = true; @@ -119,13 +130,13 @@ public async Task TestGetTokenInfo() { var result = await nep17API.GetTokenInfoAsync(NativeContract.NEO.Name.ToLower()); Assert.AreEqual(NativeContract.NEO.Symbol, result.Symbol); - Assert.AreEqual(0, (int)result.Decimals); + Assert.AreEqual(0, result.Decimals); Assert.AreEqual(1_00000000, (int)result.TotalSupply); Assert.AreEqual("NeoToken", result.Name); result = await nep17API.GetTokenInfoAsync(NativeContract.NEO.Hash); Assert.AreEqual(NativeContract.NEO.Symbol, result.Symbol); - Assert.AreEqual(0, (int)result.Decimals); + Assert.AreEqual(0, result.Decimals); Assert.AreEqual(1_00000000, (int)result.TotalSupply); Assert.AreEqual("NeoToken", result.Name); haveNeoTokenUT = true; diff --git a/tests/Neo.Network.RPC.Tests/UT_PolicyAPI.cs b/tests/Neo.Network.RPC.Tests/UT_PolicyAPI.cs index 610a25313..7defa163a 100644 --- a/tests/Neo.Network.RPC.Tests/UT_PolicyAPI.cs +++ b/tests/Neo.Network.RPC.Tests/UT_PolicyAPI.cs @@ -1,3 +1,14 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UT_PolicyAPI.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Neo.SmartContract; diff --git a/tests/Neo.Network.RPC.Tests/UT_RpcClient.cs b/tests/Neo.Network.RPC.Tests/UT_RpcClient.cs index 52191b34f..4af0f557e 100644 --- a/tests/Neo.Network.RPC.Tests/UT_RpcClient.cs +++ b/tests/Neo.Network.RPC.Tests/UT_RpcClient.cs @@ -1,3 +1,14 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UT_RpcClient.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; diff --git a/tests/Neo.Network.RPC.Tests/UT_RpcModels.cs b/tests/Neo.Network.RPC.Tests/UT_RpcModels.cs index b31a4e818..43eb7cfe7 100644 --- a/tests/Neo.Network.RPC.Tests/UT_RpcModels.cs +++ b/tests/Neo.Network.RPC.Tests/UT_RpcModels.cs @@ -1,3 +1,14 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UT_RpcModels.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Neo.Json; diff --git a/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs b/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs index 6d6120c25..ae025cf65 100644 --- a/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs +++ b/tests/Neo.Network.RPC.Tests/UT_TransactionManager.cs @@ -1,3 +1,14 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UT_TransactionManager.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Neo.Cryptography; diff --git a/tests/Neo.Network.RPC.Tests/UT_Utility.cs b/tests/Neo.Network.RPC.Tests/UT_Utility.cs index a91b40725..fa410c543 100644 --- a/tests/Neo.Network.RPC.Tests/UT_Utility.cs +++ b/tests/Neo.Network.RPC.Tests/UT_Utility.cs @@ -1,3 +1,14 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UT_Utility.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.SmartContract; using Neo.Wallets; diff --git a/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs b/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs index 14ec43053..10a35fd06 100644 --- a/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs +++ b/tests/Neo.Network.RPC.Tests/UT_WalletAPI.cs @@ -1,3 +1,14 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UT_WalletAPI.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Neo.Cryptography.ECC; diff --git a/tests/Neo.Plugins.OracleService.Tests/TestBlockchain.cs b/tests/Neo.Plugins.OracleService.Tests/TestBlockchain.cs index 4210beba9..fca5ca9d4 100644 --- a/tests/Neo.Plugins.OracleService.Tests/TestBlockchain.cs +++ b/tests/Neo.Plugins.OracleService.Tests/TestBlockchain.cs @@ -1,3 +1,14 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// TestBlockchain.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + using Neo.Persistence; using System; diff --git a/tests/Neo.Plugins.OracleService.Tests/TestUtils.cs b/tests/Neo.Plugins.OracleService.Tests/TestUtils.cs index f6e06a46e..5700b8376 100644 --- a/tests/Neo.Plugins.OracleService.Tests/TestUtils.cs +++ b/tests/Neo.Plugins.OracleService.Tests/TestUtils.cs @@ -1,3 +1,14 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// TestUtils.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + using Neo.IO; using Neo.SmartContract; using Neo.SmartContract.Native; diff --git a/tests/Neo.Plugins.OracleService.Tests/UT_OracleService.cs b/tests/Neo.Plugins.OracleService.Tests/UT_OracleService.cs index 672ded757..08f96c95d 100644 --- a/tests/Neo.Plugins.OracleService.Tests/UT_OracleService.cs +++ b/tests/Neo.Plugins.OracleService.Tests/UT_OracleService.cs @@ -1,3 +1,14 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UT_OracleService.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + using Akka.TestKit.Xunit2; using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.Cryptography.ECC; @@ -64,7 +75,7 @@ public void TestCreateOracleResponseTx() var executionFactor = NativeContract.Policy.GetExecFeeFactor(snapshot); Assert.AreEqual(executionFactor, (uint)30); var feePerByte = NativeContract.Policy.GetFeePerByte(snapshot); - Assert.AreEqual(feePerByte, (uint)1000); + Assert.AreEqual(feePerByte, 1000); OracleRequest request = new OracleRequest { diff --git a/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.cs b/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.cs index a2b3476a9..803980eb8 100644 --- a/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.cs +++ b/tests/Neo.Plugins.RpcServer.Tests/UT_RpcServer.cs @@ -1,3 +1,14 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// UT_RpcServer.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Neo.Plugins.RpcServer.Tests diff --git a/tests/Neo.Plugins.Storage.Tests/StoreTest.cs b/tests/Neo.Plugins.Storage.Tests/StoreTest.cs index 1ce26a13e..2773f92e8 100644 --- a/tests/Neo.Plugins.Storage.Tests/StoreTest.cs +++ b/tests/Neo.Plugins.Storage.Tests/StoreTest.cs @@ -1,3 +1,14 @@ +// Copyright (C) 2015-2024 The Neo Project. +// +// StoreTest.cs file belongs to the neo project and is free +// software distributed under the MIT software license, see the +// accompanying file LICENSE in the main directory of the +// repository or http://www.opensource.org/licenses/mit-license.php +// for more details. +// +// Redistribution and use in source and binary forms with or without +// modifications are permitted. + using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.Persistence; using System.IO; From 6a5c7eba984b62b48168ac465f6d3880e2408a00 Mon Sep 17 00:00:00 2001 From: Shargon Date: Wed, 10 Jan 2024 00:15:47 -0800 Subject: [PATCH 28/30] Ensure max length (#845) Co-authored-by: Jimmy --- src/RpcServer/RpcServer.SmartContract.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/RpcServer/RpcServer.SmartContract.cs b/src/RpcServer/RpcServer.SmartContract.cs index e09268581..6ccf10965 100644 --- a/src/RpcServer/RpcServer.SmartContract.cs +++ b/src/RpcServer/RpcServer.SmartContract.cs @@ -172,6 +172,11 @@ private static JObject ToJson(StackItem item, Session session) private static Signer[] SignersFromJson(JArray _params, ProtocolSettings settings) { + if (_params.Count > Transaction.MaxTransactionAttributes) + { + throw new RpcException(-100, "Max allowed witness exceeded."); + } + var ret = _params.Select(u => new Signer { Account = AddressToScriptHash(u["account"].AsString(), settings.AddressVersion), @@ -190,6 +195,11 @@ private static Signer[] SignersFromJson(JArray _params, ProtocolSettings setting private static Witness[] WitnessesFromJson(JArray _params) { + if (_params.Count > Transaction.MaxTransactionAttributes) + { + throw new RpcException(-100, "Max allowed witness exceeded."); + } + return _params.Select(u => new { Invocation = u["invocation"]?.AsString(), From 9e106a8f31c070d0be614eb5208115d60c010b65 Mon Sep 17 00:00:00 2001 From: Owen Zhang <38493437+superboyiii@users.noreply.github.com> Date: Thu, 11 Jan 2024 18:04:26 +0800 Subject: [PATCH 29/30] fix readme (#869) --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 91e0aa3b4..d8262f759 100644 --- a/README.md +++ b/README.md @@ -59,12 +59,12 @@ You can also use `RocksDBStore` in the NEO system by modifying the default stora ### RpcServer Plugin for hosting a RpcServer on the neo-node, being able to disable specific calls. -### RpcNep17Tracker -Plugin that enables NEP17 tracking using LevelDB. +### TokensTracker +Plugin that enables NEP11 and NEP17 tracking using LevelDB. This module works in conjunction with RpcServer, otherwise, just local storage (on leveldb) would be created. ## C# SDK ### RpcClient The RpcClient Project is an individual SDK that is used to interact with NEO blockchain through NEO RPC methods for development using. The main functions include RPC calling, Transaction making, Contract deployment & calling, and Asset transfering. -It needs a NEO node with the `RpcServer` plugin as a provider. And the provider needs more plugins like `RpcNep17Tracker` and `ApplicationLogs` if you want to call RPC methods supplied by the plugins. +It needs a NEO node with the `RpcServer` plugin as a provider. And the provider needs more plugins like `TokensTracker` and `ApplicationLogs` if you want to call RPC methods supplied by the plugins. From 0ff2b709ba46c79bb42eb575cebec7b2dec7d0ae Mon Sep 17 00:00:00 2001 From: Shargon Date: Thu, 11 Jan 2024 13:06:50 +0300 Subject: [PATCH 30/30] Update nugets (#868) Co-authored-by: Jimmy --- src/RocksDBStore/RocksDBStore.csproj | 2 +- src/SQLiteWallet/SQLiteWallet.csproj | 2 +- tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/RocksDBStore/RocksDBStore.csproj b/src/RocksDBStore/RocksDBStore.csproj index d098bb8d3..718fbd5e2 100644 --- a/src/RocksDBStore/RocksDBStore.csproj +++ b/src/RocksDBStore/RocksDBStore.csproj @@ -6,7 +6,7 @@ - + diff --git a/src/SQLiteWallet/SQLiteWallet.csproj b/src/SQLiteWallet/SQLiteWallet.csproj index f48e3f403..2cac0cbd7 100644 --- a/src/SQLiteWallet/SQLiteWallet.csproj +++ b/src/SQLiteWallet/SQLiteWallet.csproj @@ -7,7 +7,7 @@ - + diff --git a/tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj b/tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj index 5b290d034..73e7a531a 100644 --- a/tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj +++ b/tests/Neo.Network.RPC.Tests/Neo.Network.RPC.Tests.csproj @@ -4,7 +4,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive