From 7025642d3ec72a0f43bf25c695da347ef1754245 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Wed, 16 Sep 2020 12:12:28 -0300 Subject: [PATCH 01/77] Boa-117 Create Testengine executable to test Neo3-boa --- neo-devpack-dotnet.sln | 7 ++ src/TestEngineExe/Program.cs | 111 +++++++++++++++++++++++++ src/TestEngineExe/TestEngineExe.csproj | 12 +++ 3 files changed, 130 insertions(+) create mode 100644 src/TestEngineExe/Program.cs create mode 100644 src/TestEngineExe/TestEngineExe.csproj diff --git a/neo-devpack-dotnet.sln b/neo-devpack-dotnet.sln index d9367d9d2..4f554b6c3 100644 --- a/neo-devpack-dotnet.sln +++ b/neo-devpack-dotnet.sln @@ -26,6 +26,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Template.NEP5.CSharp", "tem EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Template.NEP5.UnitTests", "tests\Template.NEP5.UnitTests\Template.NEP5.UnitTests.csproj", "{780141EE-D6E9-4591-8470-8F91B12027CA}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestEngineExe", "src\TestEngineExe\TestEngineExe.csproj", "{39347E90-FC12-4018-8F22-828F0F1B2F7D}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -68,6 +70,10 @@ Global {780141EE-D6E9-4591-8470-8F91B12027CA}.Debug|Any CPU.Build.0 = Debug|Any CPU {780141EE-D6E9-4591-8470-8F91B12027CA}.Release|Any CPU.ActiveCfg = Release|Any CPU {780141EE-D6E9-4591-8470-8F91B12027CA}.Release|Any CPU.Build.0 = Release|Any CPU + {39347E90-FC12-4018-8F22-828F0F1B2F7D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {39347E90-FC12-4018-8F22-828F0F1B2F7D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {39347E90-FC12-4018-8F22-828F0F1B2F7D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {39347E90-FC12-4018-8F22-828F0F1B2F7D}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -82,6 +88,7 @@ Global {93BEC5CC-BAFF-4389-89E7-84AAFF5D495D} = {D5266066-0AFD-44D5-A83E-2F73668A63C8} {ADD05222-DC45-4FDC-A41A-30A97BACC95F} = {7042EF23-826B-45A1-A905-59AD678C31B7} {780141EE-D6E9-4591-8470-8F91B12027CA} = {D5266066-0AFD-44D5-A83E-2F73668A63C8} + {39347E90-FC12-4018-8F22-828F0F1B2F7D} = {79389FC0-C621-4CEA-AD2B-6074C32E7BCA} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {6DA935E1-C674-4364-B087-F1B511B79215} diff --git a/src/TestEngineExe/Program.cs b/src/TestEngineExe/Program.cs new file mode 100644 index 000000000..4caa2d219 --- /dev/null +++ b/src/TestEngineExe/Program.cs @@ -0,0 +1,111 @@ +using Neo.Compiler; +using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.IO.Json; +using Neo.VM.Types; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace TestEngineExe +{ + class TestEngineExe + { + static void Main(string[] args) + { + Console.WriteLine("Ready!"); + TestEngine testEngine = new TestEngine(); + + if (args.Length < 1) + { + Console.WriteLine("Missing required args: path and methodName."); + return; + //take off then and throw an exception + //is it possible to return value? Not being void + } + string path = args[0]; + if (!File.Exists(path)) + { + Console.WriteLine("File doesn't exists"); + return; + } + if (Path.GetExtension(path).ToLowerInvariant() != ".nef") + { + Console.WriteLine("Incorect file. Nef file required."); + return; + } + + if (args.Length < 2) + { + Console.WriteLine("Missing required args: methodName."); + return; + } + string methodName = args[1]; + var parameters = ConvertParameters(args.Skip(2).ToArray()); + + testEngine.AddEntryScript(path); + + var paramCount = GetMethodParametersCount(methodName, testEngine); + if (paramCount == -1) + { + Console.WriteLine("Method doesn't exist."); + return; + } + if (paramCount != parameters.Length) + { + Console.WriteLine("Incorrect number of parameters."); + return; + } + var result = testEngine.GetMethod(methodName).Run(parameters); + Console.WriteLine("Result: " + result); + } + + /// + /// + /// + /// + /// + /// + /// Returns the number of parameters in the method if the method exists, otherwise it returns -1. + /// + public static int GetMethodParametersCount(string methodname, TestEngine testEngine) + { + if (testEngine.ScriptEntry is null) return -1; + var methods = testEngine.ScriptEntry.finalABI["methods"] as JArray; + foreach (JObject method in methods) + { + if (method["name"].ToString() == methodname) //method exists + return (method["parameters"] as JArray).Count; + } + + return -1; + } + + static StackItem ToStackItem(string arg) + { + if (int.TryParse(arg, out int intParam)) + { + return intParam; + } + else if (bool.TryParse(arg, out bool boolParam)) + { + return boolParam; + } + else + { + return arg; + } + } + + static StackItem[] ConvertParameters(string[] args) + { + List stackParams = new List(); + + foreach (string parameter in args) + { + stackParams.Add(ToStackItem(parameter)); + } + return stackParams.ToArray(); + } + } +} diff --git a/src/TestEngineExe/TestEngineExe.csproj b/src/TestEngineExe/TestEngineExe.csproj new file mode 100644 index 000000000..705065db2 --- /dev/null +++ b/src/TestEngineExe/TestEngineExe.csproj @@ -0,0 +1,12 @@ + + + + Exe + netcoreapp3.1 + + + + + + + From c0b369e269017c4382a37b86f242e7906aef1317 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Wed, 16 Sep 2020 14:25:57 -0300 Subject: [PATCH 02/77] create a testengine executable --- neo-devpack-dotnet.sln | 2 +- src/TestEngineExe/Program.cs | 111 --------------- src/TestEngineExe/TestEngineExe.csproj | 12 -- src/TestingEngine/Engine.cs | 98 +++++++++++++ src/TestingEngine/Helper.cs | 69 +++++++++ src/TestingEngine/Program.cs | 134 ++++++++++++++++++ src/TestingEngine/TestingEngine.csproj | 25 ++++ .../Utils/TestSnapshot.cs | 11 ++ 8 files changed, 338 insertions(+), 124 deletions(-) delete mode 100644 src/TestEngineExe/Program.cs delete mode 100644 src/TestEngineExe/TestEngineExe.csproj create mode 100644 src/TestingEngine/Engine.cs create mode 100644 src/TestingEngine/Helper.cs create mode 100644 src/TestingEngine/Program.cs create mode 100644 src/TestingEngine/TestingEngine.csproj diff --git a/neo-devpack-dotnet.sln b/neo-devpack-dotnet.sln index 4f554b6c3..00de3c454 100644 --- a/neo-devpack-dotnet.sln +++ b/neo-devpack-dotnet.sln @@ -26,7 +26,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Template.NEP5.CSharp", "tem EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Template.NEP5.UnitTests", "tests\Template.NEP5.UnitTests\Template.NEP5.UnitTests.csproj", "{780141EE-D6E9-4591-8470-8F91B12027CA}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestEngineExe", "src\TestEngineExe\TestEngineExe.csproj", "{39347E90-FC12-4018-8F22-828F0F1B2F7D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestingEngine", "src\TestingEngine\TestingEngine.csproj", "{39347E90-FC12-4018-8F22-828F0F1B2F7D}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/src/TestEngineExe/Program.cs b/src/TestEngineExe/Program.cs deleted file mode 100644 index 4caa2d219..000000000 --- a/src/TestEngineExe/Program.cs +++ /dev/null @@ -1,111 +0,0 @@ -using Neo.Compiler; -using Neo.Compiler.MSIL.UnitTests.Utils; -using Neo.IO.Json; -using Neo.VM.Types; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; - -namespace TestEngineExe -{ - class TestEngineExe - { - static void Main(string[] args) - { - Console.WriteLine("Ready!"); - TestEngine testEngine = new TestEngine(); - - if (args.Length < 1) - { - Console.WriteLine("Missing required args: path and methodName."); - return; - //take off then and throw an exception - //is it possible to return value? Not being void - } - string path = args[0]; - if (!File.Exists(path)) - { - Console.WriteLine("File doesn't exists"); - return; - } - if (Path.GetExtension(path).ToLowerInvariant() != ".nef") - { - Console.WriteLine("Incorect file. Nef file required."); - return; - } - - if (args.Length < 2) - { - Console.WriteLine("Missing required args: methodName."); - return; - } - string methodName = args[1]; - var parameters = ConvertParameters(args.Skip(2).ToArray()); - - testEngine.AddEntryScript(path); - - var paramCount = GetMethodParametersCount(methodName, testEngine); - if (paramCount == -1) - { - Console.WriteLine("Method doesn't exist."); - return; - } - if (paramCount != parameters.Length) - { - Console.WriteLine("Incorrect number of parameters."); - return; - } - var result = testEngine.GetMethod(methodName).Run(parameters); - Console.WriteLine("Result: " + result); - } - - /// - /// - /// - /// - /// - /// - /// Returns the number of parameters in the method if the method exists, otherwise it returns -1. - /// - public static int GetMethodParametersCount(string methodname, TestEngine testEngine) - { - if (testEngine.ScriptEntry is null) return -1; - var methods = testEngine.ScriptEntry.finalABI["methods"] as JArray; - foreach (JObject method in methods) - { - if (method["name"].ToString() == methodname) //method exists - return (method["parameters"] as JArray).Count; - } - - return -1; - } - - static StackItem ToStackItem(string arg) - { - if (int.TryParse(arg, out int intParam)) - { - return intParam; - } - else if (bool.TryParse(arg, out bool boolParam)) - { - return boolParam; - } - else - { - return arg; - } - } - - static StackItem[] ConvertParameters(string[] args) - { - List stackParams = new List(); - - foreach (string parameter in args) - { - stackParams.Add(ToStackItem(parameter)); - } - return stackParams.ToArray(); - } - } -} diff --git a/src/TestEngineExe/TestEngineExe.csproj b/src/TestEngineExe/TestEngineExe.csproj deleted file mode 100644 index 705065db2..000000000 --- a/src/TestEngineExe/TestEngineExe.csproj +++ /dev/null @@ -1,12 +0,0 @@ - - - - Exe - netcoreapp3.1 - - - - - - - diff --git a/src/TestingEngine/Engine.cs b/src/TestingEngine/Engine.cs new file mode 100644 index 000000000..21579b40c --- /dev/null +++ b/src/TestingEngine/Engine.cs @@ -0,0 +1,98 @@ +using Neo; +using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.Cryptography.ECC; +using Neo.IO.Json; +using Neo.Network.P2P.Payloads; +using Neo.SmartContract; +using Neo.SmartContract.Manifest; +using Neo.VM; +using Neo.VM.Types; + +namespace TestingEngine +{ + public class Engine + { + private static Engine instance = null; + public static Engine Instance + { + get + { + if (instance == null) + { + instance = new Engine(); + } + return instance; + } + } + + private TestEngine engine = null; + private byte[] PubKey => HexString2Bytes("03ea01cb94bdaf0cd1c01b159d474f9604f4af35a3e2196f6bdfdb33b2aa4961fa"); + + private Engine() + { + engine = SetupNativeContracts(); + } + + public void SetTestEngine(string path) + { + engine.AddEntryScript(path); + var manifest = ContractManifest.FromJson(JObject.Parse(engine.ScriptEntry.finalManifest)); + + engine.Snapshot.Contracts.Add(manifest.Hash, new Neo.Ledger.ContractState() + { + Script = engine.ScriptEntry.finalNEF, + Manifest = manifest, + }); + } + + public JObject Run(string method, StackItem[] args) + { + engine.GetMethod(method).RunEx(args); + return engine.ToJson(); + } + + private TestEngine SetupNativeContracts() + { + var block = new Block() + { + Index = 0, + ConsensusData = new ConsensusData(), + Transactions = new Transaction[0], + Witness = new Witness() + { + InvocationScript = new byte[0], + VerificationScript = Contract.CreateSignatureRedeemScript(ECPoint.FromBytes(PubKey, ECCurve.Secp256k1)) + }, + NextConsensus = UInt160.Zero, + MerkleRoot = UInt256.Zero, + PrevHash = UInt256.Zero + }; + + TestEngine engine = new TestEngine(TriggerType.Application, block); + ((TestSnapshot)engine.Snapshot).SetPersistingBlock(block); + + using (var script = new ScriptBuilder()) + { + script.EmitSysCall(TestEngine.Native_Deploy); + engine.LoadScript(script.ToArray()); + engine.Execute(); + } + engine.ClearNotifications(); + ((TestSnapshot)engine.Snapshot).ClearStorage(); + + return engine; + } + + private static byte[] HexString2Bytes(string str) + { + if (str.IndexOf("0x") == 0) + str = str.Substring(2); + byte[] outd = new byte[str.Length / 2]; + for (var i = 0; i < str.Length / 2; i++) + { + outd[i] = byte.Parse(str.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber); + } + return outd; + } + } +} diff --git a/src/TestingEngine/Helper.cs b/src/TestingEngine/Helper.cs new file mode 100644 index 000000000..096b3fb8a --- /dev/null +++ b/src/TestingEngine/Helper.cs @@ -0,0 +1,69 @@ +using Neo; +using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.IO.Caching; +using Neo.IO.Json; +using Neo.Ledger; +using Neo.SmartContract; +using Neo.SmartContract.Native; +using Neo.VM; +using Neo.VM.Types; +using System; +using System.Linq; + +namespace TestingEngine +{ + public static class Helper + { + public static JObject ToJson(this TestEngine testEngine) + { + var json = new JObject(); + + json["vm_state"] = testEngine.State.ToString(); + json["gas_consumed"] = (new BigDecimal(testEngine.GasConsumed, NativeContract.GAS.Decimals)).ToString(); + json["result_stack"] = testEngine.ResultStack.ToJson(); + json["storage"] = testEngine.Snapshot.Storages.ToJson(); + json["notifications"] = new JArray(testEngine.Notifications.Select(n => n.ToJson())); + json["error"] = testEngine.State.HasFlag(VMState.FAULT) ? GetExceptionMessage(testEngine.FaultException) : null; + + return json; + } + + public static JObject ToJson(this EvaluationStack stack) + { + return new JArray(stack.Select(p => p.ToJson())); + } + + public static JObject ToJson(this NotifyEventArgs notification) + { + var json = new JObject(); + json["eventName"] = notification.EventName; + json["scriptHash"] = notification.ScriptHash.ToString(); + json["value"] = notification.State.ToJson(); + return json; + } + + public static JObject ToJson(this DataCache storage) + { + var storageMap = new Map(); + foreach (var storagePair in storage.Seek()) + { + var key = new ByteString(storagePair.Key.Key); + var value = new ByteString(storagePair.Value.Value); + storageMap[key] = value; + } + return storageMap.ToJson()["value"]; + } + + private static string GetExceptionMessage(Exception exception) + { + if (exception == null) return "Engine faulted."; + + if (exception.InnerException != null) + { + return GetExceptionMessage(exception.InnerException); + } + + return exception.Message; + } + } +} diff --git a/src/TestingEngine/Program.cs b/src/TestingEngine/Program.cs new file mode 100644 index 000000000..213a484ba --- /dev/null +++ b/src/TestingEngine/Program.cs @@ -0,0 +1,134 @@ +using Neo.IO.Json; +using Neo.SmartContract; +using Neo.VM; +using Neo.VM.Types; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace TestingEngine +{ + class Program + { + static int Main(string[] args) + { + JObject result; + if (args.Length >= 2) + { + result = RunWithMethodName(args[0], args[1], string.Join(" ", args.Skip(2))); + } + else + { + result = BuildJsonException("One or more arguments are missing"); + } + + Console.WriteLine(result); + if (!result.ContainsProperty("vm_state")) + { + return -1; + } + return 0; + } + + /// + /// Runs a nef script given a method name and its arguments + /// + /// Absolute path of the script + /// The name of the targeted method + /// Json string representing the arguments of the method + /// Returns a json with the engine state after executing the script + public static JObject RunWithMethodName(string path, string methodName, string jsonParams) + { + try + { + JArray parameters = new JArray(); + if (jsonParams.Length > 0) + { + var json = JObject.Parse(jsonParams); + if (json is JArray array) + { + parameters = array; + } + else + { + parameters.Insert(0, json); + } + } + + return Run(path, methodName, parameters); + } + catch (Exception e) + { + return BuildJsonException(e.Message); + } + } + + /// + /// Runs the given method from a nef script + /// + /// Absolute path of the script + /// The name of the targeted method + /// Arguments of the method + /// Returns a json with the engine state after executing the script + public static JObject Run(string path, string method, JArray parameters) + { + if (!File.Exists(path)) + { + return BuildJsonException("File doesn't exists"); + } + if (Path.GetExtension(path).ToLowerInvariant() != ".nef") + { + return BuildJsonException("Invalid file. A .nef file required."); + } + + try + { + Engine.Instance.SetTestEngine(path); + var stackParams = GetStackItemParameters(parameters); + return Engine.Instance.Run(method, stackParams); + } + catch (Exception e) + { + return BuildJsonException(e.Message); + } + } + + /// + /// Converts the data in a json array to an array of StackItem + /// + /// json array to be converted + /// Returns the built StackItem array + private static StackItem[] GetStackItemParameters(JArray parameters) + { + var items = new List(); + foreach (JObject param in parameters) + { + var success = false; + if (param.ContainsProperty("value") && param.ContainsProperty("type")) + { + try + { + items.Add(ContractParameter.FromJson(param).ToStackItem()); + success = true; + } + catch { } + } + + if (!success) + { + // if something went wrong while reading the json, inserts null in this argument position + items.Add(StackItem.Null); + } + } + return items.ToArray(); + } + + private static JObject BuildJsonException(string message) + { + var json = new JObject(); + json["error"] = message; + return json; + } + } +} diff --git a/src/TestingEngine/TestingEngine.csproj b/src/TestingEngine/TestingEngine.csproj new file mode 100644 index 000000000..d5ef02252 --- /dev/null +++ b/src/TestingEngine/TestingEngine.csproj @@ -0,0 +1,25 @@ + + + + 2015-2020 The Neo Project + Neo.TestEngine + 3.0.0-preview3 + The Neo Project + Exe + netcoreapp3.1 + NEO;Blockchain;Smart Contract + https://github.com/neo-project/neo-devpack-dotnet + MIT + git + https://github.com/neo-project/neo-devpack-dotnet.git + Neo.TestEngine + The Neo Project + TestingEngine + TestingEngine + + + + + + + diff --git a/tests/Neo.Compiler.MSIL.UnitTests/Utils/TestSnapshot.cs b/tests/Neo.Compiler.MSIL.UnitTests/Utils/TestSnapshot.cs index 5953b9a8d..c1c88a27b 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/Utils/TestSnapshot.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/Utils/TestSnapshot.cs @@ -41,5 +41,16 @@ public void SetPersistingBlock(Block block) { this.GetType().GetProperty("PersistingBlock").SetValue(this, block); } + + /// + /// Clear the storage for unit test + /// + public void ClearStorage() + { + foreach (var pair in this.Storages.Seek()) + { + ((TestDataCache)this._Storages).Delete(pair.Key); + } + } } } From bd17afc4e11212f9b499e17e237a647cfac99ca2 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 21 Sep 2020 16:26:55 -0300 Subject: [PATCH 03/77] move clear to TestDataCache --- tests/Neo.Compiler.MSIL.UnitTests/Utils/TestDataCache.cs | 8 ++++++++ tests/Neo.Compiler.MSIL.UnitTests/Utils/TestSnapshot.cs | 5 +---- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/tests/Neo.Compiler.MSIL.UnitTests/Utils/TestDataCache.cs b/tests/Neo.Compiler.MSIL.UnitTests/Utils/TestDataCache.cs index 593a7799e..e6f536d51 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/Utils/TestDataCache.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/Utils/TestDataCache.cs @@ -54,5 +54,13 @@ protected override void UpdateInternal(TKey key, TValue value) { dic[key] = value; } + + /// + /// Clear the storage for unit test + /// + public void Clear() + { + dic.Clear(); + } } } diff --git a/tests/Neo.Compiler.MSIL.UnitTests/Utils/TestSnapshot.cs b/tests/Neo.Compiler.MSIL.UnitTests/Utils/TestSnapshot.cs index c1c88a27b..dadb400ec 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/Utils/TestSnapshot.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/Utils/TestSnapshot.cs @@ -47,10 +47,7 @@ public void SetPersistingBlock(Block block) /// public void ClearStorage() { - foreach (var pair in this.Storages.Seek()) - { - ((TestDataCache)this._Storages).Delete(pair.Key); - } + ((TestDataCache)this._Storages).Clear(); } } } From 80335e3f81eeb72af6593e6daf3786ece1a2a62d Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 5 Oct 2020 14:52:16 -0300 Subject: [PATCH 04/77] moved TestEngine and TestUtils to TestEngine project + added TestEngine in Neo.Compiler.MSIL.UnitTests dependencies --- neo-devpack-dotnet.sln | 2 +- src/{TestingEngine => TestEngine}/Engine.cs | 0 src/{TestingEngine => TestEngine}/Helper.cs | 0 src/{TestingEngine => TestEngine}/Program.cs | 0 .../TestingEngine.csproj => TestEngine/TestEngine.csproj} | 2 +- .../Utils => src/TestEngine/TestUtils}/BuildNEF.cs | 3 +-- .../Utils => src/TestEngine/TestUtils}/BuildScript.cs | 0 .../Utils => src/TestEngine/TestUtils}/DefLogger.cs | 0 .../Utils => src/TestEngine/TestUtils}/NeonTestTool.cs | 2 +- .../Utils => src/TestEngine/TestUtils}/TestDataCache.cs | 0 .../Utils => src/TestEngine/TestUtils}/TestEngine.cs | 0 .../Utils => src/TestEngine/TestUtils}/TestMetaDataCache.cs | 0 .../Utils => src/TestEngine/TestUtils}/TestSnapshot.cs | 0 .../Utils => src/TestEngine/TestUtils}/TestStorageContext.cs | 0 .../Neo.Compiler.MSIL.UnitTests.csproj | 1 + 15 files changed, 5 insertions(+), 5 deletions(-) rename src/{TestingEngine => TestEngine}/Engine.cs (100%) rename src/{TestingEngine => TestEngine}/Helper.cs (100%) rename src/{TestingEngine => TestEngine}/Program.cs (100%) rename src/{TestingEngine/TestingEngine.csproj => TestEngine/TestEngine.csproj} (89%) rename {tests/Neo.Compiler.MSIL.UnitTests/Utils => src/TestEngine/TestUtils}/BuildNEF.cs (86%) rename {tests/Neo.Compiler.MSIL.UnitTests/Utils => src/TestEngine/TestUtils}/BuildScript.cs (100%) rename {tests/Neo.Compiler.MSIL.UnitTests/Utils => src/TestEngine/TestUtils}/DefLogger.cs (100%) rename {tests/Neo.Compiler.MSIL.UnitTests/Utils => src/TestEngine/TestUtils}/NeonTestTool.cs (98%) rename {tests/Neo.Compiler.MSIL.UnitTests/Utils => src/TestEngine/TestUtils}/TestDataCache.cs (100%) rename {tests/Neo.Compiler.MSIL.UnitTests/Utils => src/TestEngine/TestUtils}/TestEngine.cs (100%) rename {tests/Neo.Compiler.MSIL.UnitTests/Utils => src/TestEngine/TestUtils}/TestMetaDataCache.cs (100%) rename {tests/Neo.Compiler.MSIL.UnitTests/Utils => src/TestEngine/TestUtils}/TestSnapshot.cs (100%) rename {tests/Neo.Compiler.MSIL.UnitTests/Utils => src/TestEngine/TestUtils}/TestStorageContext.cs (100%) diff --git a/neo-devpack-dotnet.sln b/neo-devpack-dotnet.sln index 3409795a1..8d690b769 100644 --- a/neo-devpack-dotnet.sln +++ b/neo-devpack-dotnet.sln @@ -29,7 +29,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Template.NEP5.CSharp", "tem EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Template.NEP5.UnitTests", "tests\Template.NEP5.UnitTests\Template.NEP5.UnitTests.csproj", "{780141EE-D6E9-4591-8470-8F91B12027CA}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestingEngine", "src\TestingEngine\TestingEngine.csproj", "{39347E90-FC12-4018-8F22-828F0F1B2F7D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestEngine", "src\TestEngine\TestEngine.csproj", "{39347E90-FC12-4018-8F22-828F0F1B2F7D}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/src/TestingEngine/Engine.cs b/src/TestEngine/Engine.cs similarity index 100% rename from src/TestingEngine/Engine.cs rename to src/TestEngine/Engine.cs diff --git a/src/TestingEngine/Helper.cs b/src/TestEngine/Helper.cs similarity index 100% rename from src/TestingEngine/Helper.cs rename to src/TestEngine/Helper.cs diff --git a/src/TestingEngine/Program.cs b/src/TestEngine/Program.cs similarity index 100% rename from src/TestingEngine/Program.cs rename to src/TestEngine/Program.cs diff --git a/src/TestingEngine/TestingEngine.csproj b/src/TestEngine/TestEngine.csproj similarity index 89% rename from src/TestingEngine/TestingEngine.csproj rename to src/TestEngine/TestEngine.csproj index d5ef02252..f5fb41556 100644 --- a/src/TestingEngine/TestingEngine.csproj +++ b/src/TestEngine/TestEngine.csproj @@ -19,7 +19,7 @@ - + diff --git a/tests/Neo.Compiler.MSIL.UnitTests/Utils/BuildNEF.cs b/src/TestEngine/TestUtils/BuildNEF.cs similarity index 86% rename from tests/Neo.Compiler.MSIL.UnitTests/Utils/BuildNEF.cs rename to src/TestEngine/TestUtils/BuildNEF.cs index 8ce791f5f..a95625dd4 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/Utils/BuildNEF.cs +++ b/src/TestEngine/TestUtils/BuildNEF.cs @@ -1,8 +1,7 @@ -using Neo.Compiler.MSIL.UnitTests.Utils; using Neo.IO.Json; using Neo.SmartContract; -namespace Neo.Compiler.MSIL.Utils +namespace Neo.Compiler.MSIL.UnitTests.Utils { class BuildNEF : BuildScript { diff --git a/tests/Neo.Compiler.MSIL.UnitTests/Utils/BuildScript.cs b/src/TestEngine/TestUtils/BuildScript.cs similarity index 100% rename from tests/Neo.Compiler.MSIL.UnitTests/Utils/BuildScript.cs rename to src/TestEngine/TestUtils/BuildScript.cs diff --git a/tests/Neo.Compiler.MSIL.UnitTests/Utils/DefLogger.cs b/src/TestEngine/TestUtils/DefLogger.cs similarity index 100% rename from tests/Neo.Compiler.MSIL.UnitTests/Utils/DefLogger.cs rename to src/TestEngine/TestUtils/DefLogger.cs diff --git a/tests/Neo.Compiler.MSIL.UnitTests/Utils/NeonTestTool.cs b/src/TestEngine/TestUtils/NeonTestTool.cs similarity index 98% rename from tests/Neo.Compiler.MSIL.UnitTests/Utils/NeonTestTool.cs rename to src/TestEngine/TestUtils/NeonTestTool.cs index 9260ceb74..265e20319 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/Utils/NeonTestTool.cs +++ b/src/TestEngine/TestUtils/NeonTestTool.cs @@ -8,7 +8,7 @@ [assembly: InternalsVisibleTo("Neo.SmartContract.Framework.UnitTests")] namespace Neo.Compiler.MSIL.UnitTests.Utils { - internal static class NeonTestTool + public static class NeonTestTool { /// /// Is not the official script hash, just a unique hash related to the script used for unit test purpose diff --git a/tests/Neo.Compiler.MSIL.UnitTests/Utils/TestDataCache.cs b/src/TestEngine/TestUtils/TestDataCache.cs similarity index 100% rename from tests/Neo.Compiler.MSIL.UnitTests/Utils/TestDataCache.cs rename to src/TestEngine/TestUtils/TestDataCache.cs diff --git a/tests/Neo.Compiler.MSIL.UnitTests/Utils/TestEngine.cs b/src/TestEngine/TestUtils/TestEngine.cs similarity index 100% rename from tests/Neo.Compiler.MSIL.UnitTests/Utils/TestEngine.cs rename to src/TestEngine/TestUtils/TestEngine.cs diff --git a/tests/Neo.Compiler.MSIL.UnitTests/Utils/TestMetaDataCache.cs b/src/TestEngine/TestUtils/TestMetaDataCache.cs similarity index 100% rename from tests/Neo.Compiler.MSIL.UnitTests/Utils/TestMetaDataCache.cs rename to src/TestEngine/TestUtils/TestMetaDataCache.cs diff --git a/tests/Neo.Compiler.MSIL.UnitTests/Utils/TestSnapshot.cs b/src/TestEngine/TestUtils/TestSnapshot.cs similarity index 100% rename from tests/Neo.Compiler.MSIL.UnitTests/Utils/TestSnapshot.cs rename to src/TestEngine/TestUtils/TestSnapshot.cs diff --git a/tests/Neo.Compiler.MSIL.UnitTests/Utils/TestStorageContext.cs b/src/TestEngine/TestUtils/TestStorageContext.cs similarity index 100% rename from tests/Neo.Compiler.MSIL.UnitTests/Utils/TestStorageContext.cs rename to src/TestEngine/TestUtils/TestStorageContext.cs diff --git a/tests/Neo.Compiler.MSIL.UnitTests/Neo.Compiler.MSIL.UnitTests.csproj b/tests/Neo.Compiler.MSIL.UnitTests/Neo.Compiler.MSIL.UnitTests.csproj index 39bb6ae2c..644f8fa0c 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/Neo.Compiler.MSIL.UnitTests.csproj +++ b/tests/Neo.Compiler.MSIL.UnitTests/Neo.Compiler.MSIL.UnitTests.csproj @@ -20,6 +20,7 @@ + From ef714331876c66defb473f74093ac3cf336fcf0a Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 5 Oct 2020 14:56:46 -0300 Subject: [PATCH 05/77] remove unused import --- src/TestEngine/TestUtils/TestEngine.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/TestEngine/TestUtils/TestEngine.cs b/src/TestEngine/TestUtils/TestEngine.cs index ebc138812..24c8de784 100644 --- a/src/TestEngine/TestUtils/TestEngine.cs +++ b/src/TestEngine/TestUtils/TestEngine.cs @@ -1,4 +1,3 @@ -using Neo.Compiler.MSIL.Utils; using Neo.IO.Json; using Neo.Network.P2P.Payloads; using Neo.Persistence; From f0e7d6040262f75f5a637fbc973011dd80e70bf6 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 19 Oct 2020 11:29:52 -0300 Subject: [PATCH 06/77] change namespace --- src/TestEngine/Engine.cs | 4 +--- src/TestEngine/Helper.cs | 4 +--- src/TestEngine/Program.cs | 2 +- src/TestEngine/TestUtils/BuildNEF.cs | 2 +- src/TestEngine/TestUtils/BuildScript.cs | 4 +++- src/TestEngine/TestUtils/DefLogger.cs | 3 ++- src/TestEngine/TestUtils/NeonTestTool.cs | 8 +++----- src/TestEngine/TestUtils/TestDataCache.cs | 2 +- src/TestEngine/TestUtils/TestEngine.cs | 2 +- src/TestEngine/TestUtils/TestMetaDataCache.cs | 2 +- src/TestEngine/TestUtils/TestSnapshot.cs | 2 +- src/TestEngine/TestUtils/TestStorageContext.cs | 2 +- tests/Neo.Compiler.MSIL.UnitTests/UnitTest1.cs | 2 +- tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ABI_Event.cs | 2 +- tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ABI_Offset.cs | 2 +- tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Array.cs | 2 +- .../UnitTest_ByteArrayAssignment.cs | 2 +- tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Concat.cs | 2 +- .../Neo.Compiler.MSIL.UnitTests/UnitTest_ContractCall.cs | 2 +- tests/Neo.Compiler.MSIL.UnitTests/UnitTest_DebugInfo.cs | 2 +- tests/Neo.Compiler.MSIL.UnitTests/UnitTest_EntryPoints.cs | 2 +- tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Invoke.cs | 2 +- tests/Neo.Compiler.MSIL.UnitTests/UnitTest_NULL.cs | 2 +- .../UnitTest_NativeContracts.cs | 2 +- .../Neo.Compiler.MSIL.UnitTests/UnitTest_NefOptimizer.cs | 2 +- .../Neo.Compiler.MSIL.UnitTests/UnitTest_OnDeployment.cs | 2 +- tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Returns.cs | 2 +- tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Shift.cs | 2 +- .../UnitTest_StaticByteArray.cs | 2 +- tests/Neo.Compiler.MSIL.UnitTests/UnitTest_StaticVar.cs | 2 +- tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Switch.cs | 2 +- tests/Neo.Compiler.MSIL.UnitTests/UnitTest_TryCatch.cs | 2 +- tests/Neo.Compiler.MSIL.UnitTests/UnitTest_TypeConvert.cs | 2 +- tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Types.cs | 3 +-- .../UnitTest_VB/UnitTest_Returns.cs | 2 +- .../Neo.SmartContract.Framework.UnitTests/FeatureTest.cs | 2 +- tests/Neo.SmartContract.Framework.UnitTests/HelperTest.cs | 2 +- tests/Neo.SmartContract.Framework.UnitTests/ListTest.cs | 2 +- .../ManifestExtraTest.cs | 2 +- tests/Neo.SmartContract.Framework.UnitTests/MapTest.cs | 2 +- .../Services/Neo/AccountTest.cs | 2 +- .../Services/Neo/BlockchainTest.cs | 2 +- .../Services/Neo/ContractTest.cs | 2 +- .../Services/Neo/CryptoTest.cs | 2 +- .../Services/Neo/EnumeratorTest.cs | 2 +- .../Services/Neo/IteratorTest.cs | 2 +- .../Services/Neo/JsonTest.cs | 2 +- .../Services/Neo/NativeTest.cs | 2 +- .../Services/Neo/PointerTest.cs | 2 +- .../Services/Neo/RuntimeTest.cs | 2 +- .../Services/Neo/StaticStorageMapTest.cs | 2 +- .../Services/Neo/StorageTest.cs | 2 +- .../Services/System/BinaryTest.cs | 2 +- .../Services/System/CallbackTest.cs | 2 +- .../Services/System/ExecutionEngineTest.cs | 2 +- tests/Neo.SmartContract.Framework.UnitTests/StringTest.cs | 2 +- tests/Template.NEP5.UnitTests/UnitTest_NEP5.cs | 2 +- 57 files changed, 62 insertions(+), 66 deletions(-) diff --git a/src/TestEngine/Engine.cs b/src/TestEngine/Engine.cs index 21579b40c..3b3443759 100644 --- a/src/TestEngine/Engine.cs +++ b/src/TestEngine/Engine.cs @@ -1,5 +1,3 @@ -using Neo; -using Neo.Compiler.MSIL.UnitTests.Utils; using Neo.Cryptography.ECC; using Neo.IO.Json; using Neo.Network.P2P.Payloads; @@ -8,7 +6,7 @@ using Neo.VM; using Neo.VM.Types; -namespace TestingEngine +namespace Neo.TestingEngine { public class Engine { diff --git a/src/TestEngine/Helper.cs b/src/TestEngine/Helper.cs index 096b3fb8a..b784f043c 100644 --- a/src/TestEngine/Helper.cs +++ b/src/TestEngine/Helper.cs @@ -1,5 +1,3 @@ -using Neo; -using Neo.Compiler.MSIL.UnitTests.Utils; using Neo.IO.Caching; using Neo.IO.Json; using Neo.Ledger; @@ -10,7 +8,7 @@ using System; using System.Linq; -namespace TestingEngine +namespace Neo.TestingEngine { public static class Helper { diff --git a/src/TestEngine/Program.cs b/src/TestEngine/Program.cs index 213a484ba..5c50b55a6 100644 --- a/src/TestEngine/Program.cs +++ b/src/TestEngine/Program.cs @@ -7,7 +7,7 @@ using System.IO; using System.Linq; -namespace TestingEngine +namespace Neo.TestingEngine { class Program { diff --git a/src/TestEngine/TestUtils/BuildNEF.cs b/src/TestEngine/TestUtils/BuildNEF.cs index a95625dd4..9ef93757d 100644 --- a/src/TestEngine/TestUtils/BuildNEF.cs +++ b/src/TestEngine/TestUtils/BuildNEF.cs @@ -1,7 +1,7 @@ using Neo.IO.Json; using Neo.SmartContract; -namespace Neo.Compiler.MSIL.UnitTests.Utils +namespace Neo.TestingEngine { class BuildNEF : BuildScript { diff --git a/src/TestEngine/TestUtils/BuildScript.cs b/src/TestEngine/TestUtils/BuildScript.cs index d91317a69..8b03d4e4e 100644 --- a/src/TestEngine/TestUtils/BuildScript.cs +++ b/src/TestEngine/TestUtils/BuildScript.cs @@ -1,10 +1,12 @@ +using Neo.Compiler; +using Neo.Compiler.MSIL; using Neo.Compiler.Optimizer; using Neo.IO.Json; using System; using System.Collections.Generic; using System.IO; -namespace Neo.Compiler.MSIL.UnitTests.Utils +namespace Neo.TestingEngine { public class BuildScript { diff --git a/src/TestEngine/TestUtils/DefLogger.cs b/src/TestEngine/TestUtils/DefLogger.cs index 35e82ada5..a6b6e1af0 100644 --- a/src/TestEngine/TestUtils/DefLogger.cs +++ b/src/TestEngine/TestUtils/DefLogger.cs @@ -1,6 +1,7 @@ +using Neo.Compiler; using System; -namespace Neo.Compiler.MSIL.UnitTests.Utils +namespace Neo.TestingEngine { internal class DefLogger : ILogger { diff --git a/src/TestEngine/TestUtils/NeonTestTool.cs b/src/TestEngine/TestUtils/NeonTestTool.cs index 265e20319..886b5c60c 100644 --- a/src/TestEngine/TestUtils/NeonTestTool.cs +++ b/src/TestEngine/TestUtils/NeonTestTool.cs @@ -1,12 +1,10 @@ using Neo.VM; using System.IO; using System.Linq; -using System.Runtime.CompilerServices; using System.Security.Cryptography; using System.Text; -[assembly: InternalsVisibleTo("Neo.SmartContract.Framework.UnitTests")] -namespace Neo.Compiler.MSIL.UnitTests.Utils +namespace Neo.TestingEngine { public static class NeonTestTool { @@ -69,8 +67,8 @@ public static BuildScript BuildScript(string[] filenames, bool releaseMode = fal var ext = System.IO.Path.GetExtension(filenames.First()); var comp = (ext.ToLowerInvariant()) switch { - ".cs" => Compiler.CompileCSFiles(filenames, new string[0] { }, releaseMode), - ".vb" => Compiler.CompileVBFiles(filenames, new string[0] { }, releaseMode), + ".cs" => Compiler.Compiler.CompileCSFiles(filenames, new string[0] { }, releaseMode), + ".vb" => Compiler.Compiler.CompileVBFiles(filenames, new string[0] { }, releaseMode), _ => throw new System.Exception("do not support extname = " + ext), }; diff --git a/src/TestEngine/TestUtils/TestDataCache.cs b/src/TestEngine/TestUtils/TestDataCache.cs index e6f536d51..50646312b 100644 --- a/src/TestEngine/TestUtils/TestDataCache.cs +++ b/src/TestEngine/TestUtils/TestDataCache.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.Linq; -namespace Neo.Compiler.MSIL.UnitTests.Utils +namespace Neo.TestingEngine { public class TestDataCache : DataCache where TKey : IEquatable, ISerializable diff --git a/src/TestEngine/TestUtils/TestEngine.cs b/src/TestEngine/TestUtils/TestEngine.cs index 24c8de784..146800ea3 100644 --- a/src/TestEngine/TestUtils/TestEngine.cs +++ b/src/TestEngine/TestUtils/TestEngine.cs @@ -8,7 +8,7 @@ using System.Collections.Generic; using System.IO; -namespace Neo.Compiler.MSIL.UnitTests.Utils +namespace Neo.TestingEngine { public class TestEngine : ApplicationEngine { diff --git a/src/TestEngine/TestUtils/TestMetaDataCache.cs b/src/TestEngine/TestUtils/TestMetaDataCache.cs index 327088cf7..6523d54a3 100644 --- a/src/TestEngine/TestUtils/TestMetaDataCache.cs +++ b/src/TestEngine/TestUtils/TestMetaDataCache.cs @@ -1,7 +1,7 @@ using Neo.IO; using Neo.IO.Caching; -namespace Neo.Compiler.MSIL.UnitTests.Utils +namespace Neo.TestingEngine { public class TestMetaDataCache : MetaDataCache where T : class, ICloneable, ISerializable, new() { diff --git a/src/TestEngine/TestUtils/TestSnapshot.cs b/src/TestEngine/TestUtils/TestSnapshot.cs index dadb400ec..db339dfa4 100644 --- a/src/TestEngine/TestUtils/TestSnapshot.cs +++ b/src/TestEngine/TestUtils/TestSnapshot.cs @@ -4,7 +4,7 @@ using Neo.Network.P2P.Payloads; using Neo.Persistence; -namespace Neo.Compiler.MSIL.UnitTests.Utils +namespace Neo.TestingEngine { public class TestSnapshot : StoreView { diff --git a/src/TestEngine/TestUtils/TestStorageContext.cs b/src/TestEngine/TestUtils/TestStorageContext.cs index 83f1baedd..943b19f5c 100644 --- a/src/TestEngine/TestUtils/TestStorageContext.cs +++ b/src/TestEngine/TestUtils/TestStorageContext.cs @@ -1,4 +1,4 @@ -namespace Neo.Compiler.MSIL.UnitTests.Utils +namespace Neo.TestingEngine { class TestStorageContext { diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest1.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest1.cs index fa878e924..a7effdff3 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest1.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest1.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.VM.Types; using System; diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ABI_Event.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ABI_Event.cs index 3a8517541..5a8c2551d 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ABI_Event.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ABI_Event.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.IO.Json; using System; diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ABI_Offset.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ABI_Offset.cs index b7432a2b3..05ca93ae4 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ABI_Offset.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ABI_Offset.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.IO.Json; using Neo.VM.Types; diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Array.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Array.cs index 3e75b9fd7..d59a6f4fa 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Array.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Array.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.VM.Types; using System.Linq; diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ByteArrayAssignment.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ByteArrayAssignment.cs index c33035370..f0702fce2 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ByteArrayAssignment.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ByteArrayAssignment.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.VM.Types; namespace Neo.Compiler.MSIL.UnitTests diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Concat.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Concat.cs index 38a3eb52d..3443e2ab7 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Concat.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Concat.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.VM; using Neo.VM.Types; diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ContractCall.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ContractCall.cs index 5c10863f9..296be3b1d 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ContractCall.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ContractCall.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.IO.Json; using Neo.SmartContract.Manifest; using Neo.VM; diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_DebugInfo.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_DebugInfo.cs index d2317f63c..70a42e14f 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_DebugInfo.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_DebugInfo.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.IO.Json; using System.Linq; diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_EntryPoints.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_EntryPoints.cs index c3ea16ec8..43f21259c 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_EntryPoints.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_EntryPoints.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using System; namespace Neo.Compiler.MSIL.UnitTests diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Invoke.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Invoke.cs index c56d95894..9f399ed69 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Invoke.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Invoke.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.VM.Types; using System.IO; diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_NULL.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_NULL.cs index 3100902d8..182a3edff 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_NULL.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_NULL.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.SmartContract.Manifest; using Neo.VM.Types; diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_NativeContracts.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_NativeContracts.cs index 3f41fd48a..e91c7e05f 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_NativeContracts.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_NativeContracts.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.SmartContract; using Neo.SmartContract.Native; using Neo.VM; diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_NefOptimizer.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_NefOptimizer.cs index e18a66f1b..7f0c620fd 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_NefOptimizer.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_NefOptimizer.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.Compiler.Optimizer; using Neo.IO.Json; using Neo.VM; diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_OnDeployment.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_OnDeployment.cs index ce6266030..41140c8d4 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_OnDeployment.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_OnDeployment.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.IO.Json; namespace Neo.Compiler.MSIL diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Returns.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Returns.cs index b1f8a1ed5..01d75efe3 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Returns.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Returns.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.VM.Types; namespace Neo.Compiler.MSIL.UnitTests diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Shift.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Shift.cs index 342a68529..6de4dfc88 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Shift.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Shift.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.SmartContract; using System; using System.Collections.Generic; diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_StaticByteArray.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_StaticByteArray.cs index 9c2103605..b04aa84dd 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_StaticByteArray.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_StaticByteArray.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; namespace Neo.Compiler.MSIL.UnitTests { diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_StaticVar.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_StaticVar.cs index b7cc7c91b..75945cd39 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_StaticVar.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_StaticVar.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.VM.Types; namespace Neo.Compiler.MSIL.UnitTests diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Switch.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Switch.cs index 8f655d8fc..99ec13667 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Switch.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Switch.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.VM; namespace Neo.Compiler.MSIL.UnitTests diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_TryCatch.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_TryCatch.cs index 8ac5785ae..72c46c9b2 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_TryCatch.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_TryCatch.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using System; namespace Neo.Compiler.MSIL diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_TypeConvert.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_TypeConvert.cs index a9684a982..93bd78d73 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_TypeConvert.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_TypeConvert.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.VM.Types; namespace Neo.Compiler.MSIL.UnitTests diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Types.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Types.cs index f5b134a0c..785e401e7 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Types.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_Types.cs @@ -1,6 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; -using Neo.VM; +using Neo.TestingEngine; using Neo.VM.Types; using System.Linq; diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_VB/UnitTest_Returns.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_VB/UnitTest_Returns.cs index 47efecf45..cfd84ebb0 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_VB/UnitTest_Returns.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_VB/UnitTest_Returns.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.VM.Types; using System; diff --git a/tests/Neo.SmartContract.Framework.UnitTests/FeatureTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/FeatureTest.cs index 7fc60332e..23a8a8be7 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/FeatureTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/FeatureTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using System.Linq; namespace Neo.SmartContract.Framework.UnitTests diff --git a/tests/Neo.SmartContract.Framework.UnitTests/HelperTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/HelperTest.cs index 592115821..2e2d2b292 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/HelperTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/HelperTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.VM; using Neo.VM.Types; diff --git a/tests/Neo.SmartContract.Framework.UnitTests/ListTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/ListTest.cs index 216513d40..eb0869285 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/ListTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/ListTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.IO.Json; using Neo.VM; using Neo.VM.Types; diff --git a/tests/Neo.SmartContract.Framework.UnitTests/ManifestExtraTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/ManifestExtraTest.cs index 5de8c8f15..e4ad3fc36 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/ManifestExtraTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/ManifestExtraTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using System.Linq; namespace Neo.SmartContract.Framework.UnitTests diff --git a/tests/Neo.SmartContract.Framework.UnitTests/MapTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/MapTest.cs index 02bd24de3..c1a87b266 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/MapTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/MapTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.VM; using Neo.VM.Types; diff --git a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/AccountTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/AccountTest.cs index da057d09f..d593b5e03 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/AccountTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/AccountTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.Ledger; using Neo.VM.Types; diff --git a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/BlockchainTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/BlockchainTest.cs index 2d6e7b48b..764c78fea 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/BlockchainTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/BlockchainTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.IO; using Neo.Ledger; using Neo.VM; diff --git a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/ContractTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/ContractTest.cs index abbb82f1e..e46d60604 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/ContractTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/ContractTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.IO; using Neo.IO.Json; using Neo.SmartContract.Manifest; diff --git a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/CryptoTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/CryptoTest.cs index 99d23c0c2..647ee46df 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/CryptoTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/CryptoTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.Cryptography; using Neo.Network.P2P; using Neo.Network.P2P.Payloads; diff --git a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/EnumeratorTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/EnumeratorTest.cs index 85ba41092..8574f554a 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/EnumeratorTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/EnumeratorTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.SmartContract.Enumerators; using Neo.VM; using Neo.VM.Types; diff --git a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/IteratorTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/IteratorTest.cs index c9ecbf41e..81825923d 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/IteratorTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/IteratorTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.VM; using Neo.VM.Types; diff --git a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/JsonTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/JsonTest.cs index cbac16fd5..98f31d7f3 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/JsonTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/JsonTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.VM; using Neo.VM.Types; using System.Text; diff --git a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/NativeTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/NativeTest.cs index f88a16980..8c7452929 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/NativeTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/NativeTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.Cryptography.ECC; using Neo.VM; using Neo.VM.Types; diff --git a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/PointerTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/PointerTest.cs index d0ce1308f..c83c43c94 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/PointerTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/PointerTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.VM; using Neo.VM.Types; using System.Numerics; diff --git a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/RuntimeTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/RuntimeTest.cs index ff1f9589a..ad6b4b7d9 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/RuntimeTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/RuntimeTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.IO; using Neo.IO.Json; using Neo.Network.P2P.Payloads; diff --git a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/StaticStorageMapTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/StaticStorageMapTest.cs index b98b912d1..4c779deba 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/StaticStorageMapTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/StaticStorageMapTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.Ledger; using Neo.VM; using System.Linq; diff --git a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/StorageTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/StorageTest.cs index 0a8bcd1ab..481bfb827 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/StorageTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/StorageTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.Ledger; using Neo.VM.Types; using System; diff --git a/tests/Neo.SmartContract.Framework.UnitTests/Services/System/BinaryTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/Services/System/BinaryTest.cs index 82d6e7d4a..ef301ba91 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/Services/System/BinaryTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/Services/System/BinaryTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.Ledger; using Neo.SmartContract; using Neo.SmartContract.Framework.UnitTests; diff --git a/tests/Neo.SmartContract.Framework.UnitTests/Services/System/CallbackTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/Services/System/CallbackTest.cs index 5f46a605a..2ed194a9d 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/Services/System/CallbackTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/Services/System/CallbackTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.IO; using Neo.Ledger; using Neo.SmartContract; diff --git a/tests/Neo.SmartContract.Framework.UnitTests/Services/System/ExecutionEngineTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/Services/System/ExecutionEngineTest.cs index 0ec931e09..9799d0984 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/Services/System/ExecutionEngineTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/Services/System/ExecutionEngineTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.IO; using Neo.Network.P2P.Payloads; using Neo.Persistence; diff --git a/tests/Neo.SmartContract.Framework.UnitTests/StringTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/StringTest.cs index c2d0a1c10..506f9493c 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/StringTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/StringTest.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.VM.Types; namespace Neo.SmartContract.Framework.UnitTests diff --git a/tests/Template.NEP5.UnitTests/UnitTest_NEP5.cs b/tests/Template.NEP5.UnitTests/UnitTest_NEP5.cs index 8eb6e9b89..2d9c7c671 100644 --- a/tests/Template.NEP5.UnitTests/UnitTest_NEP5.cs +++ b/tests/Template.NEP5.UnitTests/UnitTest_NEP5.cs @@ -1,5 +1,5 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; +using Neo.TestingEngine; using Neo.VM.Types; using System.Linq; using System.Numerics; From ba806a14bc6ba7c935ae6c86a79e9e8c72dacc62 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Fri, 16 Oct 2020 18:51:49 -0300 Subject: [PATCH 07/77] code review + unit tests --- .github/workflows/main.yml | 2 + neo-devpack-dotnet.sln | 7 + src/TestEngine/Engine.cs | 5 + src/TestEngine/Helper.cs | 2 +- src/TestEngine/Program.cs | 25 ++- .../TestClasses/Contract1.cs | 28 ++++ .../TestClasses/Contract2.cs | 19 +++ .../TestEngine.UnitTests.csproj | 34 ++++ tests/TestEngine.UnitTests/UnitTest_Invoke.cs | 149 ++++++++++++++++++ 9 files changed, 262 insertions(+), 9 deletions(-) create mode 100644 tests/TestEngine.UnitTests/TestClasses/Contract1.cs create mode 100644 tests/TestEngine.UnitTests/TestClasses/Contract2.cs create mode 100644 tests/TestEngine.UnitTests/TestEngine.UnitTests.csproj create mode 100644 tests/TestEngine.UnitTests/UnitTest_Invoke.cs diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 46b8281ff..ee9afe0fc 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -31,6 +31,8 @@ jobs: run: dotnet test tests/Neo.SmartContract.Framework.UnitTests /p:CollectCoverage=true /p:CoverletOutput=${GITHUB_WORKSPACE}/coverage/lcov /p:MergeWith=${GITHUB_WORKSPACE}/coverage/coverage.json /p:Exclude=\"[Neo.SmartContract.*]*,[Neo.Compiler.MSIL.UnitTests]*,[Neo.Compiler.MSIL.UnitTests.*]*\" /p:CoverletOutputFormat=lcov - name: Test Template.NEP5.UnitTests run: dotnet test tests/Template.NEP5.UnitTests /p:CollectCoverage=true /p:CoverletOutput=${GITHUB_WORKSPACE}/coverage/lcov /p:MergeWith=${GITHUB_WORKSPACE}/coverage/coverage.json /p:Exclude=\"[Neo.SmartContract.*]*,[Neo.Compiler.MSIL.UnitTests]*,[Neo.Compiler.MSIL.UnitTests.*]*\" /p:CoverletOutputFormat=lcov + - name: Test TestEngine.UnitTests + run: dotnet test tests/TestEngine.UnitTests /p:CollectCoverage=true /p:CoverletOutput=${GITHUB_WORKSPACE}/coverage/lcov /p:MergeWith=${GITHUB_WORKSPACE}/coverage/coverage.json /p:Exclude=\"[Neo.SmartContract.*]*,[Neo.Compiler.MSIL.UnitTests]*,[Neo.Compiler.MSIL.UnitTests.*]*\" /p:CoverletOutputFormat=lcov - name: Coveralls uses: coverallsapp/github-action@master with: diff --git a/neo-devpack-dotnet.sln b/neo-devpack-dotnet.sln index 8d690b769..ca3e29413 100644 --- a/neo-devpack-dotnet.sln +++ b/neo-devpack-dotnet.sln @@ -31,6 +31,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Template.NEP5.UnitTests", " EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestEngine", "src\TestEngine\TestEngine.csproj", "{39347E90-FC12-4018-8F22-828F0F1B2F7D}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestEngine.UnitTests", "tests\TestEngine.UnitTests\TestEngine.UnitTests.csproj", "{FFDC189F-2F72-4542-B28B-8EFA0F28E3CF}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -77,6 +79,10 @@ Global {39347E90-FC12-4018-8F22-828F0F1B2F7D}.Debug|Any CPU.Build.0 = Debug|Any CPU {39347E90-FC12-4018-8F22-828F0F1B2F7D}.Release|Any CPU.ActiveCfg = Release|Any CPU {39347E90-FC12-4018-8F22-828F0F1B2F7D}.Release|Any CPU.Build.0 = Release|Any CPU + {FFDC189F-2F72-4542-B28B-8EFA0F28E3CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FFDC189F-2F72-4542-B28B-8EFA0F28E3CF}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FFDC189F-2F72-4542-B28B-8EFA0F28E3CF}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FFDC189F-2F72-4542-B28B-8EFA0F28E3CF}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -92,6 +98,7 @@ Global {ADD05222-DC45-4FDC-A41A-30A97BACC95F} = {7042EF23-826B-45A1-A905-59AD678C31B7} {780141EE-D6E9-4591-8470-8F91B12027CA} = {D5266066-0AFD-44D5-A83E-2F73668A63C8} {39347E90-FC12-4018-8F22-828F0F1B2F7D} = {79389FC0-C621-4CEA-AD2B-6074C32E7BCA} + {FFDC189F-2F72-4542-B28B-8EFA0F28E3CF} = {D5266066-0AFD-44D5-A83E-2F73668A63C8} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {6DA935E1-C674-4364-B087-F1B511B79215} diff --git a/src/TestEngine/Engine.cs b/src/TestEngine/Engine.cs index 3b3443759..e6d7cd34c 100644 --- a/src/TestEngine/Engine.cs +++ b/src/TestEngine/Engine.cs @@ -27,6 +27,11 @@ public static Engine Instance private byte[] PubKey => HexString2Bytes("03ea01cb94bdaf0cd1c01b159d474f9604f4af35a3e2196f6bdfdb33b2aa4961fa"); private Engine() + { + Reset(); + } + + public void Reset() { engine = SetupNativeContracts(); } diff --git a/src/TestEngine/Helper.cs b/src/TestEngine/Helper.cs index b784f043c..0fb3fdb4c 100644 --- a/src/TestEngine/Helper.cs +++ b/src/TestEngine/Helper.cs @@ -17,7 +17,7 @@ public static JObject ToJson(this TestEngine testEngine) var json = new JObject(); json["vm_state"] = testEngine.State.ToString(); - json["gas_consumed"] = (new BigDecimal(testEngine.GasConsumed, NativeContract.GAS.Decimals)).ToString(); + json["gasconsumed"] = (new BigDecimal(testEngine.GasConsumed, NativeContract.GAS.Decimals)).ToString(); json["result_stack"] = testEngine.ResultStack.ToJson(); json["storage"] = testEngine.Snapshot.Storages.ToJson(); json["notifications"] = new JArray(testEngine.Notifications.Select(n => n.ToJson())); diff --git a/src/TestEngine/Program.cs b/src/TestEngine/Program.cs index 5c50b55a6..a04d3dd86 100644 --- a/src/TestEngine/Program.cs +++ b/src/TestEngine/Program.cs @@ -9,9 +9,19 @@ namespace Neo.TestingEngine { - class Program + public class Program { static int Main(string[] args) + { + JObject result = Run(args); + if (!result.ContainsProperty("vm_state")) + { + return -1; + } + return 0; + } + + public static JObject Run(string[] args) { JObject result; if (args.Length >= 2) @@ -23,12 +33,7 @@ static int Main(string[] args) result = BuildJsonException("One or more arguments are missing"); } - Console.WriteLine(result); - if (!result.ContainsProperty("vm_state")) - { - return -1; - } - return 0; + return result; } /// @@ -112,7 +117,11 @@ private static StackItem[] GetStackItemParameters(JArray parameters) items.Add(ContractParameter.FromJson(param).ToStackItem()); success = true; } - catch { } + catch (Exception e) + { + // if something went wrong while reading the json, log the error + Console.WriteLine(e); + } } if (!success) diff --git a/tests/TestEngine.UnitTests/TestClasses/Contract1.cs b/tests/TestEngine.UnitTests/TestClasses/Contract1.cs new file mode 100644 index 000000000..f8256ebdc --- /dev/null +++ b/tests/TestEngine.UnitTests/TestClasses/Contract1.cs @@ -0,0 +1,28 @@ +namespace Neo.Compiler.MSIL.UnitTests.TestClasses +{ + public class Contract1 : SmartContract.Framework.SmartContract + { + public static byte[] unitTest_001() + { + var nb = new byte[] { 1, 2, 3, 4 }; + return nb; + } + + public static void testVoid() + { + var nb = new byte[] { 1, 2, 3, 4 }; + } + + public static byte[] testArgs1(byte a) + { + var nb = new byte[] { 1, 2, 3, 3 }; + nb[3] = a; + return nb; + } + + public static object testArgs2(byte[] a) + { + return a; + } + } +} diff --git a/tests/TestEngine.UnitTests/TestClasses/Contract2.cs b/tests/TestEngine.UnitTests/TestClasses/Contract2.cs new file mode 100644 index 000000000..6dc56991f --- /dev/null +++ b/tests/TestEngine.UnitTests/TestClasses/Contract2.cs @@ -0,0 +1,19 @@ +using System; +using System.ComponentModel; + +namespace Neo.Compiler.MSIL.UnitTests.TestClasses +{ + public class Contract2 : SmartContract.Framework.SmartContract + { + [DisplayName("event")] + public static event Action notify; + + public static byte UnitTest_002(object arg1, object arg2) + { + notify(arg1); + notify(arg2); + var nb = new byte[] { 1, 2, 3, 4 }; + return nb[2]; + } + } +} diff --git a/tests/TestEngine.UnitTests/TestEngine.UnitTests.csproj b/tests/TestEngine.UnitTests/TestEngine.UnitTests.csproj new file mode 100644 index 000000000..e56142adb --- /dev/null +++ b/tests/TestEngine.UnitTests/TestEngine.UnitTests.csproj @@ -0,0 +1,34 @@ + + + + netcoreapp3.1 + + false + + + + + + + + + + PreserveNewest + + + PreserveNewest + + + + + + + + + + + + + + + diff --git a/tests/TestEngine.UnitTests/UnitTest_Invoke.cs b/tests/TestEngine.UnitTests/UnitTest_Invoke.cs new file mode 100644 index 000000000..8e88add2a --- /dev/null +++ b/tests/TestEngine.UnitTests/UnitTest_Invoke.cs @@ -0,0 +1,149 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO.Json; +using Neo.TestingEngine; +using Neo.VM; +using Neo.VM.Types; +using System.IO; +using Compiler = Neo.Compiler.Program; + +namespace TestEngine.UnitTests +{ + [TestClass] + public class UnitTest_Invoke + { + [TestInitialize] + public void Init() + { + string path = Directory.GetCurrentDirectory(); + var option = new Compiler.Options() + { + File = path + "/TestClasses/Contract1.cs" + }; + Compiler.Compile(option); + + //Compile changes the path, reseting so that other UT won't break + Directory.SetCurrentDirectory(path); + Engine.Instance.Reset(); + } + + [TestMethod] + public void Test_Missing_Arguments() + { + var args = new string[] { + "./TestClasses/Contract1.nef" + }; + var result = Program.Run(args); + + Assert.IsTrue(result.ContainsProperty("error")); + Assert.AreEqual(result["error"].AsString(), "One or more arguments are missing"); + } + + [TestMethod] + public void Test_Method_Without_Parameters_Void() + { + var args = new string[] { + "./TestClasses/Contract1.nef", + "testVoid" + }; + var result = Program.Run(args); + + // mustn't have errors + Assert.IsTrue(result.ContainsProperty("error")); + Assert.IsNull(result["error"]); + + // test state + Assert.IsTrue(result.ContainsProperty("vm_state")); + Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + + // test result + Assert.IsTrue(result.ContainsProperty("result_stack")); + Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + + var resultStack = result["result_stack"] as JArray; + Assert.IsTrue(resultStack.Count == 0); + } + + [TestMethod] + public void Test_Method_Without_Parameters_With_Return() + { + var args = new string[] { + "./TestClasses/Contract1.nef", + "unitTest_001" + }; + var result = Program.Run(args); + + // mustn't have errors + Assert.IsTrue(result.ContainsProperty("error")); + Assert.IsNull(result["error"]); + + // test state + Assert.IsTrue(result.ContainsProperty("vm_state")); + Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + + // test result + StackItem wantresult = new byte[] { 1, 2, 3, 4 }; + Assert.IsTrue(result.ContainsProperty("result_stack")); + Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + + var resultStack = result["result_stack"] as JArray; + Assert.IsTrue(resultStack.Count == 1); + Assert.IsTrue(resultStack[0].ContainsProperty("value")); + Assert.AreEqual(resultStack[0]["value"].AsString(), wantresult.ToJson()["value"].AsString()); + } + + [TestMethod] + public void Test_Method_With_Parameters() + { + StackItem arguments = 16; + var args = new string[] { + "./TestClasses/Contract1.nef", + "testArgs1", + arguments.ToJson().ToString() + }; + var result = Program.Run(args); + + // mustn't have errors + Assert.IsTrue(result.ContainsProperty("error")); + Assert.IsNull(result["error"]); + + // test state + Assert.IsTrue(result.ContainsProperty("vm_state")); + Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + + // test result + StackItem wantresult = new byte[] { 1, 2, 3, 16 }; + Assert.IsTrue(result.ContainsProperty("result_stack")); + Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + + var resultStack = result["result_stack"] as JArray; + Assert.IsTrue(resultStack.Count == 1); + Assert.IsTrue(resultStack[0].ContainsProperty("value")); + Assert.AreEqual(resultStack[0]["value"].AsString(), wantresult.ToJson()["value"].AsString()); + } + + [TestMethod] + public void Test_Method_With_Parameters_Missing() + { + var args = new string[] { + "./TestClasses/Contract1.nef", + "testArgs1" + }; + var result = Program.Run(args); + + // mustn have an error + Assert.IsTrue(result.ContainsProperty("error")); + Assert.IsNotNull(result["error"]); + + // vm state must've faulted + Assert.IsTrue(result.ContainsProperty("vm_state")); + Assert.AreEqual(result["vm_state"].AsString(), VMState.FAULT.ToString()); + + // result stack must be empty + Assert.IsTrue(result.ContainsProperty("result_stack")); + Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + + var resultStack = result["result_stack"] as JArray; + Assert.IsTrue(resultStack.Count == 0); + } + } +} From b792b97f549d0412e4639b2ad43eaa8d3e0684ef Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 19 Oct 2020 13:28:03 -0300 Subject: [PATCH 08/77] increase coverage --- src/TestEngine/Program.cs | 11 ++- tests/TestEngine.UnitTests/UnitTest_Invoke.cs | 49 ++++++++++- .../UnitTest_Notification.cs | 85 +++++++++++++++++++ 3 files changed, 141 insertions(+), 4 deletions(-) create mode 100644 tests/TestEngine.UnitTests/UnitTest_Notification.cs diff --git a/src/TestEngine/Program.cs b/src/TestEngine/Program.cs index a04d3dd86..f3f53a690 100644 --- a/src/TestEngine/Program.cs +++ b/src/TestEngine/Program.cs @@ -26,7 +26,16 @@ public static JObject Run(string[] args) JObject result; if (args.Length >= 2) { - result = RunWithMethodName(args[0], args[1], string.Join(" ", args.Skip(2))); + string arg2 = ""; + if (args.Length == 3) + { + arg2 = args[2]; + } + else if (args.Length > 3) + { + arg2 = $"[{string.Join(",", args.Skip(2))}]"; + } + result = RunWithMethodName(args[0], args[1], arg2); } else { diff --git a/tests/TestEngine.UnitTests/UnitTest_Invoke.cs b/tests/TestEngine.UnitTests/UnitTest_Invoke.cs index 8e88add2a..ac1286378 100644 --- a/tests/TestEngine.UnitTests/UnitTest_Invoke.cs +++ b/tests/TestEngine.UnitTests/UnitTest_Invoke.cs @@ -98,7 +98,7 @@ public void Test_Method_With_Parameters() var args = new string[] { "./TestClasses/Contract1.nef", "testArgs1", - arguments.ToJson().ToString() + arguments.ToParameter().ToJson().ToString() }; var result = Program.Run(args); @@ -122,7 +122,7 @@ public void Test_Method_With_Parameters() } [TestMethod] - public void Test_Method_With_Parameters_Missing() + public void Test_Method_With_Misstyped_Parameters() { var args = new string[] { "./TestClasses/Contract1.nef", @@ -130,7 +130,7 @@ public void Test_Method_With_Parameters_Missing() }; var result = Program.Run(args); - // mustn have an error + // mustn't have an error Assert.IsTrue(result.ContainsProperty("error")); Assert.IsNotNull(result["error"]); @@ -145,5 +145,48 @@ public void Test_Method_With_Parameters_Missing() var resultStack = result["result_stack"] as JArray; Assert.IsTrue(resultStack.Count == 0); } + + [TestMethod] + public void Test_Method_With_Parameters_Missing() + { + StackItem arguments = 16; + var jsonArgument = arguments.ToParameter().ToJson().ToString(); + var args = new string[] { + "./TestClasses/Contract1.nef", + "testArgs1", + $"{jsonArgument} {jsonArgument}" + }; + var result = Program.Run(args); + + Assert.IsTrue(result.ContainsProperty("error")); + Assert.IsNotNull(result["error"]); + Assert.AreEqual(result.Properties.Count, 1); + } + + [TestMethod] + public void Test_File_Does_Not_Exist() + { + var args = new string[] { + "./TestClasses/Contract0.nef", + "testArgs1", + }; + var result = Program.Run(args); + + Assert.IsTrue(result.ContainsProperty("error")); + Assert.AreEqual(result["error"].AsString(), "File doesn't exists"); + } + + [TestMethod] + public void Test_Invalid_File() + { + var args = new string[] { + "./TestClasses/Contract1.cs", + "testArgs1", + }; + var result = Program.Run(args); + + Assert.IsTrue(result.ContainsProperty("error")); + Assert.AreEqual(result["error"].AsString(), "Invalid file. A .nef file required."); + } } } diff --git a/tests/TestEngine.UnitTests/UnitTest_Notification.cs b/tests/TestEngine.UnitTests/UnitTest_Notification.cs new file mode 100644 index 000000000..d1b925126 --- /dev/null +++ b/tests/TestEngine.UnitTests/UnitTest_Notification.cs @@ -0,0 +1,85 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO.Json; +using Neo.TestingEngine; +using Neo.VM; +using Neo.VM.Types; +using System.IO; +using Compiler = Neo.Compiler.Program; + +namespace TestEngine.UnitTests +{ + [TestClass] + public class UnitTest_Notification + { + [TestInitialize] + public void Init() + { + string path = Directory.GetCurrentDirectory(); + var option = new Compiler.Options() + { + File = path + "/TestClasses/Contract2.cs" + }; + Compiler.Compile(option); + + //Compile changes the path, reseting so that other UT won't break + Directory.SetCurrentDirectory(path); + Engine.Instance.Reset(); + } + + [TestMethod] + public void Test_Notification() + { + StackItem arg1 = 16; + StackItem arg2 = "Teste"; + + var args = new string[] { + "./TestClasses/Contract2.nef", + "unitTest_002", + arg1.ToParameter().ToJson().ToString(), + arg2.ToParameter().ToJson().ToString() + }; + var result = Program.Run(args); + + // mustn't have errors + Assert.IsTrue(result.ContainsProperty("error")); + Assert.IsNull(result["error"]); + + // test state + Assert.IsTrue(result.ContainsProperty("vm_state")); + Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + + // test result + StackItem wantresult = 3; + Assert.IsTrue(result.ContainsProperty("result_stack")); + Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + + var resultStack = result["result_stack"] as JArray; + Assert.IsTrue(resultStack.Count == 1); + Assert.IsTrue(resultStack[0].ContainsProperty("value")); + Assert.AreEqual(resultStack[0]["value"].AsString(), wantresult.ToJson()["value"].AsString()); + + // test notifications + Assert.IsTrue(result.ContainsProperty("notifications")); + Assert.IsInstanceOfType(result["notifications"], typeof(JArray)); + + var notifications = result["notifications"] as JArray; + Assert.IsTrue(notifications.Count == 2); + + Assert.IsTrue(notifications[0].ContainsProperty("value")); + Assert.IsTrue(notifications[0].ContainsProperty("eventName")); + Assert.AreEqual(notifications[0]["eventName"].AsString(), "event"); + Assert.IsTrue(notifications[0].ContainsProperty("value")); + var firstNotifications = notifications[0]["value"]; + Assert.IsTrue(firstNotifications.ContainsProperty("value")); + Assert.AreEqual((firstNotifications["value"] as JArray)[0].AsString(), arg1.ToJson().ToString()); + + Assert.IsTrue(notifications[1].ContainsProperty("value")); + Assert.IsTrue(notifications[1].ContainsProperty("eventName")); + Assert.AreEqual(notifications[1]["eventName"].AsString(), "event"); + Assert.IsTrue(notifications[1].ContainsProperty("value")); + var secondNotifications = notifications[1]["value"]; + Assert.IsTrue(secondNotifications.ContainsProperty("value")); + Assert.AreEqual((secondNotifications["value"] as JArray)[0].AsString(), arg2.ToJson().ToString()); + } + } +} From 8c449101db76938a5cef8b1e7dee3719e3cd64aa Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 19 Oct 2020 16:24:17 -0300 Subject: [PATCH 09/77] show output --- src/TestEngine/Program.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/TestEngine/Program.cs b/src/TestEngine/Program.cs index f3f53a690..4f1ef9f30 100644 --- a/src/TestEngine/Program.cs +++ b/src/TestEngine/Program.cs @@ -14,6 +14,7 @@ public class Program static int Main(string[] args) { JObject result = Run(args); + Console.WriteLine(result); if (!result.ContainsProperty("vm_state")) { return -1; From 71b59ffcf7a98d993d1865f0887de3731e4e448d Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 26 Oct 2020 12:16:12 -0300 Subject: [PATCH 10/77] add json test support to the TestEngine --- src/TestEngine/Program.cs | 61 +++++++++++++- tests/TestEngine.UnitTests/UnitTest_Invoke.cs | 80 +++++++++++++++++++ 2 files changed, 138 insertions(+), 3 deletions(-) diff --git a/src/TestEngine/Program.cs b/src/TestEngine/Program.cs index 4f1ef9f30..61a3050a8 100644 --- a/src/TestEngine/Program.cs +++ b/src/TestEngine/Program.cs @@ -24,6 +24,21 @@ static int Main(string[] args) public static JObject Run(string[] args) { + if (args.Length == 1) + { + // verifies if the parameter is a json string + try + { + var input = JObject.Parse(args[0]); + return RunWithJson(input); + } + catch + { + // if the first input is not a json, verifies if the arguments are: nef path, method name, method args + } + + } + JObject result; if (args.Length >= 2) { @@ -40,7 +55,10 @@ public static JObject Run(string[] args) } else { - result = BuildJsonException("One or more arguments are missing"); + result = BuildJsonException( + "One or more arguments are missing\n" + + "Expected arguments: " + ); } return result; @@ -50,8 +68,8 @@ public static JObject Run(string[] args) /// Runs a nef script given a method name and its arguments /// /// Absolute path of the script - /// The name of the targeted method - /// Json string representing the arguments of the method + /// The name of the targeted method + /// Json string representing the arguments of the method /// Returns a json with the engine state after executing the script public static JObject RunWithMethodName(string path, string methodName, string jsonParams) { @@ -79,6 +97,43 @@ public static JObject RunWithMethodName(string path, string methodName, string j } } + /// + /// Runs a nef script given a json with test engine fake values for testing. + /// + /// json object with fake values and execution arguments + /// Returns a json with the engine state after executing the script + public static JObject RunWithJson(JObject json) + { + var missigFieldMessage = "Missing field: '{0}'"; + if (!json.ContainsProperty("path")) + { + return BuildJsonException(string.Format(missigFieldMessage, "path")); + } + + if (!json.ContainsProperty("method")) + { + return BuildJsonException(string.Format(missigFieldMessage, "method")); + } + + if (!json.ContainsProperty("arguments")) + { + json["arguments"] = new JArray(); + } + + try + { + var path = json["path"].AsString(); + var methodName = json["method"].AsString(); + var parameters = (JArray)json["arguments"]; + + return Run(path, methodName, parameters); + } + catch (Exception e) + { + return BuildJsonException(e.Message); + } + } + /// /// Runs the given method from a nef script /// diff --git a/tests/TestEngine.UnitTests/UnitTest_Invoke.cs b/tests/TestEngine.UnitTests/UnitTest_Invoke.cs index ac1286378..52f4d0d9f 100644 --- a/tests/TestEngine.UnitTests/UnitTest_Invoke.cs +++ b/tests/TestEngine.UnitTests/UnitTest_Invoke.cs @@ -188,5 +188,85 @@ public void Test_Invalid_File() Assert.IsTrue(result.ContainsProperty("error")); Assert.AreEqual(result["error"].AsString(), "Invalid file. A .nef file required."); } + + [TestMethod] + public void Test_Json_Missing_Fields() + { + var json = new JObject(); + json["path"] = "./TestClasses/Contract1.nef"; + + var args = new string[] { + json.AsString() + }; + var result = Program.Run(args); + + Assert.IsTrue(result.ContainsProperty("error")); + Assert.AreEqual(result["error"].AsString(), "One or more arguments are missing"); + } + + [TestMethod] + public void Test_Json() + { + var json = new JObject(); + json["path"] = "./TestClasses/Contract1.nef"; + json["method"] = "unitTest_001"; + + var args = new string[] { + json.AsString() + }; + var result = Program.Run(args); + + // mustn't have errors + Assert.IsTrue(result.ContainsProperty("error")); + Assert.IsNull(result["error"]); + + // test state + Assert.IsTrue(result.ContainsProperty("vm_state")); + Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + + // test result + StackItem wantresult = new byte[] { 1, 2, 3, 4 }; + Assert.IsTrue(result.ContainsProperty("result_stack")); + Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + + var resultStack = result["result_stack"] as JArray; + Assert.IsTrue(resultStack.Count == 1); + Assert.IsTrue(resultStack[0].ContainsProperty("value")); + Assert.AreEqual(resultStack[0]["value"].AsString(), wantresult.ToJson()["value"].AsString()); + } + + [TestMethod] + public void Test_Json_With_Parameters() + { + StackItem arguments = 16; + + var json = new JObject(); + json["path"] = "./TestClasses/Contract1.nef"; + json["method"] = "testArgs1"; + json["arguments"] = arguments.ToParameter().ToJson().ToString(); + + var args = new string[] { + json.AsString() + }; + var result = Program.Run(args); + + // mustn't have errors + Assert.IsTrue(result.ContainsProperty("error")); + Assert.IsNull(result["error"]); + + // test state + Assert.IsTrue(result.ContainsProperty("vm_state")); + Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + + // test result + StackItem wantresult = new byte[] { 1, 2, 3, 16 }; + Assert.IsTrue(result.ContainsProperty("result_stack")); + Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + + var resultStack = result["result_stack"] as JArray; + Assert.IsTrue(resultStack.Count == 1); + Assert.IsTrue(resultStack[0].ContainsProperty("value")); + Assert.AreEqual(resultStack[0]["value"].AsString(), wantresult.ToJson()["value"].AsString()); + } } } From d17242723bb341211eb5f39388cb5593b8aac097 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 26 Oct 2020 13:40:24 -0300 Subject: [PATCH 11/77] fix unit tests --- tests/TestEngine.UnitTests/UnitTest_Invoke.cs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tests/TestEngine.UnitTests/UnitTest_Invoke.cs b/tests/TestEngine.UnitTests/UnitTest_Invoke.cs index 52f4d0d9f..15509a255 100644 --- a/tests/TestEngine.UnitTests/UnitTest_Invoke.cs +++ b/tests/TestEngine.UnitTests/UnitTest_Invoke.cs @@ -35,7 +35,10 @@ public void Test_Missing_Arguments() var result = Program.Run(args); Assert.IsTrue(result.ContainsProperty("error")); - Assert.AreEqual(result["error"].AsString(), "One or more arguments are missing"); + Assert.AreEqual( + "One or more arguments are missing\nExpected arguments: ", + result["error"].AsString() + ); } [TestMethod] @@ -201,7 +204,7 @@ public void Test_Json_Missing_Fields() var result = Program.Run(args); Assert.IsTrue(result.ContainsProperty("error")); - Assert.AreEqual(result["error"].AsString(), "One or more arguments are missing"); + Assert.AreEqual("Missing field: 'method'", result["error"].AsString()); } [TestMethod] @@ -243,7 +246,7 @@ public void Test_Json_With_Parameters() var json = new JObject(); json["path"] = "./TestClasses/Contract1.nef"; json["method"] = "testArgs1"; - json["arguments"] = arguments.ToParameter().ToJson().ToString(); + json["arguments"] = new JArray() { arguments.ToParameter().ToJson() }; var args = new string[] { json.AsString() From ebbc6b4045828fddc40fc8b940d37244e48cd1c1 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 26 Oct 2020 17:10:13 -0300 Subject: [PATCH 12/77] include storage values in the test engine arguments --- src/TestEngine/Engine.cs | 18 ++++++ src/TestEngine/Program.cs | 63 ++++++++++++++++--- src/TestEngine/SmartContractTest.cs | 22 +++++++ src/TestEngine/TestUtils/TestDataCache.cs | 8 +++ tests/TestEngine.UnitTests/UnitTest_Invoke.cs | 43 +++++++++++++ 5 files changed, 146 insertions(+), 8 deletions(-) create mode 100644 src/TestEngine/SmartContractTest.cs diff --git a/src/TestEngine/Engine.cs b/src/TestEngine/Engine.cs index e6d7cd34c..5c2ce13c5 100644 --- a/src/TestEngine/Engine.cs +++ b/src/TestEngine/Engine.cs @@ -1,10 +1,12 @@ using Neo.Cryptography.ECC; using Neo.IO.Json; +using Neo.Ledger; using Neo.Network.P2P.Payloads; using Neo.SmartContract; using Neo.SmartContract.Manifest; using Neo.VM; using Neo.VM.Types; +using System.Collections.Generic; namespace Neo.TestingEngine { @@ -48,6 +50,22 @@ public void SetTestEngine(string path) }); } + public void SetStorage(Dictionary storage) + { + foreach (var data in storage) + { + var key = new StorageKey() + { + Key = data.Key.GetSpan().ToArray() + }; + var value = new StorageItem() + { + Value = data.Value.GetSpan().ToArray() + }; + ((TestDataCache)engine.Snapshot.Storages).AddForTest(key, value); + } + } + public JObject Run(string method, StackItem[] args) { engine.GetMethod(method).RunEx(args); diff --git a/src/TestEngine/Program.cs b/src/TestEngine/Program.cs index 61a3050a8..7faee797a 100644 --- a/src/TestEngine/Program.cs +++ b/src/TestEngine/Program.cs @@ -89,7 +89,8 @@ public static JObject RunWithMethodName(string path, string methodName, string j } } - return Run(path, methodName, parameters); + var smartContractTestCase = new SmartContractTest(path, methodName, parameters); + return Run(smartContractTestCase); } catch (Exception e) { @@ -126,7 +127,13 @@ public static JObject RunWithJson(JObject json) var methodName = json["method"].AsString(); var parameters = (JArray)json["arguments"]; - return Run(path, methodName, parameters); + var smartContractTestCase = new SmartContractTest(path, methodName, parameters); + + if (json.ContainsProperty("storage")) + { + smartContractTestCase.storage = GetStorageFromJson(json["storage"]); + } + return Run(smartContractTestCase); } catch (Exception e) { @@ -141,22 +148,28 @@ public static JObject RunWithJson(JObject json) /// The name of the targeted method /// Arguments of the method /// Returns a json with the engine state after executing the script - public static JObject Run(string path, string method, JArray parameters) + public static JObject Run(SmartContractTest smartContractTest) { - if (!File.Exists(path)) + if (!File.Exists(smartContractTest.nefPath)) { return BuildJsonException("File doesn't exists"); } - if (Path.GetExtension(path).ToLowerInvariant() != ".nef") + if (Path.GetExtension(smartContractTest.nefPath).ToLowerInvariant() != ".nef") { return BuildJsonException("Invalid file. A .nef file required."); } try { - Engine.Instance.SetTestEngine(path); - var stackParams = GetStackItemParameters(parameters); - return Engine.Instance.Run(method, stackParams); + Engine.Instance.SetTestEngine(smartContractTest.nefPath); + + if (smartContractTest.storage.Count > 0) + { + Engine.Instance.SetStorage(smartContractTest.storage); + } + + var stackParams = GetStackItemParameters(smartContractTest.methodParameters); + return Engine.Instance.Run(smartContractTest.methodName, stackParams); } catch (Exception e) { @@ -164,6 +177,40 @@ public static JObject Run(string path, string method, JArray parameters) } } + /// + /// Converts the data in a json array to a dictionary of StackItem + /// + /// json array with the map values to be converted + /// Returns the built StackItem dictionary + private static Dictionary GetStorageFromJson(JObject jsonStorage) + { + if (!(jsonStorage is JArray storage)) + { + throw new Exception("Expecting an array object in 'storage'"); + } + + var missingFieldMessage = "Missing field '{0}'"; + var items = new Dictionary(); + foreach (var pair in storage) + { + if (!pair.ContainsProperty("key")) + { + throw new Exception(string.Format(missingFieldMessage, "key")); + } + + if (!pair.ContainsProperty("value")) + { + throw new Exception(string.Format(missingFieldMessage, "value")); + } + + var key = (PrimitiveType)ContractParameter.FromJson(pair["key"]).ToStackItem(); + var value = ContractParameter.FromJson(pair["value"]).ToStackItem(); + items[key] = value; + } + + return items; + } + /// /// Converts the data in a json array to an array of StackItem /// diff --git a/src/TestEngine/SmartContractTest.cs b/src/TestEngine/SmartContractTest.cs new file mode 100644 index 000000000..f7f4313b3 --- /dev/null +++ b/src/TestEngine/SmartContractTest.cs @@ -0,0 +1,22 @@ +using Neo.IO.Json; +using Neo.VM.Types; +using System.Collections.Generic; + +namespace Neo.TestingEngine +{ + public class SmartContractTest + { + public string nefPath; + public string methodName; + public JArray methodParameters; + public Dictionary storage = new Dictionary(); + + public SmartContractTest(string path, string method, JArray parameters) + { + nefPath = path; + methodName = method; + methodParameters = parameters; + storage.Clear(); + } + } +} diff --git a/src/TestEngine/TestUtils/TestDataCache.cs b/src/TestEngine/TestUtils/TestDataCache.cs index 50646312b..c561ed17f 100644 --- a/src/TestEngine/TestUtils/TestDataCache.cs +++ b/src/TestEngine/TestUtils/TestDataCache.cs @@ -62,5 +62,13 @@ public void Clear() { dic.Clear(); } + + /// + /// Include a new value to the storage for unit test + /// + public void AddForTest(TKey key, TValue value) + { + AddInternal(key, value); + } } } diff --git a/tests/TestEngine.UnitTests/UnitTest_Invoke.cs b/tests/TestEngine.UnitTests/UnitTest_Invoke.cs index 15509a255..30783cc06 100644 --- a/tests/TestEngine.UnitTests/UnitTest_Invoke.cs +++ b/tests/TestEngine.UnitTests/UnitTest_Invoke.cs @@ -3,6 +3,7 @@ using Neo.TestingEngine; using Neo.VM; using Neo.VM.Types; +using System.Collections.Generic; using System.IO; using Compiler = Neo.Compiler.Program; @@ -271,5 +272,47 @@ public void Test_Json_With_Parameters() Assert.IsTrue(resultStack[0].ContainsProperty("value")); Assert.AreEqual(resultStack[0]["value"].AsString(), wantresult.ToJson()["value"].AsString()); } + + [TestMethod] + public void Test_Json_With_Storage() + { + StackItem arguments = 16; + PrimitiveType key = "example"; + StackItem value = 123; + + Map storage = new Map() + { + [key] = value + }; + + var json = new JObject(); + json["path"] = "./TestClasses/Contract1.nef"; + json["method"] = "testArgs1"; + json["arguments"] = new JArray() { arguments.ToParameter().ToJson() }; + json["storage"] = storage.ToParameter().ToJson()["value"]; + + var args = new string[] { + json.AsString() + }; + var result = Program.Run(args); + + // search in the storage + Assert.IsTrue(result.ContainsProperty("storage")); + Assert.IsInstanceOfType(result["storage"], typeof(JArray)); + + storage[key] = value.GetSpan().ToArray(); + var storageArray = result["storage"] as JArray; + + var contains = false; + foreach (var pair in storageArray) + { + if (pair.AsString() == storage.ToJson()["value"].AsString()) + { + contains = true; + break; + } + } + Assert.IsTrue(contains); + } } } From b361346b6d371d39c36ec6259110c744d9b4e53a Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Thu, 29 Oct 2020 12:57:01 -0300 Subject: [PATCH 13/77] include other smart contracts in the TestEngine arguments --- src/TestEngine/Engine.cs | 13 +++ src/TestEngine/Program.cs | 63 +++++++++-- src/TestEngine/SmartContractTest.cs | 2 + src/TestEngine/TestContract.cs | 12 ++ src/TestEngine/TestEngine.csproj | 2 +- .../TestClasses/Contract_ContractCall.cs | 24 ++++ .../TestEngine.UnitTests.csproj | 4 + .../UnitTest_ContractCall.cs | 105 ++++++++++++++++++ tests/TestEngine.UnitTests/UnitTest_Invoke.cs | 1 - 9 files changed, 215 insertions(+), 11 deletions(-) create mode 100644 src/TestEngine/TestContract.cs create mode 100644 tests/TestEngine.UnitTests/TestClasses/Contract_ContractCall.cs create mode 100644 tests/TestEngine.UnitTests/UnitTest_ContractCall.cs diff --git a/src/TestEngine/Engine.cs b/src/TestEngine/Engine.cs index 5c2ce13c5..7bf17074d 100644 --- a/src/TestEngine/Engine.cs +++ b/src/TestEngine/Engine.cs @@ -50,6 +50,19 @@ public void SetTestEngine(string path) }); } + public void AddSmartContract(string path) + { + var builtScript = engine.Build(path); + if (UInt160.TryParse(builtScript.finalABI["hash"].AsString(), out var hash)) + { + engine.Snapshot.Contracts.Add(hash, new Ledger.ContractState() + { + Script = builtScript.finalNEF, + Manifest = ContractManifest.FromJson(JObject.Parse(builtScript.finalManifest)), + }); + } + } + public void SetStorage(Dictionary storage) { foreach (var data in storage) diff --git a/src/TestEngine/Program.cs b/src/TestEngine/Program.cs index 7faee797a..3c05bad1e 100644 --- a/src/TestEngine/Program.cs +++ b/src/TestEngine/Program.cs @@ -133,6 +133,11 @@ public static JObject RunWithJson(JObject json) { smartContractTestCase.storage = GetStorageFromJson(json["storage"]); } + + if (json.ContainsProperty("contracts")) + { + smartContractTestCase.contracts = GetContractsFromJson(json["contracts"]); + } return Run(smartContractTestCase); } catch (Exception e) @@ -150,23 +155,20 @@ public static JObject RunWithJson(JObject json) /// Returns a json with the engine state after executing the script public static JObject Run(SmartContractTest smartContractTest) { - if (!File.Exists(smartContractTest.nefPath)) - { - return BuildJsonException("File doesn't exists"); - } - if (Path.GetExtension(smartContractTest.nefPath).ToLowerInvariant() != ".nef") - { - return BuildJsonException("Invalid file. A .nef file required."); - } - try { + IsValidNefPath(smartContractTest.nefPath); + Engine.Instance.SetTestEngine(smartContractTest.nefPath); if (smartContractTest.storage.Count > 0) { Engine.Instance.SetStorage(smartContractTest.storage); } + foreach (var contract in smartContractTest.contracts) + { + Engine.Instance.AddSmartContract(contract.nefPath); + } var stackParams = GetStackItemParameters(smartContractTest.methodParameters); return Engine.Instance.Run(smartContractTest.methodName, stackParams); @@ -211,6 +213,34 @@ private static Dictionary GetStorageFromJson(JObject j return items; } + /// + /// Converts the data in a json array to a list of test smart contracts + /// + /// json array with the contracts' paths to be converted + /// Returns a list of smart contracts for test + private static List GetContractsFromJson(JObject jsonContracts) + { + if (!(jsonContracts is JArray contracts)) + { + throw new Exception("Expecting an array object in 'contracts'"); + } + + var items = new List(); + foreach (var pair in contracts) + { + if (!pair.ContainsProperty("nef")) + { + throw new Exception("Missing field 'nef'"); + } + + var path = pair["nef"].AsString(); + IsValidNefPath(path); + items.Add(new TestContract(path)); + } + + return items; + } + /// /// Converts the data in a json array to an array of StackItem /// @@ -245,6 +275,21 @@ private static StackItem[] GetStackItemParameters(JArray parameters) return items.ToArray(); } + private static bool IsValidNefPath(string path) + { + if (!File.Exists(path)) + { + throw new Exception("File doesn't exists"); + } + + if (Path.GetExtension(path).ToLowerInvariant() != ".nef") + { + throw new Exception("Invalid file. A .nef file required."); + } + + return true; + } + private static JObject BuildJsonException(string message) { var json = new JObject(); diff --git a/src/TestEngine/SmartContractTest.cs b/src/TestEngine/SmartContractTest.cs index f7f4313b3..61eb20291 100644 --- a/src/TestEngine/SmartContractTest.cs +++ b/src/TestEngine/SmartContractTest.cs @@ -10,6 +10,7 @@ public class SmartContractTest public string methodName; public JArray methodParameters; public Dictionary storage = new Dictionary(); + public List contracts = new List(); public SmartContractTest(string path, string method, JArray parameters) { @@ -17,6 +18,7 @@ public SmartContractTest(string path, string method, JArray parameters) methodName = method; methodParameters = parameters; storage.Clear(); + contracts.Clear(); } } } diff --git a/src/TestEngine/TestContract.cs b/src/TestEngine/TestContract.cs new file mode 100644 index 000000000..c68de708b --- /dev/null +++ b/src/TestEngine/TestContract.cs @@ -0,0 +1,12 @@ +namespace Neo.TestingEngine +{ + public class TestContract + { + internal string nefPath; + + public TestContract(string path) + { + nefPath = path; + } + } +} diff --git a/src/TestEngine/TestEngine.csproj b/src/TestEngine/TestEngine.csproj index f5fb41556..6d7ecfc61 100644 --- a/src/TestEngine/TestEngine.csproj +++ b/src/TestEngine/TestEngine.csproj @@ -12,7 +12,7 @@ MIT git https://github.com/neo-project/neo-devpack-dotnet.git - Neo.TestEngine + Neo.TestingEngine The Neo Project TestingEngine TestingEngine diff --git a/tests/TestEngine.UnitTests/TestClasses/Contract_ContractCall.cs b/tests/TestEngine.UnitTests/TestClasses/Contract_ContractCall.cs new file mode 100644 index 000000000..5c7a18776 --- /dev/null +++ b/tests/TestEngine.UnitTests/TestClasses/Contract_ContractCall.cs @@ -0,0 +1,24 @@ +using Neo.SmartContract.Framework; + +namespace Neo.Compiler.MSIL.UnitTests.TestClasses +{ + [Contract("9458d707d90e8e2838e488da0386194a0491bcb9")] + public class Contract1 + { + public static extern byte[] testArgs1(byte a); + public static extern void testVoid(); + } + + public class Contract_ContractCall : SmartContract.Framework.SmartContract + { + public static byte[] testContractCall() + { + return Contract1.testArgs1((byte)4); + } + + public static void testContractCallVoid() + { + Contract1.testVoid(); + } + } +} diff --git a/tests/TestEngine.UnitTests/TestEngine.UnitTests.csproj b/tests/TestEngine.UnitTests/TestEngine.UnitTests.csproj index e56142adb..e34c77c5e 100644 --- a/tests/TestEngine.UnitTests/TestEngine.UnitTests.csproj +++ b/tests/TestEngine.UnitTests/TestEngine.UnitTests.csproj @@ -9,6 +9,7 @@ + @@ -18,6 +19,9 @@ PreserveNewest + + PreserveNewest + diff --git a/tests/TestEngine.UnitTests/UnitTest_ContractCall.cs b/tests/TestEngine.UnitTests/UnitTest_ContractCall.cs new file mode 100644 index 000000000..34d47f841 --- /dev/null +++ b/tests/TestEngine.UnitTests/UnitTest_ContractCall.cs @@ -0,0 +1,105 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO.Json; +using Neo.TestingEngine; +using Neo.VM; +using Neo.VM.Types; +using System.IO; +using Compiler = Neo.Compiler.Program; + +namespace TestEngine.UnitTests +{ + [TestClass] + public class UnitTest_ContractCall + { + [TestInitialize] + public void Init() + { + string path = Directory.GetCurrentDirectory(); + var option = new Compiler.Options() + { + File = path + "/TestClasses/Contract1.cs" + }; + Compiler.Compile(option); + + option.File = path + "/TestClasses/Contract_ContractCall.cs"; + Compiler.Compile(option); + + //Compile changes the path, reseting so that other UT won't break + Directory.SetCurrentDirectory(path); + Engine.Instance.Reset(); + } + + [TestMethod] + public void Test_Json() + { + var contract = new JObject(); + contract["nef"] = "./TestClasses/Contract1.nef"; + + var json = new JObject(); + json["path"] = "./TestClasses/Contract_ContractCall.nef"; + json["method"] = "testContractCall"; + json["contracts"] = new JArray() + { + contract + }; + + var args = new string[] { + json.AsString() + }; + var result = Program.Run(args); + + // mustn't have errors + Assert.IsTrue(result.ContainsProperty("error")); + Assert.IsNull(result["error"]); + + // test state + Assert.IsTrue(result.ContainsProperty("vm_state")); + Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + + // test result + StackItem wantresult = new byte[] { 1, 2, 3, 4 }; + Assert.IsTrue(result.ContainsProperty("result_stack")); + Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + + var resultStack = result["result_stack"] as JArray; + Assert.IsTrue(resultStack.Count == 1); + Assert.IsTrue(resultStack[0].ContainsProperty("value")); + Assert.AreEqual(resultStack[0]["value"].AsString(), wantresult.ToJson()["value"].AsString()); + } + + [TestMethod] + public void Test_ContractCall_Void() + { + var contract = new JObject(); + contract["nef"] = "./TestClasses/Contract1.nef"; + + var json = new JObject(); + json["path"] = "./TestClasses/Contract_ContractCall.nef"; + json["method"] = "testContractCallVoid"; + json["contracts"] = new JArray() + { + contract + }; + + var args = new string[] { + json.AsString() + }; + var result = Program.Run(args); + + // mustn't have errors + Assert.IsTrue(result.ContainsProperty("error")); + Assert.IsNull(result["error"]); + + // test state + Assert.IsTrue(result.ContainsProperty("vm_state")); + Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + + // test result + Assert.IsTrue(result.ContainsProperty("result_stack")); + Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + + var resultStack = result["result_stack"] as JArray; + Assert.AreEqual(0, resultStack.Count); + } + } +} diff --git a/tests/TestEngine.UnitTests/UnitTest_Invoke.cs b/tests/TestEngine.UnitTests/UnitTest_Invoke.cs index 30783cc06..c27d8b676 100644 --- a/tests/TestEngine.UnitTests/UnitTest_Invoke.cs +++ b/tests/TestEngine.UnitTests/UnitTest_Invoke.cs @@ -3,7 +3,6 @@ using Neo.TestingEngine; using Neo.VM; using Neo.VM.Types; -using System.Collections.Generic; using System.IO; using Compiler = Neo.Compiler.Program; From 850bd5e20b8648d1d78ee5d6b5d298db041a8799 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 16 Nov 2020 16:43:50 -0300 Subject: [PATCH 14/77] fix assembly conflicts --- src/TestEngine/TestEngine.csproj | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/TestEngine/TestEngine.csproj b/src/TestEngine/TestEngine.csproj index 6d7ecfc61..d31f2757a 100644 --- a/src/TestEngine/TestEngine.csproj +++ b/src/TestEngine/TestEngine.csproj @@ -18,8 +18,27 @@ TestingEngine + + + + + + + + + neo + + + + From 6c979b9e500cdd200b0a3a412cdced063f461bba Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Wed, 4 Nov 2020 14:46:08 -0300 Subject: [PATCH 15/77] Increase block height in the TestEngine --- neo-devpack-dotnet.sln | 2 +- src/TestEngine/Engine.cs | 84 +++++++++++++++---- src/TestEngine/Program.cs | 15 +++- src/TestEngine/SmartContractTest.cs | 1 + src/TestEngine/TestUtils/TestAccount.cs | 33 ++++++++ .../TestEngine/TestUtils}/TestBlockchain.cs | 2 +- .../TestUtils/TestConsensusContext.cs | 40 +++++++++ src/TestEngine/TestUtils/TestDataCache.cs | 8 ++ src/TestEngine/TestUtils/TestMetaDataCache.cs | 9 +- src/TestEngine/TestUtils/TestSnapshot.cs | 20 +++++ src/TestEngine/TestUtils/TestWallet.cs | 76 +++++++++++++++++ .../UnitTest_BlockHeight.cs | 55 ++++++++++++ 12 files changed, 324 insertions(+), 21 deletions(-) create mode 100644 src/TestEngine/TestUtils/TestAccount.cs rename {tests/Neo.SmartContract.Framework.UnitTests => src/TestEngine/TestUtils}/TestBlockchain.cs (86%) create mode 100644 src/TestEngine/TestUtils/TestConsensusContext.cs create mode 100644 src/TestEngine/TestUtils/TestWallet.cs create mode 100644 tests/TestEngine.UnitTests/UnitTest_BlockHeight.cs diff --git a/neo-devpack-dotnet.sln b/neo-devpack-dotnet.sln index ca3e29413..bee1e22f5 100644 --- a/neo-devpack-dotnet.sln +++ b/neo-devpack-dotnet.sln @@ -31,7 +31,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Template.NEP5.UnitTests", " EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestEngine", "src\TestEngine\TestEngine.csproj", "{39347E90-FC12-4018-8F22-828F0F1B2F7D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestEngine.UnitTests", "tests\TestEngine.UnitTests\TestEngine.UnitTests.csproj", "{FFDC189F-2F72-4542-B28B-8EFA0F28E3CF}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestEngine.UnitTests", "tests\TestEngine.UnitTests\TestEngine.UnitTests.csproj", "{FFDC189F-2F72-4542-B28B-8EFA0F28E3CF}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/src/TestEngine/Engine.cs b/src/TestEngine/Engine.cs index 7bf17074d..a4b5e2e45 100644 --- a/src/TestEngine/Engine.cs +++ b/src/TestEngine/Engine.cs @@ -6,6 +6,7 @@ using Neo.SmartContract.Manifest; using Neo.VM; using Neo.VM.Types; +using System; using System.Collections.Generic; namespace Neo.TestingEngine @@ -33,6 +34,8 @@ private Engine() Reset(); } + public int BlockCount => ((TestDataCache)engine.Snapshot.Blocks).Count(); + public void Reset() { engine = SetupNativeContracts(); @@ -63,6 +66,34 @@ public void AddSmartContract(string path) } } + public void IncreaseBlockCount(uint newHeight) + { + var snapshot = (TestSnapshot)engine.Snapshot; + var blocks = (TestDataCache)snapshot.Blocks; + Block newBlock; + Block lastBlock = null; + if (blocks.Count() == 0) + { + newBlock = Blockchain.GenesisBlock; + } + else + { + newBlock = CreateBlock(); + } + + while (blocks.Count() < newHeight) + { + var hash = newBlock.Hash; + var trim = newBlock.Trim(); + blocks.AddForTest(hash, trim); + lastBlock = newBlock; + newBlock = CreateBlock(); + } + + var index = (uint)(blocks.Count() - 1); + snapshot.SetCurrentBlockHash(index, lastBlock.Hash); + } + public void SetStorage(Dictionary storage) { foreach (var data in storage) @@ -87,21 +118,8 @@ public JObject Run(string method, StackItem[] args) private TestEngine SetupNativeContracts() { - var block = new Block() - { - Index = 0, - ConsensusData = new ConsensusData(), - Transactions = new Transaction[0], - Witness = new Witness() - { - InvocationScript = new byte[0], - VerificationScript = Contract.CreateSignatureRedeemScript(ECPoint.FromBytes(PubKey, ECCurve.Secp256k1)) - }, - NextConsensus = UInt160.Zero, - MerkleRoot = UInt256.Zero, - PrevHash = UInt256.Zero - }; - + SetConsensus(); + var block = Blockchain.GenesisBlock; TestEngine engine = new TestEngine(TriggerType.Application, block); ((TestSnapshot)engine.Snapshot).SetPersistingBlock(block); @@ -117,6 +135,42 @@ private TestEngine SetupNativeContracts() return engine; } + private void SetConsensus() + { + var _ = TestBlockchain.TheNeoSystem; + var store = Blockchain.Singleton.Store; + var block = Blockchain.GenesisBlock; + } + + private Block CreateBlock() + { + var blocks = engine.Snapshot.Blocks.Seek().GetEnumerator(); + while (blocks.MoveNext()) + { } + + var (blockHash, trimmedBlock) = blocks.Current; + if (blockHash == null) + { + (blockHash, trimmedBlock) = (Blockchain.GenesisBlock.Hash, Blockchain.GenesisBlock.Trim()); + } + + return new Block() + { + Index = trimmedBlock.Index + 1, + Timestamp = trimmedBlock.Timestamp + Blockchain.MillisecondsPerBlock, + ConsensusData = new ConsensusData(), + Transactions = new Transaction[0], + Witness = new Witness() + { + InvocationScript = new byte[0], + VerificationScript = Contract.CreateSignatureRedeemScript(ECPoint.FromBytes(PubKey, ECCurve.Secp256k1)) + }, + NextConsensus = trimmedBlock.NextConsensus, + MerkleRoot = trimmedBlock.MerkleRoot, + PrevHash = blockHash + }; + } + private static byte[] HexString2Bytes(string str) { if (str.IndexOf("0x") == 0) diff --git a/src/TestEngine/Program.cs b/src/TestEngine/Program.cs index 3c05bad1e..453fcca34 100644 --- a/src/TestEngine/Program.cs +++ b/src/TestEngine/Program.cs @@ -138,6 +138,11 @@ public static JObject RunWithJson(JObject json) { smartContractTestCase.contracts = GetContractsFromJson(json["contracts"]); } + + if (json.ContainsProperty("height")) + { + smartContractTestCase.currentHeight = uint.Parse(json["height"].AsString()); + } return Run(smartContractTestCase); } catch (Exception e) @@ -149,9 +154,7 @@ public static JObject RunWithJson(JObject json) /// /// Runs the given method from a nef script /// - /// Absolute path of the script - /// The name of the targeted method - /// Arguments of the method + /// Object with the informations about the test case /// Returns a json with the engine state after executing the script public static JObject Run(SmartContractTest smartContractTest) { @@ -165,11 +168,17 @@ public static JObject Run(SmartContractTest smartContractTest) { Engine.Instance.SetStorage(smartContractTest.storage); } + foreach (var contract in smartContractTest.contracts) { Engine.Instance.AddSmartContract(contract.nefPath); } + if (smartContractTest.currentHeight > 0) + { + Engine.Instance.IncreaseBlockCount(smartContractTest.currentHeight); + } + var stackParams = GetStackItemParameters(smartContractTest.methodParameters); return Engine.Instance.Run(smartContractTest.methodName, stackParams); } diff --git a/src/TestEngine/SmartContractTest.cs b/src/TestEngine/SmartContractTest.cs index 61eb20291..a89fdda9b 100644 --- a/src/TestEngine/SmartContractTest.cs +++ b/src/TestEngine/SmartContractTest.cs @@ -11,6 +11,7 @@ public class SmartContractTest public JArray methodParameters; public Dictionary storage = new Dictionary(); public List contracts = new List(); + public uint currentHeight = 0; public SmartContractTest(string path, string method, JArray parameters) { diff --git a/src/TestEngine/TestUtils/TestAccount.cs b/src/TestEngine/TestUtils/TestAccount.cs new file mode 100644 index 000000000..c9fdda8f7 --- /dev/null +++ b/src/TestEngine/TestUtils/TestAccount.cs @@ -0,0 +1,33 @@ +using Neo.Wallets; + +namespace Neo.TestingEngine +{ + class TestAccount : WalletAccount + { + public override bool HasKey => this.key != null; + + private byte[] privateKey; + private UInt160 scriptHash; + private KeyPair key = null; + + public TestAccount(UInt160 scriptHash, byte[] privKey = null) : base(scriptHash) + { + if (privKey != null) + { + this.privateKey = privKey; + } + else + { + this.privateKey = new byte[32]; + } + + this.scriptHash = scriptHash; + this.key = new KeyPair(this.privateKey); + } + + public override KeyPair GetKey() + { + return this.key; + } + } +} diff --git a/tests/Neo.SmartContract.Framework.UnitTests/TestBlockchain.cs b/src/TestEngine/TestUtils/TestBlockchain.cs similarity index 86% rename from tests/Neo.SmartContract.Framework.UnitTests/TestBlockchain.cs rename to src/TestEngine/TestUtils/TestBlockchain.cs index 1a38d0089..5fa018354 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/TestBlockchain.cs +++ b/src/TestEngine/TestUtils/TestBlockchain.cs @@ -1,6 +1,6 @@ using Neo.Ledger; -namespace Neo.SmartContract.Framework.UnitTests +namespace Neo.TestingEngine { public static class TestBlockchain { diff --git a/src/TestEngine/TestUtils/TestConsensusContext.cs b/src/TestEngine/TestUtils/TestConsensusContext.cs new file mode 100644 index 000000000..d69c7fb11 --- /dev/null +++ b/src/TestEngine/TestUtils/TestConsensusContext.cs @@ -0,0 +1,40 @@ +using Neo.Consensus; +using Neo.Cryptography.ECC; +using Neo.Network.P2P.Payloads; +using Neo.Persistence; +using Neo.SmartContract; +using Neo.Wallets; +using System.Collections.Generic; +using System.Linq; + +namespace Neo.TestingEngine +{ + public class TestConsensusContext : ConsensusContext + { + public TestConsensusContext(ECPoint[] validators, Wallet wallet, IStore store) : base(wallet, store) + { + this.Validators = validators; + this.CommitPayloads = new ConsensusPayload[validators.Length]; + } + + public void SetBlock(Block block) + { + this.Block = block; + } + + public Block CreateBlock() + { + EnsureHeader(); + Contract contract = Contract.CreateMultiSigContract(M, Validators); + ContractParametersContext sc = new ContractParametersContext(Block); + + var witness = new Witness(); + witness.InvocationScript = contract.Script; + witness.VerificationScript = new byte[0]; + Block.Witness = witness; + Block.Transactions = TransactionHashes.Select(p => Transactions[p]).ToArray(); + return Block; + } + + } +} diff --git a/src/TestEngine/TestUtils/TestDataCache.cs b/src/TestEngine/TestUtils/TestDataCache.cs index c561ed17f..68d7f12b9 100644 --- a/src/TestEngine/TestUtils/TestDataCache.cs +++ b/src/TestEngine/TestUtils/TestDataCache.cs @@ -63,6 +63,14 @@ public void Clear() dic.Clear(); } + /// + /// Gets the size of the storage for unit test + /// + public int Count() + { + return dic.Count; + } + /// /// Include a new value to the storage for unit test /// diff --git a/src/TestEngine/TestUtils/TestMetaDataCache.cs b/src/TestEngine/TestUtils/TestMetaDataCache.cs index 6523d54a3..cf5763081 100644 --- a/src/TestEngine/TestUtils/TestMetaDataCache.cs +++ b/src/TestEngine/TestUtils/TestMetaDataCache.cs @@ -5,6 +5,7 @@ namespace Neo.TestingEngine { public class TestMetaDataCache : MetaDataCache where T : class, ICloneable, ISerializable, new() { + private T metadata = null; public TestMetaDataCache() : base(null) { @@ -16,11 +17,17 @@ protected override void AddInternal(T item) protected override T TryGetInternal() { - return null; + return metadata; } protected override void UpdateInternal(T item) { + metadata = item; + } + + public void Update(T item) + { + UpdateInternal(item); } } } diff --git a/src/TestEngine/TestUtils/TestSnapshot.cs b/src/TestEngine/TestUtils/TestSnapshot.cs index db339dfa4..029fedd94 100644 --- a/src/TestEngine/TestUtils/TestSnapshot.cs +++ b/src/TestEngine/TestUtils/TestSnapshot.cs @@ -49,5 +49,25 @@ public void ClearStorage() { ((TestDataCache)this._Storages).Clear(); } + + public void SetCurrentBlockHash(uint index, UInt256 hash) + { + if (hash != null && Blocks is TestDataCache blocks) + { + var blocksCount = blocks.Count(); + + if (index > blocksCount) + { + index = (uint)blocksCount; + } + + var hashIndex = new HashIndexState() + { + Hash = hash, + Index = index + }; + ((TestMetaDataCache)BlockHashIndex).Update(hashIndex); + } + } } } diff --git a/src/TestEngine/TestUtils/TestWallet.cs b/src/TestEngine/TestUtils/TestWallet.cs new file mode 100644 index 000000000..580b7016e --- /dev/null +++ b/src/TestEngine/TestUtils/TestWallet.cs @@ -0,0 +1,76 @@ +using Neo.SmartContract; +using Neo.Wallets; +using Neo.Wallets.NEP6; +using System; +using System.Collections.Generic; + +namespace Neo.TestingEngine +{ + public class TestWallet : NEP6Wallet + { + private Dictionary accounts; + + public TestWallet(UInt160 scriptHash) : base("", "TestWallet") + { + this.accounts = new Dictionary() + { + { scriptHash, new TestAccount(scriptHash) } + }; + } + + public override bool ChangePassword(string oldPassword, string newPassword) + { + return false; + } + + public override bool Contains(UInt160 scriptHash) + { + return this.accounts.ContainsKey(scriptHash); + } + + public override WalletAccount CreateAccount(byte[] privateKey) + { + throw new NotImplementedException(); + } + + public override WalletAccount CreateAccount(Contract contract, KeyPair key = null) + { + throw new NotImplementedException(); + } + + public override WalletAccount CreateAccount(UInt160 scriptHash) + { + var account = new TestAccount(scriptHash); + this.accounts[scriptHash] = account; + return account; + } + + public override bool DeleteAccount(UInt160 scriptHash) + { + if (!this.accounts.ContainsKey(scriptHash)) + { + return false; + } + return accounts.Remove(scriptHash); + } + + public override WalletAccount GetAccount(UInt160 scriptHash) + { + if (!this.accounts.ContainsKey(scriptHash)) + { + return null; + } + return accounts[scriptHash]; + } + + public override IEnumerable GetAccounts() + { + return this.accounts.Values; + } + + public override bool VerifyPassword(string password) + { + return true; + } + } +} diff --git a/tests/TestEngine.UnitTests/UnitTest_BlockHeight.cs b/tests/TestEngine.UnitTests/UnitTest_BlockHeight.cs new file mode 100644 index 000000000..fd57b525a --- /dev/null +++ b/tests/TestEngine.UnitTests/UnitTest_BlockHeight.cs @@ -0,0 +1,55 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO.Json; +using Neo.TestingEngine; +using Neo.VM; +using Neo.VM.Types; +using System.IO; +using Compiler = Neo.Compiler.Program; + +namespace TestEngine.UnitTests +{ + [TestClass] + public class UnitTest_BlockHeight + { + [TestInitialize] + public void Init() + { + string path = Directory.GetCurrentDirectory(); + var option = new Compiler.Options() + { + File = path + "/TestClasses/Contract1.cs" + }; + Compiler.Compile(option); + + //Compile changes the path, reseting so that other UT won't break + Directory.SetCurrentDirectory(path); + Engine.Instance.Reset(); + } + + [TestMethod] + public void Test_Json() + { + var height = 16; + + var json = new JObject(); + json["path"] = "./TestClasses/Contract1.nef"; + json["method"] = "testVoid"; + json["height"] = height; + + var args = new string[] { + json.AsString() + }; + var result = Program.Run(args); + + // mustn't have errors + Assert.IsTrue(result.ContainsProperty("error")); + Assert.IsNull(result["error"]); + + // test state + Assert.IsTrue(result.ContainsProperty("vm_state")); + Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + + Assert.AreEqual(height, Engine.Instance.BlockCount); + } + } +} From 18e4ee924c7892c58e4686f84ec05aa366e786dc Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 23 Nov 2020 13:40:46 -0300 Subject: [PATCH 16/77] fix unit test --- tests/Neo.SmartContract.Framework.UnitTests/UIntTest.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Neo.SmartContract.Framework.UnitTests/UIntTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/UIntTest.cs index 6a9974ed2..c1f594579 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/UIntTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/UIntTest.cs @@ -1,6 +1,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; using Neo.IO; +using Neo.TestingEngine; namespace Neo.SmartContract.Framework.UnitTests { From 2a5a9f7fc359888e68b4dc355e9a7f4b87a6b738 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Tue, 24 Nov 2020 16:34:13 -0300 Subject: [PATCH 17/77] Boa-263 Include CheckWitness in the TestEngine --- src/TestEngine/Engine.cs | 24 +++- src/TestEngine/Program.cs | 15 ++- src/TestEngine/SmartContractTest.cs | 10 +- .../TestClasses/Contract_CheckWitness.cs | 13 +++ .../TestEngine.UnitTests.csproj | 19 +++ .../UnitTest_CheckWitness.cs | 109 ++++++++++++++++++ 6 files changed, 179 insertions(+), 11 deletions(-) create mode 100644 tests/TestEngine.UnitTests/TestClasses/Contract_CheckWitness.cs create mode 100644 tests/TestEngine.UnitTests/UnitTest_CheckWitness.cs diff --git a/src/TestEngine/Engine.cs b/src/TestEngine/Engine.cs index a4b5e2e45..f39e7afbf 100644 --- a/src/TestEngine/Engine.cs +++ b/src/TestEngine/Engine.cs @@ -8,6 +8,7 @@ using Neo.VM.Types; using System; using System.Collections.Generic; +using System.Linq; namespace Neo.TestingEngine { @@ -27,6 +28,7 @@ public static Engine Instance } private TestEngine engine = null; + private Transaction currentTx = null; private byte[] PubKey => HexString2Bytes("03ea01cb94bdaf0cd1c01b159d474f9604f4af35a3e2196f6bdfdb33b2aa4961fa"); private Engine() @@ -110,6 +112,11 @@ public void SetStorage(Dictionary storage) } } + public void SetSigners(UInt160[] signerAccounts) + { + currentTx.Signers = signerAccounts.Select(p => new Signer() { Account = p, Scopes = WitnessScope.CalledByEntry }).ToArray(); + } + public JObject Run(string method, StackItem[] args) { engine.GetMethod(method).RunEx(args); @@ -119,9 +126,20 @@ public JObject Run(string method, StackItem[] args) private TestEngine SetupNativeContracts() { SetConsensus(); - var block = Blockchain.GenesisBlock; - TestEngine engine = new TestEngine(TriggerType.Application, block); - ((TestSnapshot)engine.Snapshot).SetPersistingBlock(block); + currentTx = new Transaction() + { + Attributes = new TransactionAttribute[0], + Script = new byte[0], + Signers = new Signer[] { new Signer() { Account = UInt160.Zero } }, + Witnesses = new Witness[0], + NetworkFee = 1, + Nonce = 2, + SystemFee = 3, + ValidUntilBlock = 4, + Version = 5 + }; + TestEngine engine = new TestEngine(TriggerType.Application, currentTx); + ((TestSnapshot)engine.Snapshot).SetPersistingBlock(Blockchain.GenesisBlock); using (var script = new ScriptBuilder()) { diff --git a/src/TestEngine/Program.cs b/src/TestEngine/Program.cs index 453fcca34..8d02c1d51 100644 --- a/src/TestEngine/Program.cs +++ b/src/TestEngine/Program.cs @@ -143,6 +143,11 @@ public static JObject RunWithJson(JObject json) { smartContractTestCase.currentHeight = uint.Parse(json["height"].AsString()); } + + if (json.ContainsProperty("signerAccounts") && json["signerAccounts"] is JArray accounts) + { + smartContractTestCase.signers = accounts.Select(p => UInt160.Parse(p.AsString())).ToArray(); + } return Run(smartContractTestCase); } catch (Exception e) @@ -169,16 +174,18 @@ public static JObject Run(SmartContractTest smartContractTest) Engine.Instance.SetStorage(smartContractTest.storage); } - foreach (var contract in smartContractTest.contracts) + if (smartContractTest.currentHeight > 0) { - Engine.Instance.AddSmartContract(contract.nefPath); + Engine.Instance.IncreaseBlockCount(smartContractTest.currentHeight); } - if (smartContractTest.currentHeight > 0) + foreach (var contract in smartContractTest.contracts) { - Engine.Instance.IncreaseBlockCount(smartContractTest.currentHeight); + Engine.Instance.AddSmartContract(contract.nefPath); } + Engine.Instance.SetSigners(smartContractTest.signers); + var stackParams = GetStackItemParameters(smartContractTest.methodParameters); return Engine.Instance.Run(smartContractTest.methodName, stackParams); } diff --git a/src/TestEngine/SmartContractTest.cs b/src/TestEngine/SmartContractTest.cs index a89fdda9b..fd73b93f7 100644 --- a/src/TestEngine/SmartContractTest.cs +++ b/src/TestEngine/SmartContractTest.cs @@ -9,17 +9,19 @@ public class SmartContractTest public string nefPath; public string methodName; public JArray methodParameters; - public Dictionary storage = new Dictionary(); - public List contracts = new List(); + public Dictionary storage; + public List contracts; public uint currentHeight = 0; + public UInt160[] signers; public SmartContractTest(string path, string method, JArray parameters) { nefPath = path; methodName = method; methodParameters = parameters; - storage.Clear(); - contracts.Clear(); + storage = new Dictionary(); + contracts = new List(); + signers = new UInt160[] { }; } } } diff --git a/tests/TestEngine.UnitTests/TestClasses/Contract_CheckWitness.cs b/tests/TestEngine.UnitTests/TestClasses/Contract_CheckWitness.cs new file mode 100644 index 000000000..19e921246 --- /dev/null +++ b/tests/TestEngine.UnitTests/TestClasses/Contract_CheckWitness.cs @@ -0,0 +1,13 @@ +using Neo; +using Neo.SmartContract.Framework.Services.Neo; + +namespace Neo.Compiler.MSIL.UnitTests.TestClasses +{ + public class Contract_CheckWitness : SmartContract.Framework.SmartContract + { + public static bool testWitness(UInt160 signature) + { + return Runtime.CheckWitness(signature); + } + } +} diff --git a/tests/TestEngine.UnitTests/TestEngine.UnitTests.csproj b/tests/TestEngine.UnitTests/TestEngine.UnitTests.csproj index e34c77c5e..9f9e300e7 100644 --- a/tests/TestEngine.UnitTests/TestEngine.UnitTests.csproj +++ b/tests/TestEngine.UnitTests/TestEngine.UnitTests.csproj @@ -9,10 +9,14 @@ + + + PreserveNewest + PreserveNewest @@ -35,4 +39,19 @@ + + + + + neo + + + + diff --git a/tests/TestEngine.UnitTests/UnitTest_CheckWitness.cs b/tests/TestEngine.UnitTests/UnitTest_CheckWitness.cs new file mode 100644 index 000000000..39539ceed --- /dev/null +++ b/tests/TestEngine.UnitTests/UnitTest_CheckWitness.cs @@ -0,0 +1,109 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo; +using Neo.IO.Json; +using Neo.SmartContract; +using Neo.TestingEngine; +using Neo.VM; +using Neo.VM.Types; +using Neo.Wallets; +using System.IO; +using Compiler = Neo.Compiler.Program; + +namespace TestEngine.UnitTests +{ + [TestClass] + public class UnitTest_CheckWitness + { + [TestInitialize] + public void Init() + { + string path = Directory.GetCurrentDirectory(); + var option = new Compiler.Options() + { + File = path + "/TestClasses/Contract_CheckWitness.cs" + }; + Compiler.Compile(option); + + //Compile changes the path, reseting so that other UT won't break + Directory.SetCurrentDirectory(path); + Engine.Instance.Reset(); + } + + [TestMethod] + public void Test_Check_Witness() + { + var scripthash = "NiNmXL8FjEUEs1nfX9uHFBNaenxDHJtmuB".ToScriptHash(); + var param = new ContractParameter(ContractParameterType.Hash160) + { + Value = scripthash.ToString().Substring(2) + }; + + var json = new JObject(); + json["path"] = "./TestClasses/Contract_CheckWitness.nef"; + json["method"] = "testWitness"; + json["arguments"] = new JArray() { param.ToJson() }; + + var args = new string[] { + json.AsString() + }; + var result = Program.Run(args); + + // mustn't have an error + Assert.IsTrue(result.ContainsProperty("error")); + Assert.IsNull(result["error"]); + + // vm state must've faulted + Assert.IsTrue(result.ContainsProperty("vm_state")); + Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + + // result stack must be empty + StackItem wantresult = false; + Assert.IsTrue(result.ContainsProperty("result_stack")); + Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + + var resultStack = result["result_stack"] as JArray; + Assert.IsTrue(resultStack.Count == 1); + Assert.IsTrue(resultStack[0].ContainsProperty("value")); + Assert.AreEqual(resultStack[0]["value"].AsString(), wantresult.ToJson()["value"].AsString()); + } + + [TestMethod] + public void Test_Check_Witness_With_Sign() + { + var scripthash = "NiNmXL8FjEUEs1nfX9uHFBNaenxDHJtmuB".ToScriptHash(); + var param = new ContractParameter(ContractParameterType.Hash160) + { + Value = scripthash.ToString().Substring(2) + }; + + var json = new JObject(); + json["path"] = "./TestClasses/Contract_CheckWitness.nef"; + json["method"] = "testWitness"; + json["arguments"] = new JArray() { param.ToJson() }; + json["signerAccounts"] = new JArray() { scripthash.ToString() }; + + var args = new string[] { + json.AsString() + }; + var result = Program.Run(args); + + // mustn't have an error + Assert.IsTrue(result.ContainsProperty("error")); + Assert.IsNull(result["error"]); + + // vm state must've faulted + Assert.IsTrue(result.ContainsProperty("vm_state")); + Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + + // result stack must be empty + StackItem wantresult = true; + Assert.IsTrue(result.ContainsProperty("result_stack")); + Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + + var resultStack = result["result_stack"] as JArray; + Assert.IsTrue(resultStack.Count == 1); + Assert.IsTrue(resultStack[0].ContainsProperty("value")); + Assert.AreEqual(resultStack[0]["value"].AsString(), wantresult.ToJson()["value"].AsString()); + } + } +} From adc77d2744511c6f2cae2fe568e817b2fd2dba11 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Wed, 25 Nov 2020 14:04:58 -0300 Subject: [PATCH 18/77] fix increase height --- src/TestEngine/Engine.cs | 4 ++-- src/TestEngine/Program.cs | 6 +----- tests/TestEngine.UnitTests/UnitTest_BlockHeight.cs | 4 ++-- 3 files changed, 5 insertions(+), 9 deletions(-) diff --git a/src/TestEngine/Engine.cs b/src/TestEngine/Engine.cs index f39e7afbf..cb2a4eee4 100644 --- a/src/TestEngine/Engine.cs +++ b/src/TestEngine/Engine.cs @@ -36,7 +36,7 @@ private Engine() Reset(); } - public int BlockCount => ((TestDataCache)engine.Snapshot.Blocks).Count(); + public uint Height => engine.Snapshot.Height; public void Reset() { @@ -83,7 +83,7 @@ public void IncreaseBlockCount(uint newHeight) newBlock = CreateBlock(); } - while (blocks.Count() < newHeight) + while (blocks.Count() <= newHeight) { var hash = newBlock.Hash; var trim = newBlock.Trim(); diff --git a/src/TestEngine/Program.cs b/src/TestEngine/Program.cs index 8d02c1d51..8ef6dc9e8 100644 --- a/src/TestEngine/Program.cs +++ b/src/TestEngine/Program.cs @@ -174,16 +174,12 @@ public static JObject Run(SmartContractTest smartContractTest) Engine.Instance.SetStorage(smartContractTest.storage); } - if (smartContractTest.currentHeight > 0) - { - Engine.Instance.IncreaseBlockCount(smartContractTest.currentHeight); - } - foreach (var contract in smartContractTest.contracts) { Engine.Instance.AddSmartContract(contract.nefPath); } + Engine.Instance.IncreaseBlockCount(smartContractTest.currentHeight); Engine.Instance.SetSigners(smartContractTest.signers); var stackParams = GetStackItemParameters(smartContractTest.methodParameters); diff --git a/tests/TestEngine.UnitTests/UnitTest_BlockHeight.cs b/tests/TestEngine.UnitTests/UnitTest_BlockHeight.cs index fd57b525a..96f5c2079 100644 --- a/tests/TestEngine.UnitTests/UnitTest_BlockHeight.cs +++ b/tests/TestEngine.UnitTests/UnitTest_BlockHeight.cs @@ -29,7 +29,7 @@ public void Init() [TestMethod] public void Test_Json() { - var height = 16; + uint height = 16; var json = new JObject(); json["path"] = "./TestClasses/Contract1.nef"; @@ -49,7 +49,7 @@ public void Test_Json() Assert.IsTrue(result.ContainsProperty("vm_state")); Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); - Assert.AreEqual(height, Engine.Instance.BlockCount); + Assert.AreEqual(height, Engine.Instance.Height); } } } From e9875e8d1b712df9e89a66e9cd2e3e024553bd02 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Tue, 8 Dec 2020 12:53:37 -0300 Subject: [PATCH 19/77] Boa-264 Include blocks and transactions in the TestEngine --- src/TestEngine/Engine.cs | 74 +++++++++++-- src/TestEngine/Helper.cs | 19 ++++ src/TestEngine/Program.cs | 73 ++++++++++++- src/TestEngine/SmartContractTest.cs | 3 + src/TestEngine/TestEngine.csproj | 1 + src/TestEngine/TestUtils/TestMetaDataCache.cs | 5 - src/TestEngine/TestUtils/TestSnapshot.cs | 27 +++-- .../TestClasses/Contract_Time.cs | 13 +++ .../TestEngine.UnitTests.csproj | 4 + tests/TestEngine.UnitTests/UnitTest_Block.cs | 101 ++++++++++++++++++ .../UnitTest_BlockHeight.cs | 55 ---------- 11 files changed, 295 insertions(+), 80 deletions(-) create mode 100644 tests/TestEngine.UnitTests/TestClasses/Contract_Time.cs create mode 100644 tests/TestEngine.UnitTests/UnitTest_Block.cs delete mode 100644 tests/TestEngine.UnitTests/UnitTest_BlockHeight.cs diff --git a/src/TestEngine/Engine.cs b/src/TestEngine/Engine.cs index cb2a4eee4..46c854a95 100644 --- a/src/TestEngine/Engine.cs +++ b/src/TestEngine/Engine.cs @@ -1,12 +1,13 @@ using Neo.Cryptography.ECC; +using Neo.IO; using Neo.IO.Json; using Neo.Ledger; using Neo.Network.P2P.Payloads; using Neo.SmartContract; using Neo.SmartContract.Manifest; +using Neo.SmartContract.Native; using Neo.VM; using Neo.VM.Types; -using System; using System.Collections.Generic; using System.Linq; @@ -41,6 +42,7 @@ private Engine() public void Reset() { engine = SetupNativeContracts(); + IncreaseBlockCount(0); } public void SetTestEngine(string path) @@ -93,7 +95,7 @@ public void IncreaseBlockCount(uint newHeight) } var index = (uint)(blocks.Count() - 1); - snapshot.SetCurrentBlockHash(index, lastBlock.Hash); + snapshot.SetCurrentBlockHash(index, lastBlock?.Hash ?? newBlock.Hash); } public void SetStorage(Dictionary storage) @@ -114,12 +116,65 @@ public void SetStorage(Dictionary storage) public void SetSigners(UInt160[] signerAccounts) { - currentTx.Signers = signerAccounts.Select(p => new Signer() { Account = p, Scopes = WitnessScope.CalledByEntry }).ToArray(); + if (signerAccounts.Length > 0) + { + currentTx.Signers = signerAccounts.Select(p => new Signer() { Account = p, Scopes = WitnessScope.CalledByEntry }).ToArray(); + } } - public JObject Run(string method, StackItem[] args) + public void AddBlock(Block block) { - engine.GetMethod(method).RunEx(args); + if (engine.Snapshot is TestSnapshot snapshot) + { + if (snapshot.Height < block.Index) + { + IncreaseBlockCount(block.Index); + } + + var currentBlock = snapshot.GetBlock(block.Index); + + if (currentBlock != null) + { + currentBlock.Timestamp = block.Timestamp; + + if (currentBlock.Transactions.Length > 0) + { + var tx = currentBlock.Transactions.ToList(); + tx.AddRange(block.Transactions); + currentBlock.Transactions = tx.ToArray(); + } + else + { + currentBlock.Transactions = block.Transactions; + } + + foreach (var tx in block.Transactions) + { + tx.ValidUntilBlock = block.Index + Transaction.MaxValidUntilBlockIncrement; + } + } + } + } + + public JObject Run(string method, ContractParameter[] args) + { + using (ScriptBuilder scriptBuilder = new ScriptBuilder()) + { + scriptBuilder.EmitAppCall(engine.EntryScriptHash, method, args); + currentTx.Script = scriptBuilder.ToArray(); + } + + var stackItemsArgs = args.Select(a => a.ToStackItem()).ToArray(); + engine.GetMethod(method).RunEx(stackItemsArgs); + + currentTx.ValidUntilBlock = engine.Snapshot.Height + Transaction.MaxValidUntilBlockIncrement; + currentTx.SystemFee = engine.GasConsumed; + UInt160[] hashes = currentTx.GetScriptHashesForVerifying(engine.Snapshot); + + // base size for transaction: includes const_header + signers + attributes + script + hashes + int size = Transaction.HeaderSize + currentTx.Signers.GetVarSize() + currentTx.Attributes.GetVarSize() + currentTx.Script.GetVarSize() + IO.Helper.GetVarSize(hashes.Length); + currentTx.NetworkFee += size * NativeContract.Policy.GetFeePerByte(engine.Snapshot); + return engine.ToJson(); } @@ -135,11 +190,14 @@ private TestEngine SetupNativeContracts() NetworkFee = 1, Nonce = 2, SystemFee = 3, - ValidUntilBlock = 4, - Version = 5 + Version = 4 }; TestEngine engine = new TestEngine(TriggerType.Application, currentTx); - ((TestSnapshot)engine.Snapshot).SetPersistingBlock(Blockchain.GenesisBlock); + if (engine.Snapshot is TestSnapshot snapshot) + { + snapshot.SetPersistingBlock(Blockchain.GenesisBlock); + currentTx.ValidUntilBlock = snapshot.Height; + } using (var script = new ScriptBuilder()) { diff --git a/src/TestEngine/Helper.cs b/src/TestEngine/Helper.cs index 0fb3fdb4c..a0acc87d0 100644 --- a/src/TestEngine/Helper.cs +++ b/src/TestEngine/Helper.cs @@ -1,6 +1,7 @@ using Neo.IO.Caching; using Neo.IO.Json; using Neo.Ledger; +using Neo.Network.P2P.Payloads; using Neo.SmartContract; using Neo.SmartContract.Native; using Neo.VM; @@ -19,6 +20,12 @@ public static JObject ToJson(this TestEngine testEngine) json["vm_state"] = testEngine.State.ToString(); json["gasconsumed"] = (new BigDecimal(testEngine.GasConsumed, NativeContract.GAS.Decimals)).ToString(); json["result_stack"] = testEngine.ResultStack.ToJson(); + + if (testEngine.ScriptContainer is Transaction tx) + { + json["transaction"] = tx.ToSimpleJson(); + } + json["storage"] = testEngine.Snapshot.Storages.ToJson(); json["notifications"] = new JArray(testEngine.Notifications.Select(n => n.ToJson())); json["error"] = testEngine.State.HasFlag(VMState.FAULT) ? GetExceptionMessage(testEngine.FaultException) : null; @@ -52,6 +59,18 @@ public static JObject ToJson(this DataCache storage) return storageMap.ToJson()["value"]; } + public static JObject ToSimpleJson(this Transaction tx) + { + JObject json = new JObject(); + json["hash"] = tx.Hash.ToString(); + json["size"] = tx.Size; + json["signers"] = tx.Signers.Select(p => p.ToJson()).ToArray(); + json["attributes"] = tx.Attributes.Select(p => p.ToJson()).ToArray(); + json["script"] = Convert.ToBase64String(tx.Script); + json["witnesses"] = tx.Witnesses.Select(p => p.ToJson()).ToArray(); + return json; + } + private static string GetExceptionMessage(Exception exception) { if (exception == null) return "Engine faulted."; diff --git a/src/TestEngine/Program.cs b/src/TestEngine/Program.cs index 8ef6dc9e8..3ae51c64e 100644 --- a/src/TestEngine/Program.cs +++ b/src/TestEngine/Program.cs @@ -1,4 +1,5 @@ using Neo.IO.Json; +using Neo.Network.P2P.Payloads; using Neo.SmartContract; using Neo.VM; using Neo.VM.Types; @@ -139,6 +140,11 @@ public static JObject RunWithJson(JObject json) smartContractTestCase.contracts = GetContractsFromJson(json["contracts"]); } + if (json.ContainsProperty("blocks") && json["blocks"] is JArray blocks) + { + smartContractTestCase.blocks = blocks.Select(b => BlockFromJson(b)).ToArray(); + } + if (json.ContainsProperty("height")) { smartContractTestCase.currentHeight = uint.Parse(json["height"].AsString()); @@ -179,6 +185,11 @@ public static JObject Run(SmartContractTest smartContractTest) Engine.Instance.AddSmartContract(contract.nefPath); } + foreach (var block in smartContractTest.blocks.OrderBy(b => b.Index)) + { + Engine.Instance.AddBlock(block); + } + Engine.Instance.IncreaseBlockCount(smartContractTest.currentHeight); Engine.Instance.SetSigners(smartContractTest.signers); @@ -258,9 +269,9 @@ private static List GetContractsFromJson(JObject jsonContracts) /// /// json array to be converted /// Returns the built StackItem array - private static StackItem[] GetStackItemParameters(JArray parameters) + private static ContractParameter[] GetStackItemParameters(JArray parameters) { - var items = new List(); + var items = new List(); foreach (JObject param in parameters) { var success = false; @@ -268,7 +279,7 @@ private static StackItem[] GetStackItemParameters(JArray parameters) { try { - items.Add(ContractParameter.FromJson(param).ToStackItem()); + items.Add(ContractParameter.FromJson(param)); success = true; } catch (Exception e) @@ -281,12 +292,66 @@ private static StackItem[] GetStackItemParameters(JArray parameters) if (!success) { // if something went wrong while reading the json, inserts null in this argument position - items.Add(StackItem.Null); + items.Add(new ContractParameter() + { + Type = ContractParameterType.Any, + Value = null + }); } } return items.ToArray(); } + private static Block BlockFromJson(JObject blockJson) + { + var transactions = blockJson["transactions"] as JArray; + return new Block() + { + Index = uint.Parse(blockJson["index"].AsString()), + Timestamp = ulong.Parse(blockJson["timestamp"].AsString()), + Transactions = transactions.Select(b => TxFromJson(b)).ToArray() + }; + } + + private static Transaction TxFromJson(JObject txJson) + { + Signer[] accounts; + Witness[] witnesses; + + if (txJson.ContainsProperty("signers") && txJson["signers"] is JArray signersJson) + { + accounts = signersJson.Select(p => new Signer() + { + Account = UInt160.Parse(p.AsString()), + Scopes = WitnessScope.CalledByEntry + }).ToArray(); + } + else + { + accounts = new Signer[0]; + } + + if (txJson.ContainsProperty("witnesses") && txJson["witnesses"] is JArray witnessesJson) + { + witnesses = witnessesJson.Select(w => new Witness() + { + InvocationScript = Convert.FromBase64String(w["invocation"].AsString()), + VerificationScript = Convert.FromBase64String(w["verification"].AsString()) + }).ToArray(); + } + else + { + witnesses = new Witness[0]; + } + + return new Transaction() + { + Script = txJson["script"].ToByteArray(false), + Signers = accounts, + Witnesses = witnesses + }; + } + private static bool IsValidNefPath(string path) { if (!File.Exists(path)) diff --git a/src/TestEngine/SmartContractTest.cs b/src/TestEngine/SmartContractTest.cs index fd73b93f7..001f07906 100644 --- a/src/TestEngine/SmartContractTest.cs +++ b/src/TestEngine/SmartContractTest.cs @@ -1,4 +1,5 @@ using Neo.IO.Json; +using Neo.Network.P2P.Payloads; using Neo.VM.Types; using System.Collections.Generic; @@ -13,6 +14,7 @@ public class SmartContractTest public List contracts; public uint currentHeight = 0; public UInt160[] signers; + public Block[] blocks; public SmartContractTest(string path, string method, JArray parameters) { @@ -22,6 +24,7 @@ public SmartContractTest(string path, string method, JArray parameters) storage = new Dictionary(); contracts = new List(); signers = new UInt160[] { }; + blocks = new Block[] { }; } } } diff --git a/src/TestEngine/TestEngine.csproj b/src/TestEngine/TestEngine.csproj index d31f2757a..b06a9b43e 100644 --- a/src/TestEngine/TestEngine.csproj +++ b/src/TestEngine/TestEngine.csproj @@ -23,6 +23,7 @@ + diff --git a/src/TestEngine/TestUtils/TestMetaDataCache.cs b/src/TestEngine/TestUtils/TestMetaDataCache.cs index cf5763081..47303eab5 100644 --- a/src/TestEngine/TestUtils/TestMetaDataCache.cs +++ b/src/TestEngine/TestUtils/TestMetaDataCache.cs @@ -24,10 +24,5 @@ protected override void UpdateInternal(T item) { metadata = item; } - - public void Update(T item) - { - UpdateInternal(item); - } } } diff --git a/src/TestEngine/TestUtils/TestSnapshot.cs b/src/TestEngine/TestUtils/TestSnapshot.cs index 029fedd94..9e08312ab 100644 --- a/src/TestEngine/TestUtils/TestSnapshot.cs +++ b/src/TestEngine/TestUtils/TestSnapshot.cs @@ -56,18 +56,29 @@ public void SetCurrentBlockHash(uint index, UInt256 hash) { var blocksCount = blocks.Count(); - if (index > blocksCount) + if (index >= blocksCount) { - index = (uint)blocksCount; + index = (uint)blocksCount - 1; } - var hashIndex = new HashIndexState() - { - Hash = hash, - Index = index - }; - ((TestMetaDataCache)BlockHashIndex).Update(hashIndex); + var blockHashIndex = BlockHashIndex.Get(); + blockHashIndex.Index = index; + blockHashIndex.Hash = hash; } } + + public Block GetBlock(uint index) + { + var blocks = Blocks.Seek().GetEnumerator(); + do { + var (hash, block) = blocks.Current; + if (block != null && block.Index == index) + { + return block.GetBlock(Transactions); + } + } while (blocks.MoveNext()); + + return null; + } } } diff --git a/tests/TestEngine.UnitTests/TestClasses/Contract_Time.cs b/tests/TestEngine.UnitTests/TestClasses/Contract_Time.cs new file mode 100644 index 000000000..4c934d2a8 --- /dev/null +++ b/tests/TestEngine.UnitTests/TestClasses/Contract_Time.cs @@ -0,0 +1,13 @@ +using Neo.SmartContract.Framework; +using Neo.SmartContract.Framework.Services.Neo; + +namespace Neo.Compiler.MSIL.UnitTests.TestClasses +{ + public class Contract_Time : SmartContract.Framework.SmartContract + { + public static ulong getTime() + { + return Runtime.Time; + } + } +} diff --git a/tests/TestEngine.UnitTests/TestEngine.UnitTests.csproj b/tests/TestEngine.UnitTests/TestEngine.UnitTests.csproj index 9f9e300e7..40b9910c2 100644 --- a/tests/TestEngine.UnitTests/TestEngine.UnitTests.csproj +++ b/tests/TestEngine.UnitTests/TestEngine.UnitTests.csproj @@ -11,6 +11,7 @@ + @@ -23,6 +24,9 @@ PreserveNewest + + PreserveNewest + PreserveNewest diff --git a/tests/TestEngine.UnitTests/UnitTest_Block.cs b/tests/TestEngine.UnitTests/UnitTest_Block.cs new file mode 100644 index 000000000..ab2fb2bdf --- /dev/null +++ b/tests/TestEngine.UnitTests/UnitTest_Block.cs @@ -0,0 +1,101 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.IO.Json; +using Neo.Ledger; +using Neo.TestingEngine; +using Neo.VM; +using Neo.VM.Types; +using System.IO; +using Compiler = Neo.Compiler.Program; + +namespace TestEngine.UnitTests +{ + [TestClass] + public class UnitTest_Block + { + [TestInitialize] + public void Init() + { + string path = Directory.GetCurrentDirectory(); + var option = new Compiler.Options() + { + File = path + "/TestClasses/Contract1.cs" + }; + Compiler.Compile(option); + + option.File = path + "/TestClasses/Contract_Time.cs"; + Compiler.Compile(option); + + //Compile changes the path, reseting so that other UT won't break + Directory.SetCurrentDirectory(path); + Engine.Instance.Reset(); + } + + [TestMethod] + public void Test_Block_Height() + { + uint height = 16; + + var json = new JObject(); + json["path"] = "./TestClasses/Contract1.nef"; + json["method"] = "testVoid"; + json["height"] = height; + + var args = new string[] { + json.AsString() + }; + var result = Program.Run(args); + + // mustn't have errors + Assert.IsTrue(result.ContainsProperty("error")); + Assert.IsNull(result["error"]); + + // test state + Assert.IsTrue(result.ContainsProperty("vm_state")); + Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + + Assert.AreEqual(height, Engine.Instance.Height); + } + + [TestMethod] + public void Test_Include_Block() + { + uint height = 10; + ulong timestamp = Blockchain.GenesisBlock.Timestamp + 20 * Blockchain.MillisecondsPerBlock; + + var blockJson = new JObject(); + blockJson["index"] = height; + blockJson["timestamp"] = timestamp; + blockJson["transactions"] = new JArray(); + + var json = new JObject(); + json["path"] = "./TestClasses/Contract_Time.nef"; + json["method"] = "getTime"; + json["blocks"] = new JArray() { blockJson }; + + var args = new string[] { + json.AsString() + }; + var result = Program.Run(args); + + // mustn't have errors + Assert.IsTrue(result.ContainsProperty("error")); + Assert.IsNull(result["error"]); + + // test state + Assert.IsTrue(result.ContainsProperty("vm_state")); + Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + + Assert.AreEqual(height, Engine.Instance.Height); + + // test result + StackItem wantresult = timestamp; + Assert.IsTrue(result.ContainsProperty("result_stack")); + Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + + var resultStack = result["result_stack"] as JArray; + Assert.IsTrue(resultStack.Count == 1); + Assert.IsTrue(resultStack[0].ContainsProperty("value")); + Assert.AreEqual(resultStack[0]["value"].AsString(), wantresult.ToJson()["value"].AsString()); + } + } +} diff --git a/tests/TestEngine.UnitTests/UnitTest_BlockHeight.cs b/tests/TestEngine.UnitTests/UnitTest_BlockHeight.cs deleted file mode 100644 index 96f5c2079..000000000 --- a/tests/TestEngine.UnitTests/UnitTest_BlockHeight.cs +++ /dev/null @@ -1,55 +0,0 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.IO.Json; -using Neo.TestingEngine; -using Neo.VM; -using Neo.VM.Types; -using System.IO; -using Compiler = Neo.Compiler.Program; - -namespace TestEngine.UnitTests -{ - [TestClass] - public class UnitTest_BlockHeight - { - [TestInitialize] - public void Init() - { - string path = Directory.GetCurrentDirectory(); - var option = new Compiler.Options() - { - File = path + "/TestClasses/Contract1.cs" - }; - Compiler.Compile(option); - - //Compile changes the path, reseting so that other UT won't break - Directory.SetCurrentDirectory(path); - Engine.Instance.Reset(); - } - - [TestMethod] - public void Test_Json() - { - uint height = 16; - - var json = new JObject(); - json["path"] = "./TestClasses/Contract1.nef"; - json["method"] = "testVoid"; - json["height"] = height; - - var args = new string[] { - json.AsString() - }; - var result = Program.Run(args); - - // mustn't have errors - Assert.IsTrue(result.ContainsProperty("error")); - Assert.IsNull(result["error"]); - - // test state - Assert.IsTrue(result.ContainsProperty("vm_state")); - Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); - - Assert.AreEqual(height, Engine.Instance.Height); - } - } -} From 459df19ddd4db0d0fd0664593602c48957eaa00a Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Thu, 10 Dec 2020 13:38:06 -0300 Subject: [PATCH 20/77] Boa-264 Include blocks and transactions in the TestEngine --- neo-devpack-dotnet.sln | 4 +- src/{TestEngine => Neo.TestEngine}/Engine.cs | 25 ++++++-- src/{TestEngine => Neo.TestEngine}/Helper.cs | 0 .../Neo.TestEngine.csproj} | 1 - src/{TestEngine => Neo.TestEngine}/Program.cs | 5 +- .../SmartContractTest.cs | 0 .../TestContract.cs | 0 .../TestUtils/BuildNEF.cs | 0 .../TestUtils/BuildScript.cs | 0 .../TestUtils/DefLogger.cs | 0 .../TestUtils/NeonTestTool.cs | 0 .../TestUtils/TestAccount.cs | 0 .../TestUtils/TestBlockchain.cs | 0 .../TestUtils/TestConsensusContext.cs | 0 .../TestUtils/TestDataCache.cs | 9 +++ .../TestUtils/TestEngine.cs | 0 .../TestUtils/TestMetaDataCache.cs | 0 .../TestUtils/TestSnapshot.cs | 53 ++++++++++++++--- .../TestUtils/TestStorageContext.cs | 0 .../TestUtils/TestWallet.cs | 0 .../Neo.Compiler.MSIL.UnitTests.csproj | 2 +- .../Neo.TestEngine.UnitTests.csproj} | 2 +- .../TestClasses/Contract1.cs | 0 .../TestClasses/Contract2.cs | 0 .../TestClasses/Contract_CheckWitness.cs | 0 .../TestClasses/Contract_ContractCall.cs | 0 .../TestClasses/Contract_Time.cs | 5 ++ .../UnitTest_Block.cs | 58 +++++++++++++++++++ .../UnitTest_CheckWitness.cs | 0 .../UnitTest_ContractCall.cs | 0 .../UnitTest_Invoke.cs | 0 .../UnitTest_Notification.cs | 0 32 files changed, 142 insertions(+), 22 deletions(-) rename src/{TestEngine => Neo.TestEngine}/Engine.cs (92%) rename src/{TestEngine => Neo.TestEngine}/Helper.cs (100%) rename src/{TestEngine/TestEngine.csproj => Neo.TestEngine/Neo.TestEngine.csproj} (96%) rename src/{TestEngine => Neo.TestEngine}/Program.cs (98%) rename src/{TestEngine => Neo.TestEngine}/SmartContractTest.cs (100%) rename src/{TestEngine => Neo.TestEngine}/TestContract.cs (100%) rename src/{TestEngine => Neo.TestEngine}/TestUtils/BuildNEF.cs (100%) rename src/{TestEngine => Neo.TestEngine}/TestUtils/BuildScript.cs (100%) rename src/{TestEngine => Neo.TestEngine}/TestUtils/DefLogger.cs (100%) rename src/{TestEngine => Neo.TestEngine}/TestUtils/NeonTestTool.cs (100%) rename src/{TestEngine => Neo.TestEngine}/TestUtils/TestAccount.cs (100%) rename src/{TestEngine => Neo.TestEngine}/TestUtils/TestBlockchain.cs (100%) rename src/{TestEngine => Neo.TestEngine}/TestUtils/TestConsensusContext.cs (100%) rename src/{TestEngine => Neo.TestEngine}/TestUtils/TestDataCache.cs (89%) rename src/{TestEngine => Neo.TestEngine}/TestUtils/TestEngine.cs (100%) rename src/{TestEngine => Neo.TestEngine}/TestUtils/TestMetaDataCache.cs (100%) rename src/{TestEngine => Neo.TestEngine}/TestUtils/TestSnapshot.cs (65%) rename src/{TestEngine => Neo.TestEngine}/TestUtils/TestStorageContext.cs (100%) rename src/{TestEngine => Neo.TestEngine}/TestUtils/TestWallet.cs (100%) rename tests/{TestEngine.UnitTests/TestEngine.UnitTests.csproj => Neo.TestEngine.UnitTests/Neo.TestEngine.UnitTests.csproj} (96%) rename tests/{TestEngine.UnitTests => Neo.TestEngine.UnitTests}/TestClasses/Contract1.cs (100%) rename tests/{TestEngine.UnitTests => Neo.TestEngine.UnitTests}/TestClasses/Contract2.cs (100%) rename tests/{TestEngine.UnitTests => Neo.TestEngine.UnitTests}/TestClasses/Contract_CheckWitness.cs (100%) rename tests/{TestEngine.UnitTests => Neo.TestEngine.UnitTests}/TestClasses/Contract_ContractCall.cs (100%) rename tests/{TestEngine.UnitTests => Neo.TestEngine.UnitTests}/TestClasses/Contract_Time.cs (68%) rename tests/{TestEngine.UnitTests => Neo.TestEngine.UnitTests}/UnitTest_Block.cs (59%) rename tests/{TestEngine.UnitTests => Neo.TestEngine.UnitTests}/UnitTest_CheckWitness.cs (100%) rename tests/{TestEngine.UnitTests => Neo.TestEngine.UnitTests}/UnitTest_ContractCall.cs (100%) rename tests/{TestEngine.UnitTests => Neo.TestEngine.UnitTests}/UnitTest_Invoke.cs (100%) rename tests/{TestEngine.UnitTests => Neo.TestEngine.UnitTests}/UnitTest_Notification.cs (100%) diff --git a/neo-devpack-dotnet.sln b/neo-devpack-dotnet.sln index bee1e22f5..e42243252 100644 --- a/neo-devpack-dotnet.sln +++ b/neo-devpack-dotnet.sln @@ -29,9 +29,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Template.NEP5.CSharp", "tem EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Template.NEP5.UnitTests", "tests\Template.NEP5.UnitTests\Template.NEP5.UnitTests.csproj", "{780141EE-D6E9-4591-8470-8F91B12027CA}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestEngine", "src\TestEngine\TestEngine.csproj", "{39347E90-FC12-4018-8F22-828F0F1B2F7D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Neo.TestEngine", "src\Neo.TestEngine\Neo.TestEngine.csproj", "{39347E90-FC12-4018-8F22-828F0F1B2F7D}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TestEngine.UnitTests", "tests\TestEngine.UnitTests\TestEngine.UnitTests.csproj", "{FFDC189F-2F72-4542-B28B-8EFA0F28E3CF}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Neo.TestEngine.UnitTests", "tests\Neo.TestEngine.UnitTests\Neo.TestEngine.UnitTests.csproj", "{FFDC189F-2F72-4542-B28B-8EFA0F28E3CF}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/src/TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs similarity index 92% rename from src/TestEngine/Engine.cs rename to src/Neo.TestEngine/Engine.cs index 46c854a95..e25404b0f 100644 --- a/src/TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -1,8 +1,10 @@ using Neo.Cryptography.ECC; using Neo.IO; +using Neo.IO.Caching; using Neo.IO.Json; using Neo.Ledger; using Neo.Network.P2P.Payloads; +using Neo.Persistence; using Neo.SmartContract; using Neo.SmartContract.Manifest; using Neo.SmartContract.Native; @@ -39,6 +41,8 @@ private Engine() public uint Height => engine.Snapshot.Height; + public StoreView Snaptshot => engine.Snapshot; + public void Reset() { engine = SetupNativeContracts(); @@ -131,10 +135,11 @@ public void AddBlock(Block block) IncreaseBlockCount(block.Index); } - var currentBlock = snapshot.GetBlock(block.Index); + var currentBlock = snapshot.TryGetBlock(block.Index); if (currentBlock != null) { + var hash = currentBlock.Hash; currentBlock.Timestamp = block.Timestamp; if (currentBlock.Transactions.Length > 0) @@ -147,17 +152,30 @@ public void AddBlock(Block block) { currentBlock.Transactions = block.Transactions; } + snapshot.AddTransactions(block.Transactions); foreach (var tx in block.Transactions) { tx.ValidUntilBlock = block.Index + Transaction.MaxValidUntilBlockIncrement; } + + if (snapshot.Blocks is TestDataCache blocks) + { + blocks.UpdateChangingKey(hash, currentBlock.Hash, currentBlock.Trim()); + } } } } public JObject Run(string method, ContractParameter[] args) { + if (engine.Snapshot is TestSnapshot snapshot) + { + var persistingBlock = snapshot.TryGetBlock(snapshot.Height); + snapshot.SetPersistingBlock(persistingBlock ?? Blockchain.GenesisBlock); + currentTx.ValidUntilBlock = snapshot.Height; + } + using (ScriptBuilder scriptBuilder = new ScriptBuilder()) { scriptBuilder.EmitAppCall(engine.EntryScriptHash, method, args); @@ -193,11 +211,6 @@ private TestEngine SetupNativeContracts() Version = 4 }; TestEngine engine = new TestEngine(TriggerType.Application, currentTx); - if (engine.Snapshot is TestSnapshot snapshot) - { - snapshot.SetPersistingBlock(Blockchain.GenesisBlock); - currentTx.ValidUntilBlock = snapshot.Height; - } using (var script = new ScriptBuilder()) { diff --git a/src/TestEngine/Helper.cs b/src/Neo.TestEngine/Helper.cs similarity index 100% rename from src/TestEngine/Helper.cs rename to src/Neo.TestEngine/Helper.cs diff --git a/src/TestEngine/TestEngine.csproj b/src/Neo.TestEngine/Neo.TestEngine.csproj similarity index 96% rename from src/TestEngine/TestEngine.csproj rename to src/Neo.TestEngine/Neo.TestEngine.csproj index b06a9b43e..d31f2757a 100644 --- a/src/TestEngine/TestEngine.csproj +++ b/src/Neo.TestEngine/Neo.TestEngine.csproj @@ -23,7 +23,6 @@ - diff --git a/src/TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs similarity index 98% rename from src/TestEngine/Program.cs rename to src/Neo.TestEngine/Program.cs index 3ae51c64e..97b211f2e 100644 --- a/src/TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -322,7 +322,7 @@ private static Transaction TxFromJson(JObject txJson) { accounts = signersJson.Select(p => new Signer() { - Account = UInt160.Parse(p.AsString()), + Account = UInt160.Parse(p["account"].AsString()), Scopes = WitnessScope.CalledByEntry }).ToArray(); } @@ -348,7 +348,8 @@ private static Transaction TxFromJson(JObject txJson) { Script = txJson["script"].ToByteArray(false), Signers = accounts, - Witnesses = witnesses + Witnesses = witnesses, + Attributes = new TransactionAttribute[0] }; } diff --git a/src/TestEngine/SmartContractTest.cs b/src/Neo.TestEngine/SmartContractTest.cs similarity index 100% rename from src/TestEngine/SmartContractTest.cs rename to src/Neo.TestEngine/SmartContractTest.cs diff --git a/src/TestEngine/TestContract.cs b/src/Neo.TestEngine/TestContract.cs similarity index 100% rename from src/TestEngine/TestContract.cs rename to src/Neo.TestEngine/TestContract.cs diff --git a/src/TestEngine/TestUtils/BuildNEF.cs b/src/Neo.TestEngine/TestUtils/BuildNEF.cs similarity index 100% rename from src/TestEngine/TestUtils/BuildNEF.cs rename to src/Neo.TestEngine/TestUtils/BuildNEF.cs diff --git a/src/TestEngine/TestUtils/BuildScript.cs b/src/Neo.TestEngine/TestUtils/BuildScript.cs similarity index 100% rename from src/TestEngine/TestUtils/BuildScript.cs rename to src/Neo.TestEngine/TestUtils/BuildScript.cs diff --git a/src/TestEngine/TestUtils/DefLogger.cs b/src/Neo.TestEngine/TestUtils/DefLogger.cs similarity index 100% rename from src/TestEngine/TestUtils/DefLogger.cs rename to src/Neo.TestEngine/TestUtils/DefLogger.cs diff --git a/src/TestEngine/TestUtils/NeonTestTool.cs b/src/Neo.TestEngine/TestUtils/NeonTestTool.cs similarity index 100% rename from src/TestEngine/TestUtils/NeonTestTool.cs rename to src/Neo.TestEngine/TestUtils/NeonTestTool.cs diff --git a/src/TestEngine/TestUtils/TestAccount.cs b/src/Neo.TestEngine/TestUtils/TestAccount.cs similarity index 100% rename from src/TestEngine/TestUtils/TestAccount.cs rename to src/Neo.TestEngine/TestUtils/TestAccount.cs diff --git a/src/TestEngine/TestUtils/TestBlockchain.cs b/src/Neo.TestEngine/TestUtils/TestBlockchain.cs similarity index 100% rename from src/TestEngine/TestUtils/TestBlockchain.cs rename to src/Neo.TestEngine/TestUtils/TestBlockchain.cs diff --git a/src/TestEngine/TestUtils/TestConsensusContext.cs b/src/Neo.TestEngine/TestUtils/TestConsensusContext.cs similarity index 100% rename from src/TestEngine/TestUtils/TestConsensusContext.cs rename to src/Neo.TestEngine/TestUtils/TestConsensusContext.cs diff --git a/src/TestEngine/TestUtils/TestDataCache.cs b/src/Neo.TestEngine/TestUtils/TestDataCache.cs similarity index 89% rename from src/TestEngine/TestUtils/TestDataCache.cs rename to src/Neo.TestEngine/TestUtils/TestDataCache.cs index 68d7f12b9..e35d67ac3 100644 --- a/src/TestEngine/TestUtils/TestDataCache.cs +++ b/src/Neo.TestEngine/TestUtils/TestDataCache.cs @@ -78,5 +78,14 @@ public void AddForTest(TKey key, TValue value) { AddInternal(key, value); } + + public void UpdateChangingKey(TKey oldKey, TKey newKey, TValue value) + { + if (ContainsInternal(oldKey)) + { + DeleteInternal(oldKey); + AddInternal(newKey, value); + } + } } } diff --git a/src/TestEngine/TestUtils/TestEngine.cs b/src/Neo.TestEngine/TestUtils/TestEngine.cs similarity index 100% rename from src/TestEngine/TestUtils/TestEngine.cs rename to src/Neo.TestEngine/TestUtils/TestEngine.cs diff --git a/src/TestEngine/TestUtils/TestMetaDataCache.cs b/src/Neo.TestEngine/TestUtils/TestMetaDataCache.cs similarity index 100% rename from src/TestEngine/TestUtils/TestMetaDataCache.cs rename to src/Neo.TestEngine/TestUtils/TestMetaDataCache.cs diff --git a/src/TestEngine/TestUtils/TestSnapshot.cs b/src/Neo.TestEngine/TestUtils/TestSnapshot.cs similarity index 65% rename from src/TestEngine/TestUtils/TestSnapshot.cs rename to src/Neo.TestEngine/TestUtils/TestSnapshot.cs index 9e08312ab..fed05a5e3 100644 --- a/src/TestEngine/TestUtils/TestSnapshot.cs +++ b/src/Neo.TestEngine/TestUtils/TestSnapshot.cs @@ -67,18 +67,53 @@ public void SetCurrentBlockHash(uint index, UInt256 hash) } } - public Block GetBlock(uint index) + public Block TryGetBlock(uint index) { - var blocks = Blocks.Seek().GetEnumerator(); - do { - var (hash, block) = blocks.Current; - if (block != null && block.Index == index) + try + { + var blocks = Blocks.Seek().GetEnumerator(); + do { - return block.GetBlock(Transactions); - } - } while (blocks.MoveNext()); + var (hash, block) = blocks.Current; + if (block != null && block.Index == index) + { + return block.GetBlock(Transactions); + } + } while (blocks.MoveNext()); + + return null; + } + catch + { + return null; + } + } - return null; + public void AddTransactions(Transaction[] txs, int blockIndex = -1) + { + uint index = blockIndex >= 0 ? (uint)blockIndex : Height; + if (Transactions is TestDataCache transactions) + { + foreach (var tx in txs) + { + if (transactions.Contains(tx.Hash)) + { + var state = transactions.TryGet(tx.Hash); + state.BlockIndex = index; + state.Transaction = tx; + } + else + { + var state = new TransactionState() + { + BlockIndex = index, + Transaction = tx, + VMState = VM.VMState.HALT + }; + transactions.AddForTest(tx.Hash, state); + } + } + } } } } diff --git a/src/TestEngine/TestUtils/TestStorageContext.cs b/src/Neo.TestEngine/TestUtils/TestStorageContext.cs similarity index 100% rename from src/TestEngine/TestUtils/TestStorageContext.cs rename to src/Neo.TestEngine/TestUtils/TestStorageContext.cs diff --git a/src/TestEngine/TestUtils/TestWallet.cs b/src/Neo.TestEngine/TestUtils/TestWallet.cs similarity index 100% rename from src/TestEngine/TestUtils/TestWallet.cs rename to src/Neo.TestEngine/TestUtils/TestWallet.cs diff --git a/tests/Neo.Compiler.MSIL.UnitTests/Neo.Compiler.MSIL.UnitTests.csproj b/tests/Neo.Compiler.MSIL.UnitTests/Neo.Compiler.MSIL.UnitTests.csproj index 5081f5cff..b7b85746a 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/Neo.Compiler.MSIL.UnitTests.csproj +++ b/tests/Neo.Compiler.MSIL.UnitTests/Neo.Compiler.MSIL.UnitTests.csproj @@ -22,7 +22,7 @@ scfx - + diff --git a/tests/TestEngine.UnitTests/TestEngine.UnitTests.csproj b/tests/Neo.TestEngine.UnitTests/Neo.TestEngine.UnitTests.csproj similarity index 96% rename from tests/TestEngine.UnitTests/TestEngine.UnitTests.csproj rename to tests/Neo.TestEngine.UnitTests/Neo.TestEngine.UnitTests.csproj index 40b9910c2..c86eb838b 100644 --- a/tests/TestEngine.UnitTests/TestEngine.UnitTests.csproj +++ b/tests/Neo.TestEngine.UnitTests/Neo.TestEngine.UnitTests.csproj @@ -40,7 +40,7 @@ - + diff --git a/tests/TestEngine.UnitTests/TestClasses/Contract1.cs b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract1.cs similarity index 100% rename from tests/TestEngine.UnitTests/TestClasses/Contract1.cs rename to tests/Neo.TestEngine.UnitTests/TestClasses/Contract1.cs diff --git a/tests/TestEngine.UnitTests/TestClasses/Contract2.cs b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract2.cs similarity index 100% rename from tests/TestEngine.UnitTests/TestClasses/Contract2.cs rename to tests/Neo.TestEngine.UnitTests/TestClasses/Contract2.cs diff --git a/tests/TestEngine.UnitTests/TestClasses/Contract_CheckWitness.cs b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_CheckWitness.cs similarity index 100% rename from tests/TestEngine.UnitTests/TestClasses/Contract_CheckWitness.cs rename to tests/Neo.TestEngine.UnitTests/TestClasses/Contract_CheckWitness.cs diff --git a/tests/TestEngine.UnitTests/TestClasses/Contract_ContractCall.cs b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_ContractCall.cs similarity index 100% rename from tests/TestEngine.UnitTests/TestClasses/Contract_ContractCall.cs rename to tests/Neo.TestEngine.UnitTests/TestClasses/Contract_ContractCall.cs diff --git a/tests/TestEngine.UnitTests/TestClasses/Contract_Time.cs b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_Time.cs similarity index 68% rename from tests/TestEngine.UnitTests/TestClasses/Contract_Time.cs rename to tests/Neo.TestEngine.UnitTests/TestClasses/Contract_Time.cs index 4c934d2a8..fdd80b66f 100644 --- a/tests/TestEngine.UnitTests/TestClasses/Contract_Time.cs +++ b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_Time.cs @@ -9,5 +9,10 @@ public static ulong getTime() { return Runtime.Time; } + + public static object getBlock(uint blockIndex) + { + return Blockchain.GetTransactionFromBlock(blockIndex, 0); + } } } diff --git a/tests/TestEngine.UnitTests/UnitTest_Block.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs similarity index 59% rename from tests/TestEngine.UnitTests/UnitTest_Block.cs rename to tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs index ab2fb2bdf..f96934880 100644 --- a/tests/TestEngine.UnitTests/UnitTest_Block.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs @@ -97,5 +97,63 @@ public void Test_Include_Block() Assert.IsTrue(resultStack[0].ContainsProperty("value")); Assert.AreEqual(resultStack[0]["value"].AsString(), wantresult.ToJson()["value"].AsString()); } + + [TestMethod] + public void Test_Include_Transaction() + { + var signer = new JObject(); + signer["account"] = "0x0000000000000000000000000000000000000000"; + signer["scopes"] = "None"; + + var transactionJson = new JObject(); + transactionJson["script"] = "EMAMB2dldFRpbWUMFIsccf/5cagRfaIDVBBMkYOwR666QWJ9W1I="; + transactionJson["witnesses"] = new JArray(); + transactionJson["signers"] = new JArray() + { + signer + }; + + uint height = 1; + ulong timestamp = Blockchain.GenesisBlock.Timestamp + 20 * Blockchain.MillisecondsPerBlock; + + var blockJson = new JObject(); + blockJson["index"] = height; + blockJson["timestamp"] = timestamp; + blockJson["transactions"] = new JArray() + { + transactionJson + }; + + var json = new JObject(); + json["path"] = "./TestClasses/Contract_Time.nef"; + json["method"] = "getBlock"; + json["arguments"] = new JArray() { ((StackItem)height).ToParameter().ToJson() }; + json["blocks"] = new JArray() { blockJson }; + + var args = new string[] { + json.AsString() + }; + var result = Program.Run(args); + + // mustn't have errors + Assert.IsTrue(result.ContainsProperty("error")); + Assert.IsNull(result["error"]); + + // test state + Assert.IsTrue(result.ContainsProperty("vm_state")); + Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + + Assert.AreEqual(height, Engine.Instance.Height); + + // test result + Assert.IsTrue(Engine.Instance.Snaptshot is TestSnapshot); + // the compiler doesn't allow to do this with only the assertion + if (Engine.Instance.Snaptshot is TestSnapshot snapshot) + { + var block = snapshot.PersistingBlock; + Assert.IsNotNull(block); + Assert.AreEqual(block.Transactions.Length, ((JArray)blockJson["transactions"]).Count); + } + } } } diff --git a/tests/TestEngine.UnitTests/UnitTest_CheckWitness.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs similarity index 100% rename from tests/TestEngine.UnitTests/UnitTest_CheckWitness.cs rename to tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs diff --git a/tests/TestEngine.UnitTests/UnitTest_ContractCall.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs similarity index 100% rename from tests/TestEngine.UnitTests/UnitTest_ContractCall.cs rename to tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs diff --git a/tests/TestEngine.UnitTests/UnitTest_Invoke.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs similarity index 100% rename from tests/TestEngine.UnitTests/UnitTest_Invoke.cs rename to tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs diff --git a/tests/TestEngine.UnitTests/UnitTest_Notification.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs similarity index 100% rename from tests/TestEngine.UnitTests/UnitTest_Notification.cs rename to tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs From 28d533732f907bfe9ba5c26f43c6bc1d008a0735 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Thu, 10 Dec 2020 14:19:38 -0300 Subject: [PATCH 21/77] fix unit test path --- .github/workflows/main.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index ee9afe0fc..e9efe9b0f 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -31,8 +31,8 @@ jobs: run: dotnet test tests/Neo.SmartContract.Framework.UnitTests /p:CollectCoverage=true /p:CoverletOutput=${GITHUB_WORKSPACE}/coverage/lcov /p:MergeWith=${GITHUB_WORKSPACE}/coverage/coverage.json /p:Exclude=\"[Neo.SmartContract.*]*,[Neo.Compiler.MSIL.UnitTests]*,[Neo.Compiler.MSIL.UnitTests.*]*\" /p:CoverletOutputFormat=lcov - name: Test Template.NEP5.UnitTests run: dotnet test tests/Template.NEP5.UnitTests /p:CollectCoverage=true /p:CoverletOutput=${GITHUB_WORKSPACE}/coverage/lcov /p:MergeWith=${GITHUB_WORKSPACE}/coverage/coverage.json /p:Exclude=\"[Neo.SmartContract.*]*,[Neo.Compiler.MSIL.UnitTests]*,[Neo.Compiler.MSIL.UnitTests.*]*\" /p:CoverletOutputFormat=lcov - - name: Test TestEngine.UnitTests - run: dotnet test tests/TestEngine.UnitTests /p:CollectCoverage=true /p:CoverletOutput=${GITHUB_WORKSPACE}/coverage/lcov /p:MergeWith=${GITHUB_WORKSPACE}/coverage/coverage.json /p:Exclude=\"[Neo.SmartContract.*]*,[Neo.Compiler.MSIL.UnitTests]*,[Neo.Compiler.MSIL.UnitTests.*]*\" /p:CoverletOutputFormat=lcov + - name: Test Neo.TestEngine.UnitTests + run: dotnet test tests/Neo.TestEngine.UnitTests /p:CollectCoverage=true /p:CoverletOutput=${GITHUB_WORKSPACE}/coverage/lcov /p:MergeWith=${GITHUB_WORKSPACE}/coverage/coverage.json /p:Exclude=\"[Neo.SmartContract.*]*,[Neo.Compiler.MSIL.UnitTests]*,[Neo.Compiler.MSIL.UnitTests.*]*\" /p:CoverletOutputFormat=lcov - name: Coveralls uses: coverallsapp/github-action@master with: From 19294caf094b6772d6fcb2b3907772457408a748 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Fri, 11 Dec 2020 18:07:17 -0300 Subject: [PATCH 22/77] fix map arguments --- src/Neo.TestEngine/Engine.cs | 5 ++- src/Neo.TestEngine/Helper.cs | 80 ++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+), 1 deletion(-) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index 5efd995b6..cdb54261f 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -53,9 +53,11 @@ public void SetTestEngine(string path) { engine.AddEntryScript(path); var manifest = ContractManifest.FromJson(JObject.Parse(engine.ScriptEntry.finalManifest)); + var hash = engine.ScriptEntry.finalNEFScript.ToScriptHash(); - engine.Snapshot.Contracts.Add(engine.ScriptEntry.finalNEFScript.ToScriptHash(), new Neo.Ledger.ContractState() + engine.Snapshot.Contracts.Add(hash, new Neo.Ledger.ContractState() { + Hash = hash, Script = engine.ScriptEntry.finalNEFScript, Manifest = manifest, }); @@ -68,6 +70,7 @@ public void AddSmartContract(string path) engine.Snapshot.Contracts.Add(hash, new Ledger.ContractState() { + Hash = hash, Script = builtScript.finalNEFScript, Manifest = ContractManifest.FromJson(JObject.Parse(builtScript.finalManifest)), }); diff --git a/src/Neo.TestEngine/Helper.cs b/src/Neo.TestEngine/Helper.cs index a0acc87d0..f6f4578e3 100644 --- a/src/Neo.TestEngine/Helper.cs +++ b/src/Neo.TestEngine/Helper.cs @@ -8,6 +8,13 @@ using Neo.VM.Types; using System; using System.Linq; +using Neo.Cryptography.ECC; +using Neo.IO; +using System.Collections.Generic; +using System.Numerics; +using Array = Neo.VM.Types.Array; +using Boolean = Neo.VM.Types.Boolean; +using Buffer = Neo.VM.Types.Buffer; namespace Neo.TestingEngine { @@ -82,5 +89,78 @@ private static string GetExceptionMessage(Exception exception) return exception.Message; } + + public static ScriptBuilder EmitAppCall(this ScriptBuilder sb, UInt160 scriptHash, string operation, params ContractParameter[] args) + { + for (int i = args.Length - 1; i >= 0; i--) + sb.EmitPush(args[i]); + sb.EmitPush(args.Length); + sb.Emit(OpCode.PACK); + sb.EmitPush(operation); + sb.EmitPush(scriptHash); + sb.EmitSysCall(ApplicationEngine.System_Contract_Call); + return sb; + } + + public static ScriptBuilder EmitPush(this ScriptBuilder sb, ContractParameter parameter) + { + if (parameter.Value is null) + sb.Emit(OpCode.PUSHNULL); + else + switch (parameter.Type) + { + case ContractParameterType.Signature: + case ContractParameterType.ByteArray: + sb.EmitPush((byte[])parameter.Value); + break; + case ContractParameterType.Boolean: + sb.EmitPush((bool)parameter.Value); + break; + case ContractParameterType.Integer: + if (parameter.Value is BigInteger bi) + sb.EmitPush(bi); + else + sb.EmitPush((BigInteger)typeof(BigInteger).GetConstructor(new[] { parameter.Value.GetType() }).Invoke(new[] { parameter.Value })); + break; + case ContractParameterType.Hash160: + sb.EmitPush((UInt160)parameter.Value); + break; + case ContractParameterType.Hash256: + sb.EmitPush((UInt256)parameter.Value); + break; + case ContractParameterType.PublicKey: + sb.EmitPush((ECPoint)parameter.Value); + break; + case ContractParameterType.String: + sb.EmitPush((string)parameter.Value); + break; + case ContractParameterType.Array: + { + IList parameters = (IList)parameter.Value; + for (int i = parameters.Count - 1; i >= 0; i--) + sb.EmitPush(parameters[i]); + sb.EmitPush(parameters.Count); + sb.Emit(OpCode.PACK); + } + break; + case ContractParameterType.Map: + { + IList> parameters = (IList>)parameter.Value; + sb.Emit(OpCode.NEWMAP); + foreach (var (key, value) in parameters) + { + sb.Emit(OpCode.DUP); + sb.EmitPush(key); + sb.EmitPush(value); + sb.Emit(OpCode.APPEND); + } + } + break; + default: + throw new ArgumentException(); + } + return sb; + } } } + From 0e85e063f217fa5fc08c1826472b54ad1e300dd7 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 14 Dec 2020 13:48:55 -0300 Subject: [PATCH 23/77] include genesis block's transactions in the TestSnapshot --- src/Neo.TestEngine/Engine.cs | 1 + src/Neo.TestEngine/TestUtils/TestSnapshot.cs | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index cdb54261f..44e6e5cf9 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -85,6 +85,7 @@ public void IncreaseBlockCount(uint newHeight) if (blocks.Count() == 0) { newBlock = Blockchain.GenesisBlock; + snapshot.AddTransactions(newBlock.Transactions, newBlock.Index); } else { diff --git a/src/Neo.TestEngine/TestUtils/TestSnapshot.cs b/src/Neo.TestEngine/TestUtils/TestSnapshot.cs index fed05a5e3..80d0d419c 100644 --- a/src/Neo.TestEngine/TestUtils/TestSnapshot.cs +++ b/src/Neo.TestEngine/TestUtils/TestSnapshot.cs @@ -92,6 +92,11 @@ public Block TryGetBlock(uint index) public void AddTransactions(Transaction[] txs, int blockIndex = -1) { uint index = blockIndex >= 0 ? (uint)blockIndex : Height; + AddTransactions(txs, index); + } + + public void AddTransactions(Transaction[] txs, uint index) + { if (Transactions is TestDataCache transactions) { foreach (var tx in txs) From 4dfd20a66069fc35869bc0975c8a383226ef4ea0 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Tue, 15 Dec 2020 18:07:40 -0300 Subject: [PATCH 24/77] code review --- src/Neo.TestEngine/Engine.cs | 15 ++++++++++----- src/Neo.TestEngine/Program.cs | 4 ++-- src/Neo.TestEngine/SmartContractTest.cs | 4 ++-- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index 44e6e5cf9..e7d90ad14 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -68,12 +68,17 @@ public void AddSmartContract(string path) var builtScript = engine.Build(path); var hash = builtScript.finalNEFScript.ToScriptHash(); - engine.Snapshot.Contracts.Add(hash, new Ledger.ContractState() + var snapshot = engine.Snapshot.Contracts; + + if (!snapshot.Contains(hash)) { - Hash = hash, - Script = builtScript.finalNEFScript, - Manifest = ContractManifest.FromJson(JObject.Parse(builtScript.finalManifest)), - }); + snapshot.Add(hash, new ContractState() + { + Hash = hash, + Script = builtScript.finalNEFScript, + Manifest = ContractManifest.FromJson(JObject.Parse(builtScript.finalManifest)), + }); + } } public void IncreaseBlockCount(uint newHeight) diff --git a/src/Neo.TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs index 97b211f2e..41bb98ba4 100644 --- a/src/Neo.TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -33,9 +33,9 @@ public static JObject Run(string[] args) var input = JObject.Parse(args[0]); return RunWithJson(input); } - catch + catch (Exception e) { - // if the first input is not a json, verifies if the arguments are: nef path, method name, method args + return BuildJsonException(e.Message); } } diff --git a/src/Neo.TestEngine/SmartContractTest.cs b/src/Neo.TestEngine/SmartContractTest.cs index 001f07906..de87959c2 100644 --- a/src/Neo.TestEngine/SmartContractTest.cs +++ b/src/Neo.TestEngine/SmartContractTest.cs @@ -7,8 +7,8 @@ namespace Neo.TestingEngine { public class SmartContractTest { - public string nefPath; - public string methodName; + public readonly string nefPath; + public readonly string methodName; public JArray methodParameters; public Dictionary storage; public List contracts; From f47fbc8667eefcb812a5e0ed5a386d9785db5513 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Thu, 17 Dec 2020 11:34:02 -0300 Subject: [PATCH 25/77] change path in the test workflow --- .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 e9efe9b0f..019f7398b 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -30,7 +30,7 @@ jobs: - name: Test Neo.SmartContract.Framework.UnitTests run: dotnet test tests/Neo.SmartContract.Framework.UnitTests /p:CollectCoverage=true /p:CoverletOutput=${GITHUB_WORKSPACE}/coverage/lcov /p:MergeWith=${GITHUB_WORKSPACE}/coverage/coverage.json /p:Exclude=\"[Neo.SmartContract.*]*,[Neo.Compiler.MSIL.UnitTests]*,[Neo.Compiler.MSIL.UnitTests.*]*\" /p:CoverletOutputFormat=lcov - name: Test Template.NEP5.UnitTests - run: dotnet test tests/Template.NEP5.UnitTests /p:CollectCoverage=true /p:CoverletOutput=${GITHUB_WORKSPACE}/coverage/lcov /p:MergeWith=${GITHUB_WORKSPACE}/coverage/coverage.json /p:Exclude=\"[Neo.SmartContract.*]*,[Neo.Compiler.MSIL.UnitTests]*,[Neo.Compiler.MSIL.UnitTests.*]*\" /p:CoverletOutputFormat=lcov + run: dotnet test tests/Template.NEP17.UnitTests /p:CollectCoverage=true /p:CoverletOutput=${GITHUB_WORKSPACE}/coverage/lcov /p:MergeWith=${GITHUB_WORKSPACE}/coverage/coverage.json /p:Exclude=\"[Neo.SmartContract.*]*,[Neo.Compiler.MSIL.UnitTests]*,[Neo.Compiler.MSIL.UnitTests.*]*\" /p:CoverletOutputFormat=lcov - name: Test Neo.TestEngine.UnitTests run: dotnet test tests/Neo.TestEngine.UnitTests /p:CollectCoverage=true /p:CoverletOutput=${GITHUB_WORKSPACE}/coverage/lcov /p:MergeWith=${GITHUB_WORKSPACE}/coverage/coverage.json /p:Exclude=\"[Neo.SmartContract.*]*,[Neo.Compiler.MSIL.UnitTests]*,[Neo.Compiler.MSIL.UnitTests.*]*\" /p:CoverletOutputFormat=lcov - name: Coveralls From 561844216f53d9dcd818bc14f762cc850dadaeac Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Thu, 17 Dec 2020 20:08:33 -0300 Subject: [PATCH 26/77] change storage json serialization/deserialization --- .gitignore | 2 +- src/Neo.TestEngine/Engine.cs | 12 ++-------- src/Neo.TestEngine/Helper.cs | 19 ++++++++++++--- src/Neo.TestEngine/Neo.TestEngine.csproj | 1 + src/Neo.TestEngine/Program.cs | 30 +++++++++++++++++++----- src/Neo.TestEngine/SmartContractTest.cs | 6 ++--- 6 files changed, 47 insertions(+), 23 deletions(-) diff --git a/.gitignore b/.gitignore index a6b1ef7d9..e4817a7ad 100644 --- a/.gitignore +++ b/.gitignore @@ -250,4 +250,4 @@ paket-files/ # JetBrains Rider .idea/ *.sln.iml -/src/Neo.Compiler.MSIL/Properties/launchSettings.json +**/launchSettings.json diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index 19b5b664a..bb1840d09 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -109,18 +109,10 @@ public void IncreaseBlockCount(uint newHeight) snapshot.SetCurrentBlockHash(index, lastBlock?.Hash ?? newBlock.Hash); } - public void SetStorage(Dictionary storage) + public void SetStorage(Dictionary storage) { - foreach (var data in storage) + foreach (var (key, value) in storage) { - var key = new StorageKey() - { - Key = data.Key.GetSpan().ToArray() - }; - var value = new StorageItem() - { - Value = data.Value.GetSpan().ToArray() - }; ((TestDataCache)engine.Snapshot.Storages).AddForTest(key, value); } } diff --git a/src/Neo.TestEngine/Helper.cs b/src/Neo.TestEngine/Helper.cs index f6f4578e3..4ea4d9818 100644 --- a/src/Neo.TestEngine/Helper.cs +++ b/src/Neo.TestEngine/Helper.cs @@ -56,14 +56,27 @@ public static JObject ToJson(this NotifyEventArgs notification) public static JObject ToJson(this DataCache storage) { - var storageMap = new Map(); + var jsonStorage = new JArray(); foreach (var storagePair in storage.Seek()) { var key = new ByteString(storagePair.Key.Key); var value = new ByteString(storagePair.Value.Value); - storageMap[key] = value; + + var jsonKey = new JObject(); + jsonKey["id"] = storagePair.Key.Id; + jsonKey["key"] = key.ToJson(); + + var jsonValue = new JObject(); + jsonValue["isconstant"] = storagePair.Value.IsConstant; + jsonValue["value"] = value.ToJson(); + + var storageItem = new JObject(); + storageItem["key"] = jsonKey; + storageItem["value"] = jsonValue; + + jsonStorage.Add(storageItem); } - return storageMap.ToJson()["value"]; + return jsonStorage; } public static JObject ToSimpleJson(this Transaction tx) diff --git a/src/Neo.TestEngine/Neo.TestEngine.csproj b/src/Neo.TestEngine/Neo.TestEngine.csproj index 59062231f..4d33aa82f 100644 --- a/src/Neo.TestEngine/Neo.TestEngine.csproj +++ b/src/Neo.TestEngine/Neo.TestEngine.csproj @@ -23,6 +23,7 @@ + diff --git a/src/Neo.TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs index e8ab84d19..acd800f89 100644 --- a/src/Neo.TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -1,4 +1,5 @@ using Neo.IO.Json; +using Neo.Ledger; using Neo.Network.P2P.Payloads; using Neo.SmartContract; using Neo.VM; @@ -211,8 +212,8 @@ public static JObject Run(SmartContractTest smartContractTest) /// Converts the data in a json array to a dictionary of StackItem /// /// json array with the map values to be converted - /// Returns the built StackItem dictionary - private static Dictionary GetStorageFromJson(JObject jsonStorage) + /// Returns the built dictionary + private static Dictionary GetStorageFromJson(JObject jsonStorage) { if (!(jsonStorage is JArray storage)) { @@ -220,22 +221,39 @@ private static Dictionary GetStorageFromJson(JObject j } var missingFieldMessage = "Missing field '{0}'"; - var items = new Dictionary(); + var items = new Dictionary(); foreach (var pair in storage) { if (!pair.ContainsProperty("key")) { throw new Exception(string.Format(missingFieldMessage, "key")); } + var jsonKey = pair["key"]; + if (!jsonKey.ContainsProperty("id") || !jsonKey.ContainsProperty("key")) + { + throw new Exception(string.Format(missingFieldMessage, "key")); + } if (!pair.ContainsProperty("value")) { throw new Exception(string.Format(missingFieldMessage, "value")); } + var jsonValue = pair["value"]; + if (!jsonValue.ContainsProperty("isconstant") || !jsonValue.ContainsProperty("value")) + { + throw new Exception(string.Format(missingFieldMessage, "value")); + } - var key = (PrimitiveType)ContractParameter.FromJson(pair["key"]).ToStackItem(); - var value = ContractParameter.FromJson(pair["value"]).ToStackItem(); - items[key] = value; + var key = (PrimitiveType)ContractParameter.FromJson(jsonKey["key"]).ToStackItem(); + var value = ContractParameter.FromJson(jsonValue["value"]).ToStackItem(); + + var storageKey = new StorageKey() + { + Id = int.Parse(jsonKey["id"].AsString()), + Key = key.GetSpan().ToArray() + }; + var storageItem = new StorageItem(value.GetSpan().ToArray(), jsonValue["isconstant"].AsBoolean()); + items[storageKey] = storageItem; } return items; diff --git a/src/Neo.TestEngine/SmartContractTest.cs b/src/Neo.TestEngine/SmartContractTest.cs index de87959c2..690e633d8 100644 --- a/src/Neo.TestEngine/SmartContractTest.cs +++ b/src/Neo.TestEngine/SmartContractTest.cs @@ -1,6 +1,6 @@ using Neo.IO.Json; +using Neo.Ledger; using Neo.Network.P2P.Payloads; -using Neo.VM.Types; using System.Collections.Generic; namespace Neo.TestingEngine @@ -10,7 +10,7 @@ public class SmartContractTest public readonly string nefPath; public readonly string methodName; public JArray methodParameters; - public Dictionary storage; + public Dictionary storage; public List contracts; public uint currentHeight = 0; public UInt160[] signers; @@ -21,7 +21,7 @@ public SmartContractTest(string path, string method, JArray parameters) nefPath = path; methodName = method; methodParameters = parameters; - storage = new Dictionary(); + storage = new Dictionary(); contracts = new List(); signers = new UInt160[] { }; blocks = new Block[] { }; From 88e916bf5790038b91ad9cc1b863872115f43f45 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Thu, 7 Jan 2021 14:34:35 -0300 Subject: [PATCH 27/77] fix unit-test --- src/Neo.TestEngine/Engine.cs | 1 + .../UnitTest_Invoke.cs | 27 ++++++++++++------- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index bb1840d09..54b2a48fe 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -35,6 +35,7 @@ public static Engine Instance private Engine() { + var _ = TestBlockchain.TheNeoSystem; Reset(); } diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs index c27d8b676..6a5213d0d 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs @@ -275,20 +275,28 @@ public void Test_Json_With_Parameters() [TestMethod] public void Test_Json_With_Storage() { - StackItem arguments = 16; PrimitiveType key = "example"; - StackItem value = 123; + key = new ByteString(key.GetSpan().ToArray()); + var storageKey = new JObject(); + storageKey["id"] = 0; + storageKey["key"] = key.ToParameter().ToJson(); - Map storage = new Map() - { - [key] = value - }; + StackItem value = "123"; + value = new ByteString(value.GetSpan().ToArray()); + var storageValue = new JObject(); + storageValue["isconstant"] = false; + storageValue["value"] = value.ToParameter().ToJson(); + var storageItem = new JObject(); + storageItem["key"] = storageKey; + storageItem["value"] = storageValue; + + StackItem arguments = 16; var json = new JObject(); json["path"] = "./TestClasses/Contract1.nef"; json["method"] = "testArgs1"; json["arguments"] = new JArray() { arguments.ToParameter().ToJson() }; - json["storage"] = storage.ToParameter().ToJson()["value"]; + json["storage"] = new JArray() { storageItem }; var args = new string[] { json.AsString() @@ -299,13 +307,14 @@ public void Test_Json_With_Storage() Assert.IsTrue(result.ContainsProperty("storage")); Assert.IsInstanceOfType(result["storage"], typeof(JArray)); - storage[key] = value.GetSpan().ToArray(); + storageKey["key"] = key.ToJson(); + storageValue["value"] = value.ToJson(); var storageArray = result["storage"] as JArray; var contains = false; foreach (var pair in storageArray) { - if (pair.AsString() == storage.ToJson()["value"].AsString()) + if (pair.AsString() == storageItem.AsString()) { contains = true; break; From d24350b5a5bd0acb01e93ad75293456abe01027b Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Thu, 7 Jan 2021 18:50:20 -0300 Subject: [PATCH 28/77] usa Directory.Build.props to set the same Neo version for the compiler and the testengine --- Directory.Build.props | 4 ++++ src/Neo.Compiler.MSIL/Neo.Compiler.MSIL.csproj | 1 - src/Neo.TestEngine/Helper.cs | 3 ++- src/Neo.TestEngine/Neo.TestEngine.csproj | 4 ---- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Directory.Build.props b/Directory.Build.props index 682b3a598..cc063974e 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -12,4 +12,8 @@ git https://github.com/neo-project/neo-devpack-dotnet.git + + + + diff --git a/src/Neo.Compiler.MSIL/Neo.Compiler.MSIL.csproj b/src/Neo.Compiler.MSIL/Neo.Compiler.MSIL.csproj index 45866a112..a14d9a3d5 100644 --- a/src/Neo.Compiler.MSIL/Neo.Compiler.MSIL.csproj +++ b/src/Neo.Compiler.MSIL/Neo.Compiler.MSIL.csproj @@ -41,7 +41,6 @@ - diff --git a/src/Neo.TestEngine/Helper.cs b/src/Neo.TestEngine/Helper.cs index 67ef469fe..6b037af96 100644 --- a/src/Neo.TestEngine/Helper.cs +++ b/src/Neo.TestEngine/Helper.cs @@ -105,13 +105,14 @@ private static string GetExceptionMessage(Exception exception) public static ScriptBuilder EmitAppCall(this ScriptBuilder sb, UInt160 scriptHash, string operation, params ContractParameter[] args) { + sb.EmitPush(CallFlags.All); for (int i = args.Length - 1; i >= 0; i--) sb.EmitPush(args[i]); sb.EmitPush(args.Length); sb.Emit(OpCode.PACK); sb.EmitPush(operation); sb.EmitPush(scriptHash); - sb.EmitSysCall(ApplicationEngine.System_Contract_Call); + sb.EmitSysCall(ApplicationEngine.System_Contract_CallEx); return sb; } diff --git a/src/Neo.TestEngine/Neo.TestEngine.csproj b/src/Neo.TestEngine/Neo.TestEngine.csproj index a7b101d82..4561180d2 100644 --- a/src/Neo.TestEngine/Neo.TestEngine.csproj +++ b/src/Neo.TestEngine/Neo.TestEngine.csproj @@ -17,10 +17,6 @@ TestingEngine - - - - From de7dee1fb93746245e177e782dcfeece9808dc36 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Tue, 19 Jan 2021 17:49:06 -0300 Subject: [PATCH 29/77] fix add contract --- src/Neo.TestEngine/Engine.cs | 2 +- src/Neo.TestEngine/Extensions/TestExtensions.cs | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index a0126fc2c..dbe5a7fd0 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -72,7 +72,7 @@ public void AddSmartContract(string path) if (!snapshot.ContainsContract(hash)) { - snapshot.ContractAdd(new ContractState() + snapshot.TryContractAdd(new ContractState() { Hash = hash, Nef = builtScript.nefFile, diff --git a/src/Neo.TestEngine/Extensions/TestExtensions.cs b/src/Neo.TestEngine/Extensions/TestExtensions.cs index c52ebaedd..1eddeb538 100644 --- a/src/Neo.TestEngine/Extensions/TestExtensions.cs +++ b/src/Neo.TestEngine/Extensions/TestExtensions.cs @@ -32,5 +32,16 @@ public static void DeployNativeContracts(this StoreView snapshot, Block persisti var engine = new TestEngine(TriggerType.OnPersist, null, snapshot, persistingBlock); method.Invoke(SmartContract.Native.NativeContract.ContractManagement, new object[] { engine }); } + public static bool TryContractAdd(this StoreView snapshot, ContractState contract) + { + var key = new KeyBuilder(-1, 8).Add(contract.Hash); + if (snapshot.Storages.Contains(key)) + { + return false; + } + + snapshot.Storages.Add(key, new StorageItem(contract)); + return true; + } } } From a79b25eb92e581c4e5e3de59cc953a93f662583e Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Wed, 20 Jan 2021 13:59:21 -0300 Subject: [PATCH 30/77] use contract id instead of hard coded id --- .../Extensions/TestExtensions.cs | 20 +++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/Neo.TestEngine/Extensions/TestExtensions.cs b/src/Neo.TestEngine/Extensions/TestExtensions.cs index 1eddeb538..a51e98d4e 100644 --- a/src/Neo.TestEngine/Extensions/TestExtensions.cs +++ b/src/Neo.TestEngine/Extensions/TestExtensions.cs @@ -3,6 +3,7 @@ using Neo.Network.P2P.Payloads; using Neo.Persistence; using Neo.SmartContract; +using Neo.SmartContract.Native; namespace Neo.TestingEngine { @@ -10,31 +11,34 @@ public static class TestExtensions { public static void ContractAdd(this StoreView snapshot, ContractState contract) { - var key = new KeyBuilder(-1, 8).Add(contract.Hash); + var key = new KeyBuilder(NativeContract.ContractManagement.Id, 8).Add(contract.Hash); snapshot.Storages.Add(key, new StorageItem(contract)); } public static bool ContainsContract(this StoreView snapshot, UInt160 hash) { - var key = new KeyBuilder(0, 8).Add(hash); - return snapshot.Storages.Contains(key); + return NativeContract.ContractManagement.GetContract(snapshot, hash) != null; } public static void DeleteContract(this StoreView snapshot, UInt160 hash) { - var key = new KeyBuilder(0, 8).Add(hash); - snapshot.Storages.Delete(key); + var contract = NativeContract.ContractManagement.GetContract(snapshot, hash); + if (contract != null) + { + var key = new KeyBuilder(contract.Id, 8).Add(hash); + snapshot.Storages.Delete(key); + } } public static void DeployNativeContracts(this StoreView snapshot, Block persistingBlock = null) { persistingBlock ??= new Block() { Index = 0 }; - var method = typeof(SmartContract.Native.ContractManagement).GetMethod("OnPersist", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); + var method = typeof(ContractManagement).GetMethod("OnPersist", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var engine = new TestEngine(TriggerType.OnPersist, null, snapshot, persistingBlock); - method.Invoke(SmartContract.Native.NativeContract.ContractManagement, new object[] { engine }); + method.Invoke(NativeContract.ContractManagement, new object[] { engine }); } public static bool TryContractAdd(this StoreView snapshot, ContractState contract) { - var key = new KeyBuilder(-1, 8).Add(contract.Hash); + var key = new KeyBuilder(NativeContract.ContractManagement.Id, 8).Add(contract.Hash); if (snapshot.Storages.Contains(key)) { return false; From 0ea2a098b99d30a5afd24c82c55d801a553e5225 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Tue, 2 Feb 2021 16:10:53 -0300 Subject: [PATCH 31/77] fixed testengine unit tests --- src/Neo.TestEngine/Engine.cs | 39 +++++---- src/Neo.TestEngine/Helper.cs | 14 ++-- .../TestUtils/TestBlockchain.cs | 81 ++++++++++++++----- src/Neo.TestEngine/TestUtils/TestDataCache.cs | 22 ++--- .../Services/Neo/BlockchainTest.cs | 2 +- .../TestClasses/Contract_Time.cs | 2 +- 6 files changed, 101 insertions(+), 59 deletions(-) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index 963dc9c5b..9fb40d500 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -46,7 +46,6 @@ private Engine() public void Reset() { engine = SetupNativeContracts(); - IncreaseBlockCount(0); } public void SetTestEngine(string path) @@ -91,7 +90,7 @@ public void IncreaseBlockCount(uint newHeight) if (snapshot.Blocks().Count == 0) { newBlock = Blockchain.GenesisBlock; - snapshot.AddTransactions(newBlock.Transactions, newBlock.Index); + snapshot.AddOrUpdateTransactions(newBlock.Transactions, newBlock.Index); } else { @@ -102,7 +101,7 @@ public void IncreaseBlockCount(uint newHeight) { var hash = newBlock.Hash; var trim = newBlock.Trim(); - snapshot.BlocksAdd(hash, trim); + snapshot.BlocksAddOrUpdate(hash, trim); lastBlock = newBlock; newBlock = CreateBlock(); } @@ -113,10 +112,13 @@ public void IncreaseBlockCount(uint newHeight) public void SetStorage(Dictionary storage) { - //foreach (var (key, value) in storage) - //{ - // ((TestDataCache)engine.Snapshot.Storages).AddForTest(key, value); - //} + if (engine.Snapshot is TestDataCache snapshot) + { + foreach (var (key, value) in storage) + { + snapshot.AddForTest(key, value); + } + } } public void SetSigners(UInt160[] signerAccounts) @@ -132,12 +134,13 @@ public void AddBlock(Block block) if (engine.Snapshot is TestDataCache snapshot) { Block currentBlock = null; - if (Height < block.Index) + if (Height < block.Index || snapshot.Blocks().Count == 0) { IncreaseBlockCount(block.Index); - currentBlock = CreateBlock(block); + currentBlock = engine.Snapshot.GetLastBlock(); } - else { + else + { currentBlock = NativeContract.Ledger.GetBlock(snapshot, block.Index); } @@ -162,10 +165,11 @@ public void AddBlock(Block block) tx.ValidUntilBlock = block.Index + Transaction.MaxValidUntilBlockIncrement; } - snapshot.UpdateChangedBlocks(hash, currentBlock.Hash, currentBlock.Trim()); + var trimmed = currentBlock.Trim(); + snapshot.UpdateChangedBlocks(hash, trimmed.Hash, trimmed); } - snapshot.AddTransactions(block.Transactions); + snapshot.AddOrUpdateTransactions(block.Transactions); } } @@ -189,6 +193,7 @@ public JObject Run(string method, ContractParameter[] args) engine.PersistingBlock.MerkleRoot = lastBlock.MerkleRoot; currentTx.ValidUntilBlock = lastBlock.Index; + snapshot.SetCurrentBlockHash(lastBlock.Index, lastBlock.Hash); } using (ScriptBuilder scriptBuilder = new ScriptBuilder()) @@ -227,14 +232,18 @@ private TestEngine SetupNativeContracts() TestEngine engine = new TestEngine(TriggerType.Application, currentTx, new TestDataCache(), persistingBlock: new Block() { Index = 0 }); engine.ClearNotifications(); - //((TestSnapshot)engine.Snapshot).ClearStorage(); - return engine; } private Block CreateBlock(Block originBlock = null) { - var trimmedBlock = engine.Snapshot.Blocks().Last(); + TrimmedBlock trimmedBlock = null; + var blocks = engine.Snapshot.Blocks(); + if (blocks.Count > 0) + { + trimmedBlock = blocks.Last(); + } + if (trimmedBlock == null) { trimmedBlock = Blockchain.GenesisBlock.Trim(); diff --git a/src/Neo.TestEngine/Helper.cs b/src/Neo.TestEngine/Helper.cs index c35892cd8..7d5d2bfbd 100644 --- a/src/Neo.TestEngine/Helper.cs +++ b/src/Neo.TestEngine/Helper.cs @@ -53,26 +53,28 @@ public static JObject ToJson(this NotifyEventArgs notification) public static JObject ToJson(this DataCache storage) { var jsonStorage = new JArray(); - foreach (var storagePair in storage.Seek()) + // had to filter which data should be returned back, since everything is in the storage now + var newStorage = storage.GetStorageOnly(); + + foreach (var (storageKey, storageValue) in newStorage) { - var key = new ByteString(storagePair.Key.Key); + var key = new ByteString(storageKey.Key); StackItem value; try { - value = new ByteString(storagePair.Value.Value); + value = new ByteString(storageValue.Value); } catch { value = StackItem.Null; } - var jsonKey = new JObject(); - jsonKey["id"] = storagePair.Key.Id; + jsonKey["id"] = storageKey.Id; jsonKey["key"] = key.ToJson(); var jsonValue = new JObject(); - jsonValue["isconstant"] = storagePair.Value.IsConstant; + jsonValue["isconstant"] = storageValue.IsConstant; jsonValue["value"] = value.ToJson(); var storageItem = new JObject(); diff --git a/src/Neo.TestEngine/TestUtils/TestBlockchain.cs b/src/Neo.TestEngine/TestUtils/TestBlockchain.cs index 2ece54796..a1a0182f4 100644 --- a/src/Neo.TestEngine/TestUtils/TestBlockchain.cs +++ b/src/Neo.TestEngine/TestUtils/TestBlockchain.cs @@ -42,24 +42,20 @@ public static StorageKey CreateStorageKey(this NativeContract contract, byte pre return new KeyBuilder(contract.Id, prefix).AddBigEndian(value); } - public static void BlocksDelete(this DataCache snapshot, UInt256 hash) + public static List<(StorageKey, StorageItem)> GetStorageOnly(this DataCache snapshot) { - snapshot.Delete(NativeContract.Ledger.CreateStorageKey(Prefix_BlockHash, hash)); - snapshot.Delete(NativeContract.Ledger.CreateStorageKey(Prefix_Block, hash)); - } - - public static void TransactionAdd(this DataCache snapshot, params TransactionState[] txs) - { - foreach (TransactionState tx in txs) + var nativeTokens = new int[] { - snapshot.Add(NativeContract.Ledger.CreateStorageKey(Prefix_Transaction, tx.Transaction.Hash), new StorageItem(tx, true)); - } + NativeContract.GAS.Id, NativeContract.NEO.Id + }; + + return snapshot.Find().Where(pair => pair.Key.Id >= 0 || nativeTokens.Contains(pair.Key.Id)).ToList(); } - public static bool ContainsTransaction(this DataCache snapshot, Transaction tx) + public static void BlocksDelete(this DataCache snapshot, UInt256 hash, TrimmedBlock block) { - var key = NativeContract.Ledger.CreateStorageKey(Prefix_Transaction, tx.Hash); - return snapshot.Contains(key); + snapshot.Delete(NativeContract.Ledger.CreateStorageKey(Prefix_BlockHash, block.Index)); + snapshot.Delete(NativeContract.Ledger.CreateStorageKey(Prefix_Block, hash)); } public static void BlocksAdd(this DataCache snapshot, UInt256 hash, TrimmedBlock block) @@ -70,9 +66,15 @@ public static void BlocksAdd(this DataCache snapshot, UInt256 hash, TrimmedBlock public static void UpdateChangedBlocks(this DataCache snapshot, UInt256 oldHash, UInt256 newHash, TrimmedBlock block) { - if (snapshot.Contains(NativeContract.Ledger.CreateStorageKey(Prefix_BlockHash, oldHash))) + if (snapshot.Contains(NativeContract.Ledger.CreateStorageKey(Prefix_Block, oldHash))) { - snapshot.BlocksDelete(oldHash); + var oldBlock = NativeContract.Ledger.GetBlock(snapshot, oldHash); + snapshot.BlocksDelete(oldHash, oldBlock.Trim()); + } + + if (snapshot.Contains(NativeContract.Ledger.CreateStorageKey(Prefix_Block, newHash))) + { + snapshot.BlocksDelete(newHash, block); } snapshot.BlocksAdd(newHash, block); } @@ -98,6 +100,19 @@ public static Block TryGetBlock(this DataCache snapshot, uint index) return NativeContract.Ledger.GetBlock(snapshot, index); } + public static void BlocksAddOrUpdate(this DataCache snapshot, UInt256 hash, TrimmedBlock block) + { + var existingBlock = NativeContract.Ledger.GetBlock(snapshot, block.Index); + if (existingBlock != null) + { + snapshot.UpdateChangedBlocks(existingBlock.Hash, hash, block); + } + else + { + snapshot.BlocksAdd(hash, block); + } + } + public static List Blocks(this DataCache snapshot) { var blockKey = NativeContract.Ledger.CreateStorageKey(Prefix_Block); @@ -106,6 +121,14 @@ public static List Blocks(this DataCache snapshot) .OrderBy(b => b.Index).ToList(); } + public static List BlocksIndex(this DataCache snapshot) + { + var blockKey = NativeContract.Ledger.CreateStorageKey(Prefix_BlockHash); + return snapshot.Find(blockKey.ToArray()) + .Select(item => new UInt256(item.Value.ToArray())) + .ToList(); + } + public static Block GetLastBlock(this DataCache snapshot) { var trim = snapshot.Blocks().Last(); @@ -126,13 +149,33 @@ public static void SetCurrentBlockHash(this DataCache snapshot, uint index, UInt item.Value = BinarySerializer.Serialize(hashIndex.ToStackItem(null), MaxStackSize); } - public static void AddTransactions(this DataCache snapshot, Transaction[] txs, int blockIndex = -1) + public static void TransactionAddOrUpdate(this DataCache snapshot, params TransactionState[] txs) + { + foreach (TransactionState tx in txs) + { + var key = NativeContract.Ledger.CreateStorageKey(Prefix_Transaction, tx.Transaction.Hash); + + if (snapshot.Contains(key)) + { + snapshot.Delete(key); + } + snapshot.Add(key, new StorageItem(tx, true)); + } + } + + public static bool ContainsTransaction(this DataCache snapshot, Transaction tx) + { + var key = NativeContract.Ledger.CreateStorageKey(Prefix_Transaction, tx.Hash); + return snapshot.Contains(key); + } + + public static void AddOrUpdateTransactions(this DataCache snapshot, Transaction[] txs, int blockIndex = -1) { uint index = blockIndex >= 0 ? (uint)blockIndex : NativeContract.Ledger.CurrentIndex(snapshot); - snapshot.AddTransactions(txs, index); + snapshot.AddOrUpdateTransactions(txs, index); } - public static void AddTransactions(this DataCache snapshot, Transaction[] txs, uint index) + public static void AddOrUpdateTransactions(this DataCache snapshot, Transaction[] txs, uint index) { var states = new List(); foreach (var tx in txs) @@ -151,7 +194,7 @@ public static void AddTransactions(this DataCache snapshot, Transaction[] txs, u states.Add(state); } - snapshot.TransactionAdd(states.ToArray()); + snapshot.TransactionAddOrUpdate(states.ToArray()); } } } diff --git a/src/Neo.TestEngine/TestUtils/TestDataCache.cs b/src/Neo.TestEngine/TestUtils/TestDataCache.cs index 5408f4121..cf04298fd 100644 --- a/src/Neo.TestEngine/TestUtils/TestDataCache.cs +++ b/src/Neo.TestEngine/TestUtils/TestDataCache.cs @@ -55,28 +55,16 @@ protected override void UpdateInternal(StorageKey key, StorageItem value) dict[key] = value; } - /// - /// Clear the storage for unit test - /// - public void Clear() - { - dict.Clear(); - } - - /// - /// Gets the size of the storage for unit test - /// - public int Count() - { - return dict.Count; - } - /// /// Include a new value to the storage for unit test /// public void AddForTest(StorageKey key, StorageItem value) { - AddInternal(key, value); + if (Contains(key)) + { + Delete(key); + } + Add(key, value); } } } diff --git a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/BlockchainTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/BlockchainTest.cs index 35579f256..74e366feb 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/BlockchainTest.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/Services/Neo/BlockchainTest.cs @@ -44,7 +44,7 @@ public void Init() }; snapshot.BlocksAdd(_block.Hash, _block.Trim()); - snapshot.TransactionAdd(new TransactionState() + snapshot.TransactionAddOrUpdate(new TransactionState() { BlockIndex = _block.Index, Transaction = _block.Transactions[0] diff --git a/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_Time.cs b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_Time.cs index 3dbefc8b3..ee34f200d 100644 --- a/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_Time.cs +++ b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_Time.cs @@ -12,7 +12,7 @@ public static ulong getTime() public static object getBlock(uint blockIndex) { - return Ledger.GetTransactionFromBlock(blockIndex, 0); + return Ledger.GetBlock(blockIndex); } } } From c8346d2c467212a1b6699f0296fb49f7e446ba54 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Fri, 5 Feb 2021 18:20:45 -0300 Subject: [PATCH 32/77] can execute included smart contracts and native by scripthash as well --- src/Neo.TestEngine/Engine.cs | 32 ++++++++++++++--- .../Extensions/TestExtensions.cs | 2 +- src/Neo.TestEngine/Program.cs | 32 ++++++++++++----- src/Neo.TestEngine/SmartContractTest.cs | 14 ++++++-- src/Neo.TestEngine/TestContract.cs | 3 ++ src/Neo.TestEngine/TestUtils/BuildNEF.cs | 4 +-- src/Neo.TestEngine/TestUtils/BuildNative.cs | 31 ++++++++++++++++ src/Neo.TestEngine/TestUtils/TestEngine.cs | 35 +++++++++++++++++++ 8 files changed, 135 insertions(+), 18 deletions(-) create mode 100644 src/Neo.TestEngine/TestUtils/BuildNative.cs diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index 9fb40d500..1cdf3bd65 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -8,7 +8,6 @@ using Neo.SmartContract.Manifest; using Neo.SmartContract.Native; using Neo.VM; -using Neo.VM.Types; using System.Collections.Generic; using System.Linq; @@ -48,12 +47,17 @@ public void Reset() engine = SetupNativeContracts(); } - public void SetTestEngine(string path) + public void SetEntryScript(string path) { engine.AddEntryScript(path); var manifest = ContractManifest.FromJson(JObject.Parse(engine.ScriptEntry.finalManifest)); var hash = engine.ScriptEntry.finalNEFScript.ToScriptHash(); + if (engine.Snapshot.ContainsContract(hash)) + { + engine.Snapshot.DeleteContract(hash); + } + engine.Snapshot.ContractAdd(new ContractState() { Hash = hash, @@ -62,7 +66,18 @@ public void SetTestEngine(string path) }); } - public void AddSmartContract(string path) + public void SetEntryScript(UInt160 contractHash) + { + engine.AddEntryScript(contractHash); + } + + public void AddSmartContract(TestContract contract) + { + var script = AddSmartContract(contract.nefPath); + contract.nefFile = script.nefFile; + } + + private BuildScript AddSmartContract(string path) { var builtScript = engine.Build(path); var hash = builtScript.finalNEFScript.ToScriptHash(); @@ -78,6 +93,8 @@ public void AddSmartContract(string path) Manifest = ContractManifest.FromJson(JObject.Parse(builtScript.finalManifest)), }); } + + return builtScript; } public void IncreaseBlockCount(uint newHeight) @@ -203,7 +220,14 @@ public JObject Run(string method, ContractParameter[] args) } var stackItemsArgs = args.Select(a => a.ToStackItem()).ToArray(); - engine.GetMethod(method).RunEx(stackItemsArgs); + if (engine.ScriptEntry is BuildNative) + { + engine.RunNativeContract(method, stackItemsArgs); + } + else + { + engine.GetMethod(method).RunEx(stackItemsArgs); + } //currentTx.ValidUntilBlock = engine.Snapshot.Height + Transaction.MaxValidUntilBlockIncrement; currentTx.SystemFee = engine.GasConsumed; diff --git a/src/Neo.TestEngine/Extensions/TestExtensions.cs b/src/Neo.TestEngine/Extensions/TestExtensions.cs index b343d6848..bca5cc60e 100644 --- a/src/Neo.TestEngine/Extensions/TestExtensions.cs +++ b/src/Neo.TestEngine/Extensions/TestExtensions.cs @@ -23,7 +23,7 @@ public static void DeleteContract(this DataCache snapshot, UInt160 hash) var contract = NativeContract.ContractManagement.GetContract(snapshot, hash); if (contract != null) { - var key = new KeyBuilder(contract.Id, 8).Add(hash); + var key = new KeyBuilder(NativeContract.ContractManagement.Id, 8).Add(hash); snapshot.Delete(key); } } diff --git a/src/Neo.TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs index d97b07b6b..cb3e0e7af 100644 --- a/src/Neo.TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -1,5 +1,4 @@ using Neo.IO.Json; -using Neo.Ledger; using Neo.Network.P2P.Payloads; using Neo.SmartContract; using Neo.VM; @@ -113,7 +112,7 @@ public static JObject RunWithMethodName(string path, string methodName, string j public static JObject RunWithJson(JObject json) { var missigFieldMessage = "Missing field: '{0}'"; - if (!json.ContainsProperty("path")) + if (!json.ContainsProperty("path") && !json.ContainsProperty("scripthash")) { return BuildJsonException(string.Format(missigFieldMessage, "path")); } @@ -130,11 +129,21 @@ public static JObject RunWithJson(JObject json) try { - var path = json["path"].AsString(); var methodName = json["method"].AsString(); var parameters = (JArray)json["arguments"]; - var smartContractTestCase = new SmartContractTest(path, methodName, parameters); + + SmartContractTest smartContractTestCase; + if (json.ContainsProperty("path") && json["path"].AsString().Length > 0) + { + var path = json["path"].AsString(); + smartContractTestCase = new SmartContractTest(path, methodName, parameters); + } + else + { + var scriptHash = UInt160.Parse(json["scripthash"].AsString()); + smartContractTestCase = new SmartContractTest(scriptHash, methodName, parameters); + } if (json.ContainsProperty("storage")) { @@ -177,10 +186,6 @@ public static JObject Run(SmartContractTest smartContractTest) { try { - IsValidNefPath(smartContractTest.nefPath); - - Engine.Instance.SetTestEngine(smartContractTest.nefPath); - if (smartContractTest.storage.Count > 0) { Engine.Instance.SetStorage(smartContractTest.storage); @@ -188,9 +193,18 @@ public static JObject Run(SmartContractTest smartContractTest) foreach (var contract in smartContractTest.contracts) { - Engine.Instance.AddSmartContract(contract.nefPath); + Engine.Instance.AddSmartContract(contract); } + if (smartContractTest.nefPath != null) + { + IsValidNefPath(smartContractTest.nefPath); + Engine.Instance.SetEntryScript(smartContractTest.nefPath); + } + else + { + Engine.Instance.SetEntryScript(smartContractTest.scriptHash); + } foreach (var block in smartContractTest.blocks.OrderBy(b => b.Index)) { Engine.Instance.AddBlock(block); diff --git a/src/Neo.TestEngine/SmartContractTest.cs b/src/Neo.TestEngine/SmartContractTest.cs index 21baf0ea2..444ce71f5 100644 --- a/src/Neo.TestEngine/SmartContractTest.cs +++ b/src/Neo.TestEngine/SmartContractTest.cs @@ -7,7 +7,8 @@ namespace Neo.TestingEngine { public class SmartContractTest { - public readonly string nefPath; + public readonly UInt160 scriptHash = null; + public readonly string nefPath = null; public readonly string methodName; public JArray methodParameters; public Dictionary storage; @@ -16,9 +17,18 @@ public class SmartContractTest public UInt160[] signers; public Block[] blocks; - public SmartContractTest(string path, string method, JArray parameters) + public SmartContractTest(string path, string method, JArray parameters) : this(method, parameters) { nefPath = path; + } + + public SmartContractTest(UInt160 scriptHash, string method, JArray parameters) : this(method, parameters) + { + this.scriptHash = scriptHash; + } + + private SmartContractTest(string method, JArray parameters) + { methodName = method; methodParameters = parameters; storage = new Dictionary(); diff --git a/src/Neo.TestEngine/TestContract.cs b/src/Neo.TestEngine/TestContract.cs index c68de708b..875709c51 100644 --- a/src/Neo.TestEngine/TestContract.cs +++ b/src/Neo.TestEngine/TestContract.cs @@ -1,8 +1,11 @@ +using Neo.SmartContract; + namespace Neo.TestingEngine { public class TestContract { internal string nefPath; + internal NefFile nefFile = null; public TestContract(string path) { diff --git a/src/Neo.TestEngine/TestUtils/BuildNEF.cs b/src/Neo.TestEngine/TestUtils/BuildNEF.cs index bdb9361b4..d96224282 100644 --- a/src/Neo.TestEngine/TestUtils/BuildNEF.cs +++ b/src/Neo.TestEngine/TestUtils/BuildNEF.cs @@ -11,8 +11,8 @@ public BuildNEF(NefFile nefFile, string manifestFile) : base(nefFile) UseOptimizer = false; Error = null; finalNEFScript = nefFile.Script; - JObject manifestAbi = JObject.Parse(manifestFile); - var abi = manifestAbi["abi"] as JObject; + JObject manifestJson = JObject.Parse(manifestFile); + var abi = manifestJson["abi"] as JObject; finalABI = abi; finalManifest = manifestFile; } diff --git a/src/Neo.TestEngine/TestUtils/BuildNative.cs b/src/Neo.TestEngine/TestUtils/BuildNative.cs new file mode 100644 index 000000000..5cd3b2cc1 --- /dev/null +++ b/src/Neo.TestEngine/TestUtils/BuildNative.cs @@ -0,0 +1,31 @@ +using Neo.IO.Json; +using Neo.SmartContract; +using Neo.SmartContract.Native; +using Neo.VM; + +namespace Neo.TestingEngine +{ + class BuildNative : BuildScript + { + public readonly NativeContract nativeContract; + public BuildNative(NativeContract nativeContract) : base() + { + this.nativeContract = nativeContract; + byte[] script; + using (ScriptBuilder sb = new ScriptBuilder()) + { + sb.EmitPush(nativeContract.Hash); + sb.EmitSysCall(ApplicationEngine.System_Contract_Call); + script = sb.ToArray(); + } + + IsBuild = true; + UseOptimizer = false; + Error = null; + JObject manifestJson = nativeContract.Manifest.ToJson(); + var abi = manifestJson["abi"] as JObject; + finalABI = abi; + finalNEFScript = script; + } + } +} diff --git a/src/Neo.TestEngine/TestUtils/TestEngine.cs b/src/Neo.TestEngine/TestUtils/TestEngine.cs index 49e28f4ff..091008a37 100644 --- a/src/Neo.TestEngine/TestUtils/TestEngine.cs +++ b/src/Neo.TestEngine/TestUtils/TestEngine.cs @@ -2,11 +2,13 @@ using Neo.Network.P2P.Payloads; using Neo.Persistence; using Neo.SmartContract; +using Neo.SmartContract.Native; using Neo.VM; using Neo.VM.Types; using System; using System.Collections.Generic; using System.IO; +using System.Linq; namespace Neo.TestingEngine { @@ -79,6 +81,39 @@ public void AddEntryScript(string[] filenames, bool releaseMode = false, bool op Reset(); } + public void AddEntryScript(UInt160 contractHash) + { + var nativeContract = NativeContract.GetContract(contractHash); + if (nativeContract != null) + { + ScriptEntry = new BuildNative(nativeContract); + } + else + { + var buildScripts = scriptsAll.Values.ToArray(); + var scriptHashes = buildScripts.Select(build => build.finalNEFScript.ToScriptHash()).ToList(); + + if (!scriptHashes.Contains(contractHash)) + { + new InvalidOperationException($"Contract Does Not Exist: {contractHash}"); + } + var index = scriptHashes.IndexOf(contractHash); + ScriptEntry = buildScripts[index]; + } + + Reset(); + } + + public void RunNativeContract(string method, StackItem[] parameters, CallFlags flags = CallFlags.All) + { + VM.Types.Array paramsArray = new VM.Types.Array(parameters); + ByteString methodName = method; + Integer callFlag = (uint)flags; + + var items = new StackItem[] { methodName, callFlag, paramsArray }; + ExecuteTestCaseStandard(method, items.ToArray()); + } + public void Reset() { this.State = VMState.BREAK; // Required for allow to reuse the same TestEngine From 0ceaf14a37785c14ee9cffeb5685c438f7587c12 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Fri, 5 Feb 2021 18:44:22 -0300 Subject: [PATCH 33/77] fix import --- .../UnitTest_ABI_ContractPermission.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ABI_ContractPermission.cs b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ABI_ContractPermission.cs index 3d4cc3f84..bb49de57b 100644 --- a/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ABI_ContractPermission.cs +++ b/tests/Neo.Compiler.MSIL.UnitTests/UnitTest_ABI_ContractPermission.cs @@ -1,6 +1,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.Compiler.MSIL.UnitTests.Utils; using Neo.IO.Json; +using Neo.TestingEngine; namespace Neo.Compiler.MSIL.UnitTests { From dd13f2243ced5f18e8c40a09a28ae01cdb51d7ef Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 1 Mar 2021 18:26:17 -0300 Subject: [PATCH 34/77] fix storage access between contracts --- src/Neo.TestEngine/Engine.cs | 29 ++++++------------- .../Extensions/TestExtensions.cs | 11 ++++++- 2 files changed, 19 insertions(+), 21 deletions(-) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index 1cdf3bd65..cbbf2de6a 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -50,20 +50,7 @@ public void Reset() public void SetEntryScript(string path) { engine.AddEntryScript(path); - var manifest = ContractManifest.FromJson(JObject.Parse(engine.ScriptEntry.finalManifest)); - var hash = engine.ScriptEntry.finalNEFScript.ToScriptHash(); - - if (engine.Snapshot.ContainsContract(hash)) - { - engine.Snapshot.DeleteContract(hash); - } - - engine.Snapshot.ContractAdd(new ContractState() - { - Hash = hash, - Nef = engine.ScriptEntry.nefFile, - Manifest = manifest, - }); + AddSmartContract(path); } public void SetEntryScript(UInt160 contractHash) @@ -73,11 +60,11 @@ public void SetEntryScript(UInt160 contractHash) public void AddSmartContract(TestContract contract) { - var script = AddSmartContract(contract.nefPath); - contract.nefFile = script.nefFile; + var state = AddSmartContract(contract.nefPath); + contract.nefFile = state.Nef; } - private BuildScript AddSmartContract(string path) + private ContractState AddSmartContract(string path) { var builtScript = engine.Build(path); var hash = builtScript.finalNEFScript.ToScriptHash(); @@ -86,15 +73,17 @@ private BuildScript AddSmartContract(string path) if (!snapshot.ContainsContract(hash)) { - snapshot.TryContractAdd(new ContractState() + var state = new ContractState() { + Id = snapshot.GetNextAvailableId(), Hash = hash, Nef = builtScript.nefFile, Manifest = ContractManifest.FromJson(JObject.Parse(builtScript.finalManifest)), - }); + }; + snapshot.TryContractAdd(state); } - return builtScript; + return NativeContract.ContractManagement.GetContract(snapshot, hash); } public void IncreaseBlockCount(uint newHeight) diff --git a/src/Neo.TestEngine/Extensions/TestExtensions.cs b/src/Neo.TestEngine/Extensions/TestExtensions.cs index bca5cc60e..b9dec6a28 100644 --- a/src/Neo.TestEngine/Extensions/TestExtensions.cs +++ b/src/Neo.TestEngine/Extensions/TestExtensions.cs @@ -3,11 +3,14 @@ using Neo.Persistence; using Neo.SmartContract; using Neo.SmartContract.Native; +using System.Linq; namespace Neo.TestingEngine { public static class TestExtensions { + private const byte Prefix_NextAvailableId = 15; + public static void ContractAdd(this DataCache snapshot, ContractState contract) { var key = new KeyBuilder(NativeContract.ContractManagement.Id, 8).Add(contract.Hash); @@ -41,7 +44,7 @@ public static void DeployNativeContracts(this DataCache snapshot, Block persisti public static bool TryContractAdd(this DataCache snapshot, ContractState contract) { - var key = new KeyBuilder(NativeContract.ContractManagement.Id, 8).Add(contract.Hash); + var key = NativeContract.ContractManagement.CreateStorageKey(8, contract.Hash); if (snapshot.Contains(key)) { return false; @@ -50,5 +53,11 @@ public static bool TryContractAdd(this DataCache snapshot, ContractState contrac snapshot.Add(key, new StorageItem(contract)); return true; } + public static int GetNextAvailableId(this DataCache snapshot) + { + StorageItem item = snapshot.GetAndChange(NativeContract.ContractManagement.CreateStorageKey(Prefix_NextAvailableId)); + item.Add(1); + return NativeContract.ContractManagement.ListContracts(snapshot).ToList().Where(state => state.Id >= 0).Count(); + } } } From 0ac6724271541c6a244af3e1d9102ddaf1d83434 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 22 Mar 2021 14:26:22 -0300 Subject: [PATCH 35/77] fix native contract call --- src/Neo.TestEngine/TestUtils/BuildNative.cs | 2 ++ src/Neo.TestEngine/TestUtils/BuildScript.cs | 2 +- src/Neo.TestEngine/TestUtils/TestEngine.cs | 3 ++- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/Neo.TestEngine/TestUtils/BuildNative.cs b/src/Neo.TestEngine/TestUtils/BuildNative.cs index 5cd3b2cc1..145477b4d 100644 --- a/src/Neo.TestEngine/TestUtils/BuildNative.cs +++ b/src/Neo.TestEngine/TestUtils/BuildNative.cs @@ -11,6 +11,8 @@ class BuildNative : BuildScript public BuildNative(NativeContract nativeContract) : base() { this.nativeContract = nativeContract; + this.nefFile = nativeContract.Nef; + byte[] script; using (ScriptBuilder sb = new ScriptBuilder()) { diff --git a/src/Neo.TestEngine/TestUtils/BuildScript.cs b/src/Neo.TestEngine/TestUtils/BuildScript.cs index 538957a30..71addc3e0 100644 --- a/src/Neo.TestEngine/TestUtils/BuildScript.cs +++ b/src/Neo.TestEngine/TestUtils/BuildScript.cs @@ -22,7 +22,7 @@ public class BuildScript public JObject finalABI { get; protected set; } public string finalManifest { get; protected set; } public JObject debugInfo { get; private set; } - public NefFile nefFile { get; private set; } + public NefFile nefFile { get; protected set; } public BuildScript() { diff --git a/src/Neo.TestEngine/TestUtils/TestEngine.cs b/src/Neo.TestEngine/TestUtils/TestEngine.cs index bf03dc50c..4a3d71156 100644 --- a/src/Neo.TestEngine/TestUtils/TestEngine.cs +++ b/src/Neo.TestEngine/TestUtils/TestEngine.cs @@ -111,7 +111,8 @@ public void RunNativeContract(string method, StackItem[] parameters, CallFlags f Integer callFlag = (uint)flags; var items = new StackItem[] { methodName, callFlag, paramsArray }; - ExecuteTestCaseStandard(method, items.ToArray()); + var rvcount = GetMethodReturnCount(method); + ExecuteTestCaseStandard(0, (ushort)rvcount, ScriptEntry.nefFile, items.ToArray()); } public void Reset() From 8936b866059c0044d39af41e78a7d981fc7c59bc Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Tue, 30 Mar 2021 19:26:03 -0300 Subject: [PATCH 36/77] change TestEngine to test contracts update --- src/Neo.TestEngine/Engine.cs | 15 ++++++++++---- src/Neo.TestEngine/TestContract.cs | 2 +- src/Neo.TestEngine/TestUtils/BuildNEF.cs | 20 ++++++++++++++++--- .../TestUtils/TestBlockchain.cs | 2 +- src/Neo.TestEngine/TestUtils/TestEngine.cs | 7 ++++++- 5 files changed, 36 insertions(+), 10 deletions(-) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index 25cca1f92..e96d10295 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -61,19 +61,20 @@ public void SetEntryScript(UInt160 contractHash) public void AddSmartContract(TestContract contract) { var state = AddSmartContract(contract.nefPath); - contract.nefFile = state.Nef; + contract.buildScript = state; } - private ContractState AddSmartContract(string path) + private BuildScript AddSmartContract(string path) { var builtScript = engine.Build(path); var hash = builtScript.finalNEFScript.ToScriptHash(); var snapshot = engine.Snapshot; + ContractState state; if (!snapshot.ContainsContract(hash)) { - var state = new ContractState() + state = new ContractState() { Id = snapshot.GetNextAvailableId(), Hash = hash, @@ -82,8 +83,14 @@ private ContractState AddSmartContract(string path) }; snapshot.TryContractAdd(state); } + else + { + state = NativeContract.ContractManagement.GetContract(snapshot, hash); + builtScript = new BuildNEF(state.Nef, state.Manifest.ToJson()); + } - return NativeContract.ContractManagement.GetContract(snapshot, hash); + engine.AddContract(path, builtScript); + return builtScript; } public void IncreaseBlockCount(uint newHeight) diff --git a/src/Neo.TestEngine/TestContract.cs b/src/Neo.TestEngine/TestContract.cs index 875709c51..b821f7d33 100644 --- a/src/Neo.TestEngine/TestContract.cs +++ b/src/Neo.TestEngine/TestContract.cs @@ -5,7 +5,7 @@ namespace Neo.TestingEngine public class TestContract { internal string nefPath; - internal NefFile nefFile = null; + internal BuildScript buildScript = null; public TestContract(string path) { diff --git a/src/Neo.TestEngine/TestUtils/BuildNEF.cs b/src/Neo.TestEngine/TestUtils/BuildNEF.cs index d96224282..7df13bd48 100644 --- a/src/Neo.TestEngine/TestUtils/BuildNEF.cs +++ b/src/Neo.TestEngine/TestUtils/BuildNEF.cs @@ -7,14 +7,28 @@ class BuildNEF : BuildScript { public BuildNEF(NefFile nefFile, string manifestFile) : base(nefFile) { - IsBuild = true; - UseOptimizer = false; - Error = null; finalNEFScript = nefFile.Script; JObject manifestJson = JObject.Parse(manifestFile); var abi = manifestJson["abi"] as JObject; finalABI = abi; finalManifest = manifestFile; + SetPropeties(); + } + + public BuildNEF(NefFile nefFile, JObject manifestJson) : base(nefFile) + { + finalNEFScript = nefFile.Script; + var abi = manifestJson["abi"] as JObject; + finalABI = abi; + finalManifest = manifestJson.AsString(); + SetPropeties(); + } + + private void SetPropeties() + { + IsBuild = true; + UseOptimizer = false; + Error = null; } } } diff --git a/src/Neo.TestEngine/TestUtils/TestBlockchain.cs b/src/Neo.TestEngine/TestUtils/TestBlockchain.cs index d8ee34bbf..be6e41ab2 100644 --- a/src/Neo.TestEngine/TestUtils/TestBlockchain.cs +++ b/src/Neo.TestEngine/TestUtils/TestBlockchain.cs @@ -41,7 +41,7 @@ public static StorageKey CreateStorageKey(this NativeContract contract, byte pre { var nativeTokens = new int[] { - NativeContract.GAS.Id, NativeContract.NEO.Id + NativeContract.GAS.Id, NativeContract.NEO.Id, NativeContract.ContractManagement.Id }; return snapshot.Find().Where(pair => pair.Key.Id >= 0 || nativeTokens.Contains(pair.Key.Id)).ToList(); diff --git a/src/Neo.TestEngine/TestUtils/TestEngine.cs b/src/Neo.TestEngine/TestUtils/TestEngine.cs index 4a3d71156..f7d27a5f2 100644 --- a/src/Neo.TestEngine/TestUtils/TestEngine.cs +++ b/src/Neo.TestEngine/TestUtils/TestEngine.cs @@ -32,7 +32,7 @@ public BuildScript Build(string filename, bool releaseMode = false, bool optimiz { var contains = scriptsAll.ContainsKey(filename); - if (!contains || (contains && scriptsAll[filename].UseOptimizer != optimizer)) + if (!contains || (contains && !(scriptsAll[filename] is BuildNEF) && scriptsAll[filename].UseOptimizer != optimizer)) { if (Path.GetExtension(filename).ToLowerInvariant() == ".nef") { @@ -104,6 +104,11 @@ public void AddEntryScript(UInt160 contractHash) Reset(); } + public void AddContract(string filename, BuildScript script) + { + scriptsAll[filename] = script; + } + public void RunNativeContract(string method, StackItem[] parameters, CallFlags flags = CallFlags.All) { VM.Types.Array paramsArray = new VM.Types.Array(parameters); From 92bb0c469b391b63eb566b0aa1fd898455e93270 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Wed, 31 Mar 2021 14:52:53 -0300 Subject: [PATCH 37/77] read json file input --- src/Neo.TestEngine/Program.cs | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/src/Neo.TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs index 57640be07..b58f4ad71 100644 --- a/src/Neo.TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -27,18 +27,39 @@ public static JObject Run(string[] args) { if (args.Length == 1) { + var isFile = Path.GetExtension(args[0]).ToLowerInvariant() == ".json"; JObject input; try { // verifies if the parameter is a json string - input = JObject.Parse(args[0]); + string jsonString; + if (isFile) + { + jsonString = File.ReadAllText(args[0]); + } + else + { + jsonString = args[0]; + } + input = JObject.Parse(jsonString); } catch { // if it isn't, at least one argument is missing + string lastExpectedArg; + if (isFile) + { + lastExpectedArg = "json file with method arguments"; + } + else + { + lastExpectedArg = "method arguments as json"; + } + return BuildJsonException( - "One or more arguments are missing\n" + - "Expected arguments: " + string.Format("One or more arguments are missing\n" + + "Expected arguments: <{0}>", + lastExpectedArg) ); } From 979a6f9ab51c3fcebc521ffe068ea53ac68d277e Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Wed, 14 Apr 2021 15:37:44 -0300 Subject: [PATCH 38/77] include tx attributes in the input --- src/Neo.TestEngine/Engine.cs | 7 +- src/Neo.TestEngine/Program.cs | 85 ++++++++++++++++++- src/Neo.TestEngine/SmartContractTest.cs | 1 + .../TestUtils/TestBlockchain.cs | 2 +- 4 files changed, 91 insertions(+), 4 deletions(-) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index 82b5c66c5..c5908e195 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -1,13 +1,13 @@ using Neo.Cryptography.ECC; using Neo.IO; using Neo.IO.Json; -using Neo.Ledger; using Neo.Network.P2P.Payloads; using Neo.Persistence; using Neo.SmartContract; using Neo.SmartContract.Manifest; using Neo.SmartContract.Native; using Neo.VM; +using Neo.VM.Types; using System.Collections.Generic; using System.Linq; @@ -142,6 +142,11 @@ public void SetSigners(UInt160[] signerAccounts) } } + internal void SetTxAttributes(TransactionAttribute[] attributes) + { + currentTx.Attributes = attributes.Where(attr => attr != null).ToArray(); + } + public void AddBlock(Block block) { if (engine.Snapshot is TestDataCache snapshot) diff --git a/src/Neo.TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs index 9eb72313b..12624cc28 100644 --- a/src/Neo.TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -166,26 +166,37 @@ public static JObject RunWithJson(JObject json) smartContractTestCase = new SmartContractTest(scriptHash, methodName, parameters); } + // fake storage if (json.ContainsProperty("storage")) { smartContractTestCase.storage = GetStorageFromJson(json["storage"]); } + // additional contracts that aren't the entry point but can be called during executing if (json.ContainsProperty("contracts")) { smartContractTestCase.contracts = GetContractsFromJson(json["contracts"]); } + // set data for previous blocks for better simulation if (json.ContainsProperty("blocks") && json["blocks"] is JArray blocks) { smartContractTestCase.blocks = blocks.Select(b => BlockFromJson(b)).ToArray(); } + // set the current heigh if (json.ContainsProperty("height")) { smartContractTestCase.currentHeight = uint.Parse(json["height"].AsString()); } + // set data for current tx + if (json.ContainsProperty("currentTx")) + { + smartContractTestCase.currentTx = TxFromJson(json["currentTx"]); + } + + // tx signers if (json.ContainsProperty("signerAccounts") && json["signerAccounts"] is JArray accounts) { smartContractTestCase.signers = accounts.Select(p => UInt160.Parse(p.AsString())).ToArray(); @@ -225,6 +236,14 @@ public static JObject Run(SmartContractTest smartContractTest) Engine.Instance.IncreaseBlockCount(smartContractTest.currentHeight); Engine.Instance.SetSigners(smartContractTest.signers); + Engine.Instance.IncreaseBlockCount(smartContractTest.currentHeight); + Engine.Instance.SetSigners(smartContractTest.signers); + + if (smartContractTest.currentTx != null) + { + Engine.Instance.SetTxAttributes(smartContractTest.currentTx.Attributes); + } + if (smartContractTest.nefPath != null) { IsValidNefPath(smartContractTest.nefPath); @@ -234,6 +253,7 @@ public static JObject Run(SmartContractTest smartContractTest) { Engine.Instance.SetEntryScript(smartContractTest.scriptHash); } + var stackParams = GetStackItemParameters(smartContractTest.methodParameters); return Engine.Instance.Run(smartContractTest.methodName, stackParams); } @@ -383,6 +403,7 @@ private static Transaction TxFromJson(JObject txJson) { Signer[] accounts; Witness[] witnesses; + List attributes = new List(); if (txJson.ContainsProperty("signers") && txJson["signers"] is JArray signersJson) { @@ -410,15 +431,75 @@ private static Transaction TxFromJson(JObject txJson) witnesses = new Witness[0]; } + if (txJson.ContainsProperty("attributes") && txJson["attributes"] is JArray attributesJson) + { + foreach (var attr in attributesJson) + { + var txAttribute = TxAttributeFromJson(attr); + if (txAttribute != null) + { + attributes.Add(txAttribute); + } + } + } + + byte[] script; + if (txJson.ContainsProperty("script")) + { + script = txJson["script"].ToByteArray(false); + } + else if (attributes.Any(attribute => attribute is OracleResponse oracleAttr)) + { + script = OracleResponse.FixedScript; + } + else + { + script = new byte[0]; + } + return new Transaction() { - Script = txJson["script"].ToByteArray(false), + Script = script, Signers = accounts, Witnesses = witnesses, - Attributes = new TransactionAttribute[0] + Attributes = attributes.ToArray() }; } + private static TransactionAttribute TxAttributeFromJson(JObject txAttributeJson) + { + if (!txAttributeJson.ContainsProperty("type")) + { + return null; + } + + if (!Enum.TryParse(txAttributeJson["type"].AsString(), out var type)) + { + return null; + } + + switch (type) + { + case TransactionAttributeType.OracleResponse: + + if (!Enum.TryParse(txAttributeJson["code"].AsString(), out var responseCode)) + { + throw new ArgumentException(); + } + + return new OracleResponse() + { + Id = ulong.Parse(txAttributeJson["id"].AsString()), + Code = responseCode, + Result = Convert.FromBase64String(txAttributeJson["result"].AsString()) + }; + case TransactionAttributeType.HighPriority: + return new HighPriorityAttribute(); + default: + return null; + } + } + private static bool IsValidNefPath(string path) { if (!File.Exists(path)) diff --git a/src/Neo.TestEngine/SmartContractTest.cs b/src/Neo.TestEngine/SmartContractTest.cs index 444ce71f5..6601c8f8f 100644 --- a/src/Neo.TestEngine/SmartContractTest.cs +++ b/src/Neo.TestEngine/SmartContractTest.cs @@ -16,6 +16,7 @@ public class SmartContractTest public uint currentHeight = 0; public UInt160[] signers; public Block[] blocks; + public Transaction currentTx; public SmartContractTest(string path, string method, JArray parameters) : this(method, parameters) { diff --git a/src/Neo.TestEngine/TestUtils/TestBlockchain.cs b/src/Neo.TestEngine/TestUtils/TestBlockchain.cs index be6e41ab2..caa07d6db 100644 --- a/src/Neo.TestEngine/TestUtils/TestBlockchain.cs +++ b/src/Neo.TestEngine/TestUtils/TestBlockchain.cs @@ -41,7 +41,7 @@ public static StorageKey CreateStorageKey(this NativeContract contract, byte pre { var nativeTokens = new int[] { - NativeContract.GAS.Id, NativeContract.NEO.Id, NativeContract.ContractManagement.Id + NativeContract.GAS.Id, NativeContract.NEO.Id, NativeContract.ContractManagement.Id, NativeContract.Oracle.Id }; return snapshot.Find().Where(pair => pair.Key.Id >= 0 || nativeTokens.Contains(pair.Key.Id)).ToList(); From b4aac8ee69a51a43628464b82b5e4122c7048555 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Wed, 14 Apr 2021 17:12:48 -0300 Subject: [PATCH 39/77] remove comments --- src/Neo.TestEngine/Neo.TestEngine.csproj | 1 + src/Neo.TestEngine/TestUtils/TestEngine.cs | 13 ------------- tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs | 2 -- .../UnitTest_CheckWitness.cs | 7 ------- .../UnitTest_ContractCall.cs | 10 ---------- tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs | 7 ------- .../UnitTest_Notification.cs | 7 ------- 7 files changed, 1 insertion(+), 46 deletions(-) diff --git a/src/Neo.TestEngine/Neo.TestEngine.csproj b/src/Neo.TestEngine/Neo.TestEngine.csproj index 5d6d3ecd0..15f7caa11 100644 --- a/src/Neo.TestEngine/Neo.TestEngine.csproj +++ b/src/Neo.TestEngine/Neo.TestEngine.csproj @@ -26,6 +26,7 @@ + diff --git a/src/Neo.TestEngine/TestUtils/TestEngine.cs b/src/Neo.TestEngine/TestUtils/TestEngine.cs index 5d86884fc..dba15738e 100644 --- a/src/Neo.TestEngine/TestUtils/TestEngine.cs +++ b/src/Neo.TestEngine/TestUtils/TestEngine.cs @@ -44,19 +44,6 @@ static TestEngine() references.Add(MetadataReference.CreateFromFile(typeof(string).Assembly.Location)); references.Add(MetadataReference.CreateFromFile(typeof(DisplayNameAttribute).Assembly.Location)); references.Add(MetadataReference.CreateFromFile(typeof(BigInteger).Assembly.Location)); - - string folder = Path.GetFullPath(string.Format( - "{0}/../../../../../src/Neo.SmartContract.Framework/", - AppContext.BaseDirectory - )); - string obj = Path.Combine(folder, "obj"); - IEnumerable st = Directory.EnumerateFiles(folder, "*.cs", SearchOption.AllDirectories) - .Where(p => !p.StartsWith(obj)) - .OrderBy(p => p) - .Select(p => CSharpSyntaxTree.ParseText(File.ReadAllText(p), path: p)); - CSharpCompilationOptions options = new(OutputKind.DynamicallyLinkedLibrary); - CSharpCompilation cr = CSharpCompilation.Create(null, st, references, options); - references.Add(cr.ToMetadataReference()); } catch (Exception e) { diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs index c029da38a..4b27fb2f0 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs @@ -1,13 +1,11 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Neo.IO.Json; -using Neo.Ledger; using Neo.SmartContract.Native; using Neo.TestEngine.UnitTests.Utils; using Neo.TestingEngine; using Neo.VM; using Neo.VM.Types; using System.IO; -using System.Linq; namespace TestEngine.UnitTests { diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs index d0a7be99a..a8d2f0fc5 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs @@ -8,7 +8,6 @@ using Neo.VM.Types; using Neo.Wallets; using System.IO; -//using Compiler = Neo.Compiler.Program; namespace TestEngine.UnitTests { @@ -19,12 +18,6 @@ public class UnitTest_CheckWitness public void Init() { string path = Directory.GetCurrentDirectory(); - //var option = new Compiler.Options() - //{ - // File = path + "/TestClasses/Contract_CheckWitness.cs" - //}; - //Compiler.Compile(option); - CSharpCompiler.Compile(path + "/TestClasses/Contract_CheckWitness.cs"); //Compile changes the path, reseting so that other UT won't break diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs index 10b1d6b66..cac8281c0 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs @@ -5,7 +5,6 @@ using Neo.VM; using Neo.VM.Types; using System.IO; -//using Compiler = Neo.Compiler.Program; namespace TestEngine.UnitTests { @@ -16,15 +15,6 @@ public class UnitTest_ContractCall public void Init() { string path = Directory.GetCurrentDirectory(); - //var option = new Compiler.Options() - //{ - // File = path + "/TestClasses/Contract1.cs" - //}; - //Compiler.Compile(option); - - //option.File = path + "/TestClasses/Contract_ContractCall.cs"; - //Compiler.Compile(option); - CSharpCompiler.Compile(path + "/TestClasses/Contract_ContractCall.cs"); //Compile changes the path, reseting so that other UT won't break diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs index 55e7e72e9..c6d37e042 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs @@ -5,7 +5,6 @@ using Neo.VM; using Neo.VM.Types; using System.IO; -//using Compiler = Neo.Compiler.Program; namespace TestEngine.UnitTests { @@ -16,12 +15,6 @@ public class UnitTest_Invoke public void Init() { string path = Directory.GetCurrentDirectory(); - //var option = new Compiler.Options() - //{ - // File = path + "/TestClasses/Contract1.cs" - //}; - //Compiler.Compile(option); - CSharpCompiler.Compile(path + "/TestClasses/Contract1.cs"); //Compile changes the path, reseting so that other UT won't break diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs index a8e7dbcf2..13f9130e8 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs @@ -5,7 +5,6 @@ using Neo.VM; using Neo.VM.Types; using System.IO; -//using Compiler = Neo.Compiler.Program; namespace TestEngine.UnitTests { @@ -16,12 +15,6 @@ public class UnitTest_Notification public void Init() { string path = Directory.GetCurrentDirectory(); - //var option = new Compiler.Options() - //{ - // File = path + "/TestClasses/Contract2.cs" - //}; - //Compiler.Compile(option); - CSharpCompiler.Compile(path + "/TestClasses/Contract2.cs"); //Compile changes the path, reseting so that other UT won't break From 71a3cb21635cd14a75a08be393be819831b2e80c Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Wed, 14 Apr 2021 17:47:45 -0300 Subject: [PATCH 40/77] fix import --- src/Neo.TestEngine/TestUtils/TestEngine.cs | 12 ++++++++++-- .../UnitTest_Params.cs | 18 ++++++++++++++++++ .../Utils/CSharpCompiler.cs | 6 ------ 3 files changed, 28 insertions(+), 8 deletions(-) create mode 100644 tests/Neo.Compiler.CSharp.UnitTests/UnitTest_Params.cs diff --git a/src/Neo.TestEngine/TestUtils/TestEngine.cs b/src/Neo.TestEngine/TestUtils/TestEngine.cs index dba15738e..ca12f6a96 100644 --- a/src/Neo.TestEngine/TestUtils/TestEngine.cs +++ b/src/Neo.TestEngine/TestUtils/TestEngine.cs @@ -43,12 +43,20 @@ static TestEngine() references.Add(MetadataReference.CreateFromFile(Path.Combine(coreDir, "System.Runtime.InteropServices.dll"))); references.Add(MetadataReference.CreateFromFile(typeof(string).Assembly.Location)); references.Add(MetadataReference.CreateFromFile(typeof(DisplayNameAttribute).Assembly.Location)); - references.Add(MetadataReference.CreateFromFile(typeof(BigInteger).Assembly.Location)); + references.Add(MetadataReference.CreateFromFile(typeof(BigInteger).Assembly.Location)); string folder = Path.GetFullPath("../../../../../src/Neo.SmartContract.Framework/"); + + string obj = Path.Combine(folder, "obj"); + IEnumerable st = Directory.EnumerateFiles(folder, "*.cs", SearchOption.AllDirectories) + .Where(p => !p.StartsWith(obj)) + .OrderBy(p => p) + .Select(p => CSharpSyntaxTree.ParseText(File.ReadAllText(p), path: p)); + CSharpCompilationOptions options = new(OutputKind.DynamicallyLinkedLibrary); + CSharpCompilation cr = CSharpCompilation.Create(null, st, references, options); + references.Add(cr.ToMetadataReference()); } catch (Exception e) { Console.WriteLine(e); - throw e; } } diff --git a/tests/Neo.Compiler.CSharp.UnitTests/UnitTest_Params.cs b/tests/Neo.Compiler.CSharp.UnitTests/UnitTest_Params.cs new file mode 100644 index 000000000..e093ecf24 --- /dev/null +++ b/tests/Neo.Compiler.CSharp.UnitTests/UnitTest_Params.cs @@ -0,0 +1,18 @@ +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Neo.TestingEngine; + +namespace Neo.Compiler.CSharp.UnitTests +{ + [TestClass] + public class UnitTest_Params + { + [TestMethod] + public void Test_Params() + { + TestEngine testengine = new(); + testengine.AddEntryScript("./TestClasses/Contract_Params.cs"); + var result = testengine.ExecuteTestCaseStandard("test"); + Assert.AreEqual(15, result.Pop()); + } + } +} diff --git a/tests/Neo.TestEngine.UnitTests/Utils/CSharpCompiler.cs b/tests/Neo.TestEngine.UnitTests/Utils/CSharpCompiler.cs index 04b593d61..329c30e7f 100644 --- a/tests/Neo.TestEngine.UnitTests/Utils/CSharpCompiler.cs +++ b/tests/Neo.TestEngine.UnitTests/Utils/CSharpCompiler.cs @@ -1,9 +1,3 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - namespace Neo.TestEngine.UnitTests.Utils { public class CSharpCompiler From 99fd4743d17e5c46686652d402e46feac9a1771b Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Wed, 28 Apr 2021 15:25:31 -0300 Subject: [PATCH 41/77] fix test engine unit tests --- .../UnitTest_ABI_ContractPermission.cs | 18 ----- .../Services/IteratorTest.cs | 72 ------------------- .../TestClasses/Contract_CheckWitness.cs | 3 +- .../TestClasses/Contract_ContractCall.cs | 2 +- .../TestClasses/Contract_Time.cs | 14 ++-- .../Utils/CSharpCompiler.cs | 26 +++++-- 6 files changed, 28 insertions(+), 107 deletions(-) delete mode 100644 tests/Neo.Compiler.CSharp.UnitTests/UnitTest_ABI_ContractPermission.cs delete mode 100644 tests/Neo.SmartContract.Framework.UnitTests/Services/IteratorTest.cs diff --git a/tests/Neo.Compiler.CSharp.UnitTests/UnitTest_ABI_ContractPermission.cs b/tests/Neo.Compiler.CSharp.UnitTests/UnitTest_ABI_ContractPermission.cs deleted file mode 100644 index efdba9ac3..000000000 --- a/tests/Neo.Compiler.CSharp.UnitTests/UnitTest_ABI_ContractPermission.cs +++ /dev/null @@ -1,18 +0,0 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.TestingEngine; - -namespace Neo.Compiler.CSharp.UnitTests -{ - [TestClass] - public class UnitTest_ABI_ContractPermission - { - [TestMethod] - public void TestWildcardContractPermission() - { - var testEngine = new TestEngine(); - testEngine.AddEntryScript("./TestClasses/Contract_ABIContractPermission.cs"); - var permissions = testEngine.Manifest["permissions"].ToString(false); - Assert.AreEqual(@"[{""contract"":""0x01ff00ff00ff00ff00ff00ff00ff00ff00ff00a4"",""methods"":[""a"",""b""]},{""contract"":""*"",""methods"":[""c""]}]", permissions); - } - } -} diff --git a/tests/Neo.SmartContract.Framework.UnitTests/Services/IteratorTest.cs b/tests/Neo.SmartContract.Framework.UnitTests/Services/IteratorTest.cs deleted file mode 100644 index 9fb271cb6..000000000 --- a/tests/Neo.SmartContract.Framework.UnitTests/Services/IteratorTest.cs +++ /dev/null @@ -1,72 +0,0 @@ -using Microsoft.VisualStudio.TestTools.UnitTesting; -using Neo.TestingEngine; -using Neo.VM; -using Neo.VM.Types; - -namespace Neo.SmartContract.Framework.UnitTests.Services -{ - [TestClass] - public class IteratorTest - { - private TestEngine _engine; - - [TestInitialize] - public void Init() - { - _engine = new TestEngine(); - _engine.AddEntryScript("./TestClasses/Contract_Iterator.cs"); - } - - [TestMethod] - public void TestNextIntArray() - { - _engine.Reset(); - var result = _engine.ExecuteTestCaseStandard("testNextIntArray", new Array(new StackItem[] { 1, 2, 3 })); - Assert.AreEqual(VMState.HALT, _engine.State); - Assert.AreEqual(1, result.Count); - - var item = result.Pop(); - Assert.IsInstanceOfType(item, typeof(Integer)); - Assert.AreEqual(6, item.GetInteger()); - } - - [TestMethod] - public void TestNextIntArrayForeach() - { - _engine.Reset(); - var result = _engine.ExecuteTestCaseStandard("testNextIntArrayForeach", new Array(new StackItem[] { 1, 2, 3 })); - Assert.AreEqual(VMState.HALT, _engine.State); - Assert.AreEqual(1, result.Count); - - var item = result.Pop(); - Assert.IsInstanceOfType(item, typeof(Integer)); - Assert.AreEqual(6, item.GetInteger()); - } - - [TestMethod] - public void TestNextIntArrayBase() - { - _engine.Reset(); - var result = _engine.ExecuteTestCaseStandard("testNextIntArrayBase", new Array(new StackItem[] { 1, 2, 3 })); - Assert.AreEqual(VMState.HALT, _engine.State); - Assert.AreEqual(1, result.Count); - - var item = result.Pop(); - Assert.IsInstanceOfType(item, typeof(Integer)); - Assert.AreEqual(6, item.GetInteger()); - } - - [TestMethod] - public void TestNextByteArray() - { - _engine.Reset(); - var result = _engine.ExecuteTestCaseStandard("testNextByteArray", new byte[] { 1, 2, 3 }); - Assert.AreEqual(VMState.HALT, _engine.State); - Assert.AreEqual(1, result.Count); - - var item = result.Pop(); - Assert.IsInstanceOfType(item, typeof(Integer)); - Assert.AreEqual(6, item.GetInteger()); - } - } -} diff --git a/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_CheckWitness.cs b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_CheckWitness.cs index 19e921246..9b58475bc 100644 --- a/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_CheckWitness.cs +++ b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_CheckWitness.cs @@ -1,5 +1,4 @@ -using Neo; -using Neo.SmartContract.Framework.Services.Neo; +using Neo.SmartContract.Framework.Services; namespace Neo.Compiler.MSIL.UnitTests.TestClasses { diff --git a/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_ContractCall.cs b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_ContractCall.cs index 049725087..257081e70 100644 --- a/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_ContractCall.cs +++ b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_ContractCall.cs @@ -2,7 +2,7 @@ namespace Neo.Compiler.MSIL.UnitTests.TestClasses { - [Contract("725549b81801976b6e490b0f58662fcf286a4ea3")] + [Contract("0x4281dd379f0831b4131f9bc3433299e4fda02e68")] public class Contract1 { public static extern byte[] testArgs1(byte a); diff --git a/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_Time.cs b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_Time.cs index ee34f200d..db224e529 100644 --- a/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_Time.cs +++ b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_Time.cs @@ -1,18 +1,18 @@ -using Neo.SmartContract.Framework; -using Neo.SmartContract.Framework.Services.Neo; +using Neo.SmartContract.Framework.Native; +using Neo.SmartContract.Framework.Services; -namespace Neo.Compiler.MSIL.UnitTests.TestClasses +namespace Neo.SmartContract.Framework.UnitTests.TestClasses { - public class Contract_Time : SmartContract.Framework.SmartContract + public class Contract_Runtime : SmartContract { - public static ulong getTime() + public static ulong GetTime() { return Runtime.Time; } - public static object getBlock(uint blockIndex) + public static object GetBlock(uint index) { - return Ledger.GetBlock(blockIndex); + return Ledger.GetBlock(index); } } } diff --git a/tests/Neo.TestEngine.UnitTests/Utils/CSharpCompiler.cs b/tests/Neo.TestEngine.UnitTests/Utils/CSharpCompiler.cs index 329c30e7f..fd6bdb101 100644 --- a/tests/Neo.TestEngine.UnitTests/Utils/CSharpCompiler.cs +++ b/tests/Neo.TestEngine.UnitTests/Utils/CSharpCompiler.cs @@ -1,16 +1,28 @@ +using Neo.Compiler; +using Neo.IO; +using System; +using System.IO; + namespace Neo.TestEngine.UnitTests.Utils { public class CSharpCompiler { public static void Compile(string filepath) { - System.Diagnostics.Process process = new System.Diagnostics.Process(); - System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); - startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; - startInfo.FileName = "cmd.exe"; - startInfo.Arguments = string.Format("/C nccs {0}", filepath); - process.StartInfo = startInfo; - process.Start(); + CompilationContext context = CompilationContext.CompileSources(new[] { filepath }, new Options + { + AddressVersion = ProtocolSettings.Default.AddressVersion + }); + + if (!context.Success) + { + throw new Exception(string.Format("Could not compile '{0}'", filepath)); + } + var nefPath = filepath.Replace(".cs", ".nef"); + File.WriteAllBytes(nefPath, context.CreateExecutable().ToArray()); + + var manifestPath = filepath.Replace(".cs", ".manifest.json"); + File.WriteAllBytes(manifestPath, context.CreateManifest().ToByteArray(false)); } } } From 787039800cdaaefdbe18f5843f6fe219d8e4df6f Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Thu, 29 Apr 2021 15:26:33 -0300 Subject: [PATCH 42/77] Sync to Neo 3.0.0-CI01272 --- src/Neo.Compiler.CSharp/CompilationContext.cs | 1 + .../Neo.Compiler.CSharp.csproj | 4 +- src/Neo.SmartContract.Framework/Native/GAS.cs | 1 + .../Services/Iterator.cs | 12 ---- src/Neo.TestEngine/Neo.TestEngine.csproj | 2 +- .../TestClasses/Contract_Iterator.cs | 59 ------------------- 6 files changed, 5 insertions(+), 74 deletions(-) delete mode 100644 tests/Neo.SmartContract.Framework.UnitTests/TestClasses/Contract_Iterator.cs diff --git a/src/Neo.Compiler.CSharp/CompilationContext.cs b/src/Neo.Compiler.CSharp/CompilationContext.cs index 4f7ed1660..ba61a1cc2 100644 --- a/src/Neo.Compiler.CSharp/CompilationContext.cs +++ b/src/Neo.Compiler.CSharp/CompilationContext.cs @@ -258,6 +258,7 @@ public JObject CreateManifest() { ["name"] = ContractName, ["groups"] = new JArray(), + ["features"] = new JObject(), ["supportedstandards"] = supportedStandards.OrderBy(p => p).Select(p => (JString)p).ToArray(), ["abi"] = new JObject { diff --git a/src/Neo.Compiler.CSharp/Neo.Compiler.CSharp.csproj b/src/Neo.Compiler.CSharp/Neo.Compiler.CSharp.csproj index 8b6cb2e77..08507fda4 100644 --- a/src/Neo.Compiler.CSharp/Neo.Compiler.CSharp.csproj +++ b/src/Neo.Compiler.CSharp/Neo.Compiler.CSharp.csproj @@ -25,8 +25,8 @@ - - + + diff --git a/src/Neo.SmartContract.Framework/Native/GAS.cs b/src/Neo.SmartContract.Framework/Native/GAS.cs index 3ff5115e4..1666317f6 100644 --- a/src/Neo.SmartContract.Framework/Native/GAS.cs +++ b/src/Neo.SmartContract.Framework/Native/GAS.cs @@ -13,5 +13,6 @@ public class GAS public static extern BigInteger TotalSupply(); public static extern BigInteger BalanceOf(UInt160 account); public static extern bool Transfer(UInt160 from, UInt160 to, BigInteger amount, object data = null); + public static extern void Refuel(UInt160 account, long amount); } } diff --git a/src/Neo.SmartContract.Framework/Services/Iterator.cs b/src/Neo.SmartContract.Framework/Services/Iterator.cs index 6ceef3536..456d957fd 100644 --- a/src/Neo.SmartContract.Framework/Services/Iterator.cs +++ b/src/Neo.SmartContract.Framework/Services/Iterator.cs @@ -6,18 +6,6 @@ namespace Neo.SmartContract.Framework.Services { public class Iterator : IApiInterface, IEnumerable { - [Syscall("System.Iterator.Create")] - public static extern Iterator Create(T[] array); - - [Syscall("System.Iterator.Create")] - public static extern Iterator<(TKey, TValue)> Create(Map map); - - [Syscall("System.Iterator.Create")] - public static extern Iterator Create(byte[] buffer); - - [Syscall("System.Iterator.Create")] - public static extern Iterator Create(ByteString buffer); - [Syscall("System.Iterator.Next")] public extern bool Next(); diff --git a/src/Neo.TestEngine/Neo.TestEngine.csproj b/src/Neo.TestEngine/Neo.TestEngine.csproj index 418e20658..92415ae30 100644 --- a/src/Neo.TestEngine/Neo.TestEngine.csproj +++ b/src/Neo.TestEngine/Neo.TestEngine.csproj @@ -21,7 +21,7 @@ - + diff --git a/tests/Neo.SmartContract.Framework.UnitTests/TestClasses/Contract_Iterator.cs b/tests/Neo.SmartContract.Framework.UnitTests/TestClasses/Contract_Iterator.cs deleted file mode 100644 index 0139497ea..000000000 --- a/tests/Neo.SmartContract.Framework.UnitTests/TestClasses/Contract_Iterator.cs +++ /dev/null @@ -1,59 +0,0 @@ -using Neo.SmartContract.Framework.Services; - -namespace Neo.SmartContract.Framework.UnitTests.TestClasses -{ - public class Contract_Iterator : SmartContract - { - public static int TestNextByteArray(byte[] a) - { - int sum = 0; - var iterator = Iterator.Create(a); - - while (iterator.Next()) - { - sum += iterator.Value; - } - - return sum; - } - - public static int TestNextIntArray(int[] a) - { - int sum = 0; - var iterator = Iterator.Create(a); - - while (iterator.Next()) - { - sum += iterator.Value; - } - - return sum; - } - - public static int TestNextIntArrayForeach(int[] a) - { - int sum = 0; - var iterator = Iterator.Create(a); - - foreach (var value in iterator) - { - sum += value; - } - - return sum; - } - - public static int TestNextIntArrayBase(int[] a) - { - int sum = 0; - var iterator = (Iterator)Iterator.Create(a); - - while (iterator.Next()) - { - sum += (int)iterator.Value; - } - - return sum; - } - } -} From 04353ebfeee0fe3de43ac083e7dbcdef8476cac0 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Thu, 29 Apr 2021 18:42:55 -0300 Subject: [PATCH 43/77] update namespaces + dotnet-format --- src/Neo.Compiler.CSharp/CompilationContext.cs | 2 +- tests/Neo.TestEngine.UnitTests/TestClasses/Contract1.cs | 2 +- tests/Neo.TestEngine.UnitTests/TestClasses/Contract2.cs | 2 +- .../TestClasses/Contract_CheckWitness.cs | 2 +- .../TestClasses/Contract_ContractCall.cs | 2 +- tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs | 2 +- tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs | 2 +- tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs | 2 +- tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs | 2 +- tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Neo.Compiler.CSharp/CompilationContext.cs b/src/Neo.Compiler.CSharp/CompilationContext.cs index 2080c1190..463ec94eb 100644 --- a/src/Neo.Compiler.CSharp/CompilationContext.cs +++ b/src/Neo.Compiler.CSharp/CompilationContext.cs @@ -149,7 +149,7 @@ public static CompilationContext CompileSources(string[] sourceFiles, Options op public static CompilationContext CompileSources(string[] sourceFiles, List extraReferences, Options options) { List references = new(commonReferences); - foreach(var extraRef in extraReferences) + foreach (var extraRef in extraReferences) { if (!references.Contains(extraRef)) { diff --git a/tests/Neo.TestEngine.UnitTests/TestClasses/Contract1.cs b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract1.cs index f8256ebdc..11766a045 100644 --- a/tests/Neo.TestEngine.UnitTests/TestClasses/Contract1.cs +++ b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract1.cs @@ -1,4 +1,4 @@ -namespace Neo.Compiler.MSIL.UnitTests.TestClasses +namespace Neo.TestEngine.UnitTests.TestClasses { public class Contract1 : SmartContract.Framework.SmartContract { diff --git a/tests/Neo.TestEngine.UnitTests/TestClasses/Contract2.cs b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract2.cs index 6dc56991f..e5d8bfb0c 100644 --- a/tests/Neo.TestEngine.UnitTests/TestClasses/Contract2.cs +++ b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract2.cs @@ -1,7 +1,7 @@ using System; using System.ComponentModel; -namespace Neo.Compiler.MSIL.UnitTests.TestClasses +namespace Neo.TestEngine.UnitTests.TestClasses { public class Contract2 : SmartContract.Framework.SmartContract { diff --git a/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_CheckWitness.cs b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_CheckWitness.cs index 9b58475bc..49de6dea9 100644 --- a/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_CheckWitness.cs +++ b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_CheckWitness.cs @@ -1,6 +1,6 @@ using Neo.SmartContract.Framework.Services; -namespace Neo.Compiler.MSIL.UnitTests.TestClasses +namespace Neo.TestEngine.UnitTests.TestClasses { public class Contract_CheckWitness : SmartContract.Framework.SmartContract { diff --git a/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_ContractCall.cs b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_ContractCall.cs index 257081e70..a0a369291 100644 --- a/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_ContractCall.cs +++ b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_ContractCall.cs @@ -1,6 +1,6 @@ using Neo.SmartContract.Framework; -namespace Neo.Compiler.MSIL.UnitTests.TestClasses +namespace Neo.TestEngine.UnitTests.TestClasses { [Contract("0x4281dd379f0831b4131f9bc3433299e4fda02e68")] public class Contract1 diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs index 4b27fb2f0..42da89412 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs @@ -7,7 +7,7 @@ using Neo.VM.Types; using System.IO; -namespace TestEngine.UnitTests +namespace Neo.TestEngine.UnitTests { [TestClass] public class UnitTest_Block diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs index a8d2f0fc5..901c585dd 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs @@ -9,7 +9,7 @@ using Neo.Wallets; using System.IO; -namespace TestEngine.UnitTests +namespace Neo.TestEngine.UnitTests { [TestClass] public class UnitTest_CheckWitness diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs index cac8281c0..a091aa71b 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs @@ -6,7 +6,7 @@ using Neo.VM.Types; using System.IO; -namespace TestEngine.UnitTests +namespace Neo.TestEngine.UnitTests { [TestClass] public class UnitTest_ContractCall diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs index c6d37e042..478833193 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs @@ -6,7 +6,7 @@ using Neo.VM.Types; using System.IO; -namespace TestEngine.UnitTests +namespace Neo.TestEngine.UnitTests { [TestClass] public class UnitTest_Invoke diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs index 13f9130e8..e32461590 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs @@ -6,7 +6,7 @@ using Neo.VM.Types; using System.IO; -namespace TestEngine.UnitTests +namespace Neo.TestEngine.UnitTests { [TestClass] public class UnitTest_Notification From 1fb01e81dc8145bf072fdd106e039a7005964615 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Tue, 4 May 2021 12:47:30 -0300 Subject: [PATCH 44/77] code review --- src/Neo.TestEngine/Engine.cs | 3 +- src/Neo.TestEngine/Neo.TestEngine.csproj | 2 +- src/Neo.TestEngine/TestUtils/NeonTestTool.cs | 46 ------ .../TestClasses/Contract1.cs | 88 +++++------ .../TestClasses/Contract_CreateAndUpdate.cs | 26 ++-- .../TestClasses/Contract_Native.cs | 140 +++++++++--------- .../Neo.TestEngine.UnitTests.csproj | 2 +- .../UnitTest_Block.cs | 3 - .../UnitTest_CheckWitness.cs | 3 - .../UnitTest_ContractCall.cs | 3 - .../UnitTest_Invoke.cs | 3 - .../UnitTest_Notification.cs | 3 - 12 files changed, 131 insertions(+), 191 deletions(-) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index 254734de5..8cdf0d17b 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -52,9 +52,10 @@ public void SetEntryScript(string path) AddSmartContract(path); } - public void SetEntryScript(UInt160 contractHash) + public Engine SetEntryScript(UInt160 contractHash) { engine.AddEntryScript(contractHash); + return this; } public void AddSmartContract(TestContract contract) diff --git a/src/Neo.TestEngine/Neo.TestEngine.csproj b/src/Neo.TestEngine/Neo.TestEngine.csproj index 4651242ad..81c58c28e 100644 --- a/src/Neo.TestEngine/Neo.TestEngine.csproj +++ b/src/Neo.TestEngine/Neo.TestEngine.csproj @@ -1,4 +1,4 @@ - + 2015-2021 The Neo Project diff --git a/src/Neo.TestEngine/TestUtils/NeonTestTool.cs b/src/Neo.TestEngine/TestUtils/NeonTestTool.cs index f713fb134..5bd076b17 100644 --- a/src/Neo.TestEngine/TestUtils/NeonTestTool.cs +++ b/src/Neo.TestEngine/TestUtils/NeonTestTool.cs @@ -42,51 +42,5 @@ public static byte[] HexString2Bytes(string str) } return outd; } - - ///// - ///// Build script - ///// - ///// File - ///// Release mode (default=false) - ///// Optimize script (default=false) - ///// BuildScript - //public static BuildScript BuildScript(string filename, bool releaseMode = false, bool optimizer = false) - //{ - // return BuildScript(new string[] { filename }, releaseMode, optimizer); - //} - - ///// - ///// Build script - ///// - ///// Files - ///// Release mode (default=false) - ///// Optimize script (default=false) - ///// BuildScript - //public static BuildScript BuildScript(string[] filenames, bool releaseMode = false, bool optimizer = false) - //{ - // var ext = System.IO.Path.GetExtension(filenames.First()); - // var comp = (ext.ToLowerInvariant()) switch - // { - // ".cs" => Compiler.Compiler.CompileCSFiles(filenames, new string[0] { }, releaseMode), - // ".vb" => Compiler.Compiler.CompileVBFiles(filenames, new string[0] { }, releaseMode), - // _ => throw new System.Exception("do not support extname = " + ext), - // }; - - // using (var streamDll = new MemoryStream(comp.Dll)) - // using (var streamPdb = new MemoryStream(comp.Pdb)) - // { - // var bs = new BuildScript(); - // bs.Build(streamDll, streamPdb, optimizer); - - // if (bs.Error != null) - // { - // throw (bs.Error); - // } - - // if (bs.Error != null) throw bs.Error; - - // return bs; - // } - //} } } diff --git a/tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract1.cs b/tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract1.cs index 88dedc415..56b8441c2 100644 --- a/tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract1.cs +++ b/tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract1.cs @@ -1,44 +1,44 @@ -namespace Neo.Compiler.CSharp.UnitTests.TestClasses -{ - public class Contract1 : SmartContract.Framework.SmartContract - { - private static string privateMethod() - { - return "NEO3"; - } - - public static byte[] unitTest_001() - { - var nb = new byte[] { 1, 2, 3, 4 }; - return nb; - } - - public static void testVoid() - { - var nb = new byte[] { 1, 2, 3, 4 }; - } - - public static byte[] testArgs1(byte a) - { - var nb = new byte[] { 1, 2, 3, 3 }; - nb[3] = a; - return nb; - } - - public static object testArgs2(byte[] a) - { - return a; - } - - public static void testArgs3(int a, int b) - { - a = a + 2; - } - - public static int testArgs4(int a, int b) - { - a = a + 2; - return a + b; - } - } -} +namespace Neo.Compiler.CSharp.UnitTests.TestClasses +{ + public class Contract1 : SmartContract.Framework.SmartContract + { + private static string privateMethod() + { + return "NEO3"; + } + + public static byte[] unitTest_001() + { + var nb = new byte[] { 1, 2, 3, 4 }; + return nb; + } + + public static void testVoid() + { + var nb = new byte[] { 1, 2, 3, 4 }; + } + + public static byte[] testArgs1(byte a) + { + var nb = new byte[] { 1, 2, 3, 3 }; + nb[3] = a; + return nb; + } + + public static object testArgs2(byte[] a) + { + return a; + } + + public static void testArgs3(int a, int b) + { + a = a + 2; + } + + public static int testArgs4(int a, int b) + { + a = a + 2; + return a + b; + } + } +} diff --git a/tests/Neo.SmartContract.Framework.UnitTests/TestClasses/Contract_CreateAndUpdate.cs b/tests/Neo.SmartContract.Framework.UnitTests/TestClasses/Contract_CreateAndUpdate.cs index 23ad1408e..b90f9c623 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/TestClasses/Contract_CreateAndUpdate.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/TestClasses/Contract_CreateAndUpdate.cs @@ -1,13 +1,13 @@ -using Neo.SmartContract.Framework.Native; - -namespace Neo.SmartContract.Framework.UnitTests.TestClasses -{ - public class Contract_CreateAndUpdate : SmartContract - { - public static int OldContract(byte[] nefFile, string manifest) - { - ContractManagement.Update((ByteString)nefFile, manifest, null); - return 123; - } - } -} +using Neo.SmartContract.Framework.Native; + +namespace Neo.SmartContract.Framework.UnitTests.TestClasses +{ + public class Contract_CreateAndUpdate : SmartContract + { + public static int OldContract(byte[] nefFile, string manifest) + { + ContractManagement.Update((ByteString)nefFile, manifest, null); + return 123; + } + } +} diff --git a/tests/Neo.SmartContract.Framework.UnitTests/TestClasses/Contract_Native.cs b/tests/Neo.SmartContract.Framework.UnitTests/TestClasses/Contract_Native.cs index 7b2c0de06..dbec94eeb 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/TestClasses/Contract_Native.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/TestClasses/Contract_Native.cs @@ -1,72 +1,72 @@ -using Neo.Cryptography.ECC; -using Neo.SmartContract.Framework.Native; -using System; -using System.ComponentModel; -using System.Numerics; - -namespace Neo.SmartContract.Framework.UnitTests.TestClasses -{ - public class Contract_Native : SmartContract - { - [DisplayName("NEO_Decimals")] - public static int NEO_Decimals() - { - return NEO.Decimals; - } - - [DisplayName("NEO_Transfer")] - public static bool NEO_Transfer(UInt160 from, UInt160 to, BigInteger amount) - { - return NEO.Transfer(from, to, amount, null); - } - - [DisplayName("NEO_BalanceOf")] - public static BigInteger NEO_BalanceOf(UInt160 account) - { - return NEO.BalanceOf(account); - } - - [DisplayName("NEO_GetGasPerBlock")] - public static BigInteger NEO_GetGasPerBlock() - { - return NEO.GetGasPerBlock(); - } - - [DisplayName("NEO_UnclaimedGas")] - public static BigInteger NEO_UnclaimedGas(UInt160 account, uint end) - { - return NEO.UnclaimedGas(account, end); - } - - [DisplayName("NEO_RegisterCandidate")] - public static bool NEO_RegisterCandidate(ECPoint pubkey) - { - return NEO.RegisterCandidate(pubkey); - } - - [DisplayName("NEO_GetCandidates")] - public static (ECPoint, BigInteger)[] NEO_GetCandidates() - { - return NEO.GetCandidates(); - } - - [DisplayName("GAS_Decimals")] - public static int GAS_Decimals() - { - return GAS.Decimals; - } - - [DisplayName("Policy_GetFeePerByte")] - public static long Policy_GetFeePerByte() - { - return Policy.GetFeePerByte(); - } - - [DisplayName("Policy_IsBlocked")] - public static bool Policy_IsBlocked(UInt160 account) - { - return Policy.IsBlocked(account); - } - } +using Neo.Cryptography.ECC; +using Neo.SmartContract.Framework.Native; +using System; +using System.ComponentModel; +using System.Numerics; + +namespace Neo.SmartContract.Framework.UnitTests.TestClasses +{ + public class Contract_Native : SmartContract + { + [DisplayName("NEO_Decimals")] + public static int NEO_Decimals() + { + return NEO.Decimals; + } + + [DisplayName("NEO_Transfer")] + public static bool NEO_Transfer(UInt160 from, UInt160 to, BigInteger amount) + { + return NEO.Transfer(from, to, amount, null); + } + + [DisplayName("NEO_BalanceOf")] + public static BigInteger NEO_BalanceOf(UInt160 account) + { + return NEO.BalanceOf(account); + } + + [DisplayName("NEO_GetGasPerBlock")] + public static BigInteger NEO_GetGasPerBlock() + { + return NEO.GetGasPerBlock(); + } + + [DisplayName("NEO_UnclaimedGas")] + public static BigInteger NEO_UnclaimedGas(UInt160 account, uint end) + { + return NEO.UnclaimedGas(account, end); + } + + [DisplayName("NEO_RegisterCandidate")] + public static bool NEO_RegisterCandidate(ECPoint pubkey) + { + return NEO.RegisterCandidate(pubkey); + } + + [DisplayName("NEO_GetCandidates")] + public static (ECPoint, BigInteger)[] NEO_GetCandidates() + { + return NEO.GetCandidates(); + } + + [DisplayName("GAS_Decimals")] + public static int GAS_Decimals() + { + return GAS.Decimals; + } + + [DisplayName("Policy_GetFeePerByte")] + public static long Policy_GetFeePerByte() + { + return Policy.GetFeePerByte(); + } + + [DisplayName("Policy_IsBlocked")] + public static bool Policy_IsBlocked(UInt160 account) + { + return Policy.IsBlocked(account); + } + } } diff --git a/tests/Neo.TestEngine.UnitTests/Neo.TestEngine.UnitTests.csproj b/tests/Neo.TestEngine.UnitTests/Neo.TestEngine.UnitTests.csproj index 3839ea8d4..47ce6bd65 100644 --- a/tests/Neo.TestEngine.UnitTests/Neo.TestEngine.UnitTests.csproj +++ b/tests/Neo.TestEngine.UnitTests/Neo.TestEngine.UnitTests.csproj @@ -1,4 +1,4 @@ - + net5.0 diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs index 42da89412..a35c6686a 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs @@ -19,9 +19,6 @@ public void Init() CSharpCompiler.Compile(path + "/TestClasses/Contract1.cs"); CSharpCompiler.Compile(path + "/TestClasses/Contract_Time.cs"); - - //Compile changes the path, reseting so that other UT won't break - Directory.SetCurrentDirectory(path); Engine.Instance.Reset(); } diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs index 901c585dd..8bde44a5a 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs @@ -19,9 +19,6 @@ public void Init() { string path = Directory.GetCurrentDirectory(); CSharpCompiler.Compile(path + "/TestClasses/Contract_CheckWitness.cs"); - - //Compile changes the path, reseting so that other UT won't break - Directory.SetCurrentDirectory(path); Engine.Instance.Reset(); } diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs index a091aa71b..48b271e9e 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs @@ -16,9 +16,6 @@ public void Init() { string path = Directory.GetCurrentDirectory(); CSharpCompiler.Compile(path + "/TestClasses/Contract_ContractCall.cs"); - - //Compile changes the path, reseting so that other UT won't break - Directory.SetCurrentDirectory(path); Engine.Instance.Reset(); } diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs index 478833193..b05b7eb61 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs @@ -16,9 +16,6 @@ public void Init() { string path = Directory.GetCurrentDirectory(); CSharpCompiler.Compile(path + "/TestClasses/Contract1.cs"); - - //Compile changes the path, reseting so that other UT won't break - Directory.SetCurrentDirectory(path); Engine.Instance.Reset(); } diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs index e32461590..16e00bcc4 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs @@ -16,9 +16,6 @@ public void Init() { string path = Directory.GetCurrentDirectory(); CSharpCompiler.Compile(path + "/TestClasses/Contract2.cs"); - - //Compile changes the path, reseting so that other UT won't break - Directory.SetCurrentDirectory(path); Engine.Instance.Reset(); } From 531158651ada76c4f7190ffe4be757f4465c6339 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 10 May 2021 12:48:23 -0300 Subject: [PATCH 45/77] return engine for concatenating --- src/Neo.TestEngine/Engine.cs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index 8cdf0d17b..c39e51f04 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -47,9 +47,10 @@ public void Reset() engine = SetupNativeContracts(); } - public void SetEntryScript(string path) + public Engine SetEntryScript(string path) { AddSmartContract(path); + return this; } public Engine SetEntryScript(UInt160 contractHash) @@ -58,10 +59,11 @@ public Engine SetEntryScript(UInt160 contractHash) return this; } - public void AddSmartContract(TestContract contract) + public Engine AddSmartContract(TestContract contract) { var state = AddSmartContract(contract.nefPath); contract.buildScript = state; + return this; } private object AddSmartContract(string path) @@ -94,7 +96,7 @@ private object AddSmartContract(string path) return engine.ScriptContext; } - public void IncreaseBlockCount(uint newHeight) + public Engine IncreaseBlockCount(uint newHeight) { var snapshot = (TestDataCache)engine.Snapshot; if (snapshot.Blocks().Count <= newHeight) @@ -122,9 +124,10 @@ public void IncreaseBlockCount(uint newHeight) snapshot.SetCurrentBlockHash(lastBlock.Index, lastBlock.Hash); } + return this; } - public void SetStorage(Dictionary storage) + public Engine SetStorage(Dictionary storage) { if (engine.Snapshot is TestDataCache snapshot) { @@ -133,14 +136,16 @@ public void SetStorage(Dictionary storage) snapshot.AddForTest(key, value); } } + return this; } - public void SetSigners(UInt160[] signerAccounts) + public Engine SetSigners(UInt160[] signerAccounts) { if (signerAccounts.Length > 0) { currentTx.Signers = signerAccounts.Select(p => new Signer() { Account = p, Scopes = WitnessScope.CalledByEntry }).ToArray(); } + return this; } internal void SetTxAttributes(TransactionAttribute[] attributes) @@ -148,7 +153,7 @@ internal void SetTxAttributes(TransactionAttribute[] attributes) currentTx.Attributes = attributes.Where(attr => attr != null).ToArray(); } - public void AddBlock(Block block) + public Engine AddBlock(Block block) { if (engine.Snapshot is TestDataCache snapshot) { @@ -190,6 +195,7 @@ public void AddBlock(Block block) snapshot.AddOrUpdateTransactions(block.Transactions); } + return this; } public JObject Run(string method, ContractParameter[] args) From ec2f1d86f2727928743552fcc76c2e6738930019 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Thu, 13 May 2021 17:11:58 -0300 Subject: [PATCH 46/77] rename fields and use vm helper method --- src/Neo.TestEngine/Engine.cs | 5 +-- src/Neo.TestEngine/Helper.cs | 45 +------------------ .../UnitTest_Block.cs | 6 +-- .../UnitTest_CheckWitness.cs | 12 ++--- .../UnitTest_ContractCall.cs | 12 ++--- .../UnitTest_Invoke.cs | 36 +++++++-------- .../UnitTest_Notification.cs | 14 +++--- 7 files changed, 44 insertions(+), 86 deletions(-) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index c39e51f04..f93636668 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -7,7 +7,6 @@ using Neo.SmartContract.Manifest; using Neo.SmartContract.Native; using Neo.VM; -using Neo.VM.Types; using System.Collections.Generic; using System.Linq; @@ -221,7 +220,7 @@ public JObject Run(string method, ContractParameter[] args) byte[] script; using (ScriptBuilder scriptBuilder = new ScriptBuilder()) { - scriptBuilder.EmitAppCall(native.NativeContract.Hash, method, args); + scriptBuilder.EmitDynamicCall(native.NativeContract.Hash, method, args); script = scriptBuilder.ToArray(); } engine.RunNativeContract(script, method, stackItemsArgs); @@ -230,7 +229,7 @@ public JObject Run(string method, ContractParameter[] args) { using (ScriptBuilder scriptBuilder = new ScriptBuilder()) { - scriptBuilder.EmitAppCall(engine.EntryScriptHash, method, args); + scriptBuilder.EmitDynamicCall(engine.EntryScriptHash, method, args); currentTx.Script = scriptBuilder.ToArray(); } engine.ExecuteTestCaseStandard(method, stackItemsArgs); diff --git a/src/Neo.TestEngine/Helper.cs b/src/Neo.TestEngine/Helper.cs index 8b4ad189d..0351cd279 100644 --- a/src/Neo.TestEngine/Helper.cs +++ b/src/Neo.TestEngine/Helper.cs @@ -22,7 +22,7 @@ public static JObject ToJson(this TestEngine testEngine) json["vm_state"] = testEngine.State.ToString(); json["gasconsumed"] = (new BigDecimal((decimal)testEngine.GasConsumed, NativeContract.GAS.Decimals)).ToString(); - json["result_stack"] = testEngine.ResultStack.ToJson(); + json["resultstack"] = testEngine.ResultStack.ToJson(); if (testEngine.ScriptContainer is Transaction tx) { @@ -44,7 +44,7 @@ public static JObject ToJson(this EvaluationStack stack) public static JObject ToJson(this NotifyEventArgs notification) { var json = new JObject(); - json["eventName"] = notification.EventName; + json["eventname"] = notification.EventName; json["scripthash"] = notification.ScriptHash.ToString(); json["value"] = notification.State.ToJson(); return json; @@ -109,47 +109,6 @@ private static string GetExceptionMessage(Exception exception) return exception.Message; } - - public static ScriptBuilder EmitAppCall(this ScriptBuilder sb, UInt160 scriptHash, string operation, params ContractParameter[] args) - { - for (int i = args.Length - 1; i >= 0; i--) - sb.EmitPush(args[i]); - sb.EmitPush(args.Length); - sb.Emit(OpCode.PACK); - sb.EmitPush(CallFlags.All); - sb.EmitPush(operation); - sb.EmitPush(scriptHash); - sb.EmitSysCall(ApplicationEngine.System_Contract_Call); - return sb; - } - - public static ScriptBuilder EmitPush(this ScriptBuilder sb, ContractParameter parameter) - { - try - { - return VM.Helper.EmitPush(sb, parameter); - } - catch (ArgumentException) - { - if (parameter.Type == ContractParameterType.Map) - { - var parameters = (IList>)parameter.Value; - sb.Emit(OpCode.NEWMAP); - foreach (var p in parameters) - { - sb.Emit(OpCode.DUP); - sb.EmitPush(p.Key); - sb.EmitPush(p.Value); - sb.Emit(OpCode.APPEND); - } - return sb; - } - else - { - throw; - } - } - } } } diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs index a35c6686a..6cce74b73 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs @@ -81,10 +81,10 @@ public void Test_Include_Block() // test result StackItem wantresult = timestamp; - Assert.IsTrue(result.ContainsProperty("result_stack")); - Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + Assert.IsTrue(result.ContainsProperty("resultstack")); + Assert.IsInstanceOfType(result["resultstack"], typeof(JArray)); - var resultStack = result["result_stack"] as JArray; + var resultStack = result["resultstack"] as JArray; Assert.IsTrue(resultStack.Count == 1); Assert.IsTrue(resultStack[0].ContainsProperty("value")); Assert.AreEqual(resultStack[0]["value"].AsString(), wantresult.ToJson()["value"].AsString()); diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs index 8bde44a5a..d53dfda7a 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs @@ -51,10 +51,10 @@ public void Test_Check_Witness() // result stack must be empty StackItem wantresult = false; - Assert.IsTrue(result.ContainsProperty("result_stack")); - Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + Assert.IsTrue(result.ContainsProperty("resultstack")); + Assert.IsInstanceOfType(result["resultstack"], typeof(JArray)); - var resultStack = result["result_stack"] as JArray; + var resultStack = result["resultstack"] as JArray; Assert.IsTrue(resultStack.Count == 1); Assert.IsTrue(resultStack[0].ContainsProperty("value")); Assert.AreEqual(resultStack[0]["value"].AsString(), wantresult.ToJson()["value"].AsString()); @@ -90,10 +90,10 @@ public void Test_Check_Witness_With_Sign() // result stack must be empty StackItem wantresult = true; - Assert.IsTrue(result.ContainsProperty("result_stack")); - Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + Assert.IsTrue(result.ContainsProperty("resultstack")); + Assert.IsInstanceOfType(result["resultstack"], typeof(JArray)); - var resultStack = result["result_stack"] as JArray; + var resultStack = result["resultstack"] as JArray; Assert.IsTrue(resultStack.Count == 1); Assert.IsTrue(resultStack[0].ContainsProperty("value")); Assert.AreEqual(resultStack[0]["value"].AsString(), wantresult.ToJson()["value"].AsString()); diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs index 48b271e9e..d0d1aecaf 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs @@ -48,10 +48,10 @@ public void Test_Json() // test result StackItem wantresult = new byte[] { 1, 2, 3, 4 }; - Assert.IsTrue(result.ContainsProperty("result_stack")); - Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + Assert.IsTrue(result.ContainsProperty("resultstack")); + Assert.IsInstanceOfType(result["resultstack"], typeof(JArray)); - var resultStack = result["result_stack"] as JArray; + var resultStack = result["resultstack"] as JArray; Assert.IsTrue(resultStack.Count == 1); Assert.IsTrue(resultStack[0].ContainsProperty("value")); Assert.AreEqual(resultStack[0]["value"].AsString(), wantresult.ToJson()["value"].AsString()); @@ -85,10 +85,10 @@ public void Test_ContractCall_Void() Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); // test result - Assert.IsTrue(result.ContainsProperty("result_stack")); - Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + Assert.IsTrue(result.ContainsProperty("resultstack")); + Assert.IsInstanceOfType(result["resultstack"], typeof(JArray)); - var resultStack = result["result_stack"] as JArray; + var resultStack = result["resultstack"] as JArray; Assert.AreEqual(0, resultStack.Count); } } diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs index b05b7eb61..e44f35dd2 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs @@ -52,10 +52,10 @@ public void Test_Method_Without_Parameters_Void() Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); // test result - Assert.IsTrue(result.ContainsProperty("result_stack")); - Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + Assert.IsTrue(result.ContainsProperty("resultstack")); + Assert.IsInstanceOfType(result["resultstack"], typeof(JArray)); - var resultStack = result["result_stack"] as JArray; + var resultStack = result["resultstack"] as JArray; Assert.IsTrue(resultStack.Count == 0); } @@ -78,10 +78,10 @@ public void Test_Method_Without_Parameters_With_Return() // test result StackItem wantresult = new byte[] { 1, 2, 3, 4 }; - Assert.IsTrue(result.ContainsProperty("result_stack")); - Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + Assert.IsTrue(result.ContainsProperty("resultstack")); + Assert.IsInstanceOfType(result["resultstack"], typeof(JArray)); - var resultStack = result["result_stack"] as JArray; + var resultStack = result["resultstack"] as JArray; Assert.IsTrue(resultStack.Count == 1); Assert.IsTrue(resultStack[0].ContainsProperty("value")); Assert.AreEqual(resultStack[0]["value"].AsString(), wantresult.ToJson()["value"].AsString()); @@ -108,10 +108,10 @@ public void Test_Method_With_Parameters() // test result StackItem wantresult = new byte[] { 1, 2, 3, 16 }; - Assert.IsTrue(result.ContainsProperty("result_stack")); - Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + Assert.IsTrue(result.ContainsProperty("resultstack")); + Assert.IsInstanceOfType(result["resultstack"], typeof(JArray)); - var resultStack = result["result_stack"] as JArray; + var resultStack = result["resultstack"] as JArray; Assert.IsTrue(resultStack.Count == 1); Assert.IsTrue(resultStack[0].ContainsProperty("value")); Assert.AreEqual(resultStack[0]["value"].AsString(), wantresult.ToJson()["value"].AsString()); @@ -135,10 +135,10 @@ public void Test_Method_With_Misstyped_Parameters() Assert.AreEqual(result["vm_state"].AsString(), VMState.FAULT.ToString()); // result stack must be empty - Assert.IsTrue(result.ContainsProperty("result_stack")); - Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + Assert.IsTrue(result.ContainsProperty("resultstack")); + Assert.IsInstanceOfType(result["resultstack"], typeof(JArray)); - var resultStack = result["result_stack"] as JArray; + var resultStack = result["resultstack"] as JArray; Assert.IsTrue(resultStack.Count == 0); } @@ -222,10 +222,10 @@ public void Test_Json() // test result StackItem wantresult = new byte[] { 1, 2, 3, 4 }; - Assert.IsTrue(result.ContainsProperty("result_stack")); - Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + Assert.IsTrue(result.ContainsProperty("resultstack")); + Assert.IsInstanceOfType(result["resultstack"], typeof(JArray)); - var resultStack = result["result_stack"] as JArray; + var resultStack = result["resultstack"] as JArray; Assert.IsTrue(resultStack.Count == 1); Assert.IsTrue(resultStack[0].ContainsProperty("value")); Assert.AreEqual(resultStack[0]["value"].AsString(), wantresult.ToJson()["value"].AsString()); @@ -256,10 +256,10 @@ public void Test_Json_With_Parameters() // test result StackItem wantresult = new byte[] { 1, 2, 3, 16 }; - Assert.IsTrue(result.ContainsProperty("result_stack")); - Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + Assert.IsTrue(result.ContainsProperty("resultstack")); + Assert.IsInstanceOfType(result["resultstack"], typeof(JArray)); - var resultStack = result["result_stack"] as JArray; + var resultStack = result["resultstack"] as JArray; Assert.IsTrue(resultStack.Count == 1); Assert.IsTrue(resultStack[0].ContainsProperty("value")); Assert.AreEqual(resultStack[0]["value"].AsString(), wantresult.ToJson()["value"].AsString()); diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs index 16e00bcc4..b666872e8 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs @@ -43,10 +43,10 @@ public void Test_Notification() // test result StackItem wantresult = 3; - Assert.IsTrue(result.ContainsProperty("result_stack")); - Assert.IsInstanceOfType(result["result_stack"], typeof(JArray)); + Assert.IsTrue(result.ContainsProperty("resultstack")); + Assert.IsInstanceOfType(result["resultstack"], typeof(JArray)); - var resultStack = result["result_stack"] as JArray; + var resultStack = result["resultstack"] as JArray; Assert.IsTrue(resultStack.Count == 1); Assert.IsTrue(resultStack[0].ContainsProperty("value")); Assert.AreEqual(resultStack[0]["value"].AsString(), wantresult.ToJson()["value"].AsString()); @@ -59,16 +59,16 @@ public void Test_Notification() Assert.IsTrue(notifications.Count == 2); Assert.IsTrue(notifications[0].ContainsProperty("value")); - Assert.IsTrue(notifications[0].ContainsProperty("eventName")); - Assert.AreEqual(notifications[0]["eventName"].AsString(), "event"); + Assert.IsTrue(notifications[0].ContainsProperty("eventname")); + Assert.AreEqual(notifications[0]["eventname"].AsString(), "event"); Assert.IsTrue(notifications[0].ContainsProperty("value")); var firstNotifications = notifications[0]["value"]; Assert.IsTrue(firstNotifications.ContainsProperty("value")); Assert.AreEqual((firstNotifications["value"] as JArray)[0].AsString(), arg1.ToJson().ToString()); Assert.IsTrue(notifications[1].ContainsProperty("value")); - Assert.IsTrue(notifications[1].ContainsProperty("eventName")); - Assert.AreEqual(notifications[1]["eventName"].AsString(), "event"); + Assert.IsTrue(notifications[1].ContainsProperty("eventname")); + Assert.AreEqual(notifications[1]["eventname"].AsString(), "event"); Assert.IsTrue(notifications[1].ContainsProperty("value")); var secondNotifications = notifications[1]["value"]; Assert.IsTrue(secondNotifications.ContainsProperty("value")); From 90a33f7ddaf3609bcafcd677ad3a2f68cc9b3d2a Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Thu, 20 May 2021 15:57:04 -0300 Subject: [PATCH 47/77] use wallet to calculate network fee --- src/Neo.TestEngine/Engine.cs | 38 +++++++-------- src/Neo.TestEngine/Program.cs | 3 -- src/Neo.TestEngine/TestUtils/BuildNEF.cs | 14 ------ src/Neo.TestEngine/TestUtils/NeonTestTool.cs | 46 ------------------ src/Neo.TestEngine/TestUtils/TestAccount.cs | 12 +---- .../TestUtils/TestStorageContext.cs | 8 ---- src/Neo.TestEngine/TestUtils/TestWallet.cs | 47 +++++++++++++++++-- 7 files changed, 59 insertions(+), 109 deletions(-) delete mode 100644 src/Neo.TestEngine/TestUtils/BuildNEF.cs delete mode 100644 src/Neo.TestEngine/TestUtils/NeonTestTool.cs delete mode 100644 src/Neo.TestEngine/TestUtils/TestStorageContext.cs diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index f93636668..ea07143a1 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -7,6 +7,7 @@ using Neo.SmartContract.Manifest; using Neo.SmartContract.Native; using Neo.VM; +using Neo.Wallets; using System.Collections.Generic; using System.Linq; @@ -29,11 +30,13 @@ public static Engine Instance private TestEngine engine = null; private Transaction currentTx = null; - private byte[] PubKey => HexString2Bytes("03ea01cb94bdaf0cd1c01b159d474f9604f4af35a3e2196f6bdfdb33b2aa4961fa"); + private ECPoint PubKey => wallet.DefaultAccount.GetKey().PublicKey; + private TestWallet wallet = null; private Engine() { var _ = TestBlockchain.TheNeoSystem; + wallet = new TestWallet(); Reset(); } @@ -142,7 +145,14 @@ public Engine SetSigners(UInt160[] signerAccounts) { if (signerAccounts.Length > 0) { - currentTx.Signers = signerAccounts.Select(p => new Signer() { Account = p, Scopes = WitnessScope.CalledByEntry }).ToArray(); + var newSigners = new List(); + foreach (var account in signerAccounts) + { + var signer = new Signer() { Account = account, Scopes = WitnessScope.CalledByEntry }; + newSigners.Add(signer); + wallet.AddSignerAccount(account); + } + currentTx.Signers = newSigners.Concat(currentTx.Signers).ToArray(); } return this; } @@ -235,13 +245,9 @@ public JObject Run(string method, ContractParameter[] args) engine.ExecuteTestCaseStandard(method, stackItemsArgs); } - //currentTx.ValidUntilBlock = engine.Snapshot.Height + Transaction.MaxValidUntilBlockIncrement; + currentTx.ValidUntilBlock = engine.Snapshot.GetLastBlock().Index + ProtocolSettings.Default.MaxValidUntilBlockIncrement; currentTx.SystemFee = engine.GasConsumed; - UInt160[] hashes = currentTx.GetScriptHashesForVerifying(engine.Snapshot); - - // base size for transaction: includes const_header + signers + attributes + script + hashes - int size = Transaction.HeaderSize + currentTx.Signers.GetVarSize() + currentTx.Attributes.GetVarSize() + currentTx.Script.GetVarSize() + IO.Helper.GetVarSize(hashes.Length); - currentTx.NetworkFee += size * NativeContract.Policy.GetFeePerByte(engine.Snapshot); + currentTx.NetworkFee = wallet.CalculateNetworkFee(engine.Snapshot, currentTx); return engine.ToJson(); } @@ -252,7 +258,7 @@ private TestEngine SetupNativeContracts() { Attributes = new TransactionAttribute[0], Script = new byte[0], - Signers = new Signer[] { new Signer() { Account = UInt160.Zero } }, + Signers = new Signer[] { new Signer() { Account = wallet.DefaultAccount.ScriptHash } }, Witnesses = new Witness[0], NetworkFee = 1, Nonce = 2, @@ -295,7 +301,7 @@ private Block CreateBlock(Block originBlock = null) Witness = new Witness() { InvocationScript = new byte[0], - VerificationScript = Contract.CreateSignatureRedeemScript(ECPoint.FromBytes(PubKey, ECCurve.Secp256k1)) + VerificationScript = Contract.CreateSignatureRedeemScript(PubKey) }, NextConsensus = trimmedBlock.Header.NextConsensus, MerkleRoot = trimmedBlock.Header.MerkleRoot, @@ -311,17 +317,5 @@ private Block CreateBlock(Block originBlock = null) return newBlock; } - - private static byte[] HexString2Bytes(string str) - { - if (str.IndexOf("0x") == 0) - str = str.Substring(2); - byte[] outd = new byte[str.Length / 2]; - for (var i = 0; i < str.Length / 2; i++) - { - outd[i] = byte.Parse(str.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber); - } - return outd; - } } } diff --git a/src/Neo.TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs index 12624cc28..ab6df2c5e 100644 --- a/src/Neo.TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -236,9 +236,6 @@ public static JObject Run(SmartContractTest smartContractTest) Engine.Instance.IncreaseBlockCount(smartContractTest.currentHeight); Engine.Instance.SetSigners(smartContractTest.signers); - Engine.Instance.IncreaseBlockCount(smartContractTest.currentHeight); - Engine.Instance.SetSigners(smartContractTest.signers); - if (smartContractTest.currentTx != null) { Engine.Instance.SetTxAttributes(smartContractTest.currentTx.Attributes); diff --git a/src/Neo.TestEngine/TestUtils/BuildNEF.cs b/src/Neo.TestEngine/TestUtils/BuildNEF.cs deleted file mode 100644 index fd94a4034..000000000 --- a/src/Neo.TestEngine/TestUtils/BuildNEF.cs +++ /dev/null @@ -1,14 +0,0 @@ -using Neo.IO.Json; -using Neo.SmartContract; - -namespace Neo.TestingEngine -{ - class BuildNEF : BuildScript - { - public BuildNEF(NefFile nefFile, string manifestFile) - : base(nefFile, manifestJson: JObject.Parse(manifestFile)) - { - - } - } -} diff --git a/src/Neo.TestEngine/TestUtils/NeonTestTool.cs b/src/Neo.TestEngine/TestUtils/NeonTestTool.cs deleted file mode 100644 index 5bd076b17..000000000 --- a/src/Neo.TestEngine/TestUtils/NeonTestTool.cs +++ /dev/null @@ -1,46 +0,0 @@ -using Neo.VM; -using System.IO; -using System.Linq; -using System.Security.Cryptography; -using System.Text; - -namespace Neo.TestingEngine -{ - public static class NeonTestTool - { - /// - /// Is not the official script hash, just a unique hash related to the script used for unit test purpose - /// - /// Context - /// UInt160 - public static UInt160 ScriptHash(this ExecutionContext context) - { - using (var sha = SHA1.Create()) - { - return new UInt160(sha.ComputeHash(((byte[])context.Script))); - } - } - - public static string Bytes2HexString(byte[] data) - { - StringBuilder sb = new StringBuilder(); - foreach (var d in data) - { - sb.Append(d.ToString("x02")); - } - return sb.ToString(); - } - - public static byte[] HexString2Bytes(string str) - { - if (str.IndexOf("0x") == 0) - str = str.Substring(2); - byte[] outd = new byte[str.Length / 2]; - for (var i = 0; i < str.Length / 2; i++) - { - outd[i] = byte.Parse(str.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber); - } - return outd; - } - } -} diff --git a/src/Neo.TestEngine/TestUtils/TestAccount.cs b/src/Neo.TestEngine/TestUtils/TestAccount.cs index 20b3ab7d2..b640f5ff7 100644 --- a/src/Neo.TestEngine/TestUtils/TestAccount.cs +++ b/src/Neo.TestEngine/TestUtils/TestAccount.cs @@ -5,24 +5,14 @@ namespace Neo.TestingEngine class TestAccount : WalletAccount { public override bool HasKey => this.key != null; - - private byte[] privateKey; - private UInt160 scriptHash; private KeyPair key = null; public TestAccount(UInt160 scriptHash, byte[] privKey = null) : base(scriptHash, ProtocolSettings.Default) { if (privKey != null) { - this.privateKey = privKey; - } - else - { - this.privateKey = new byte[32]; + key = new KeyPair(privKey); } - - this.scriptHash = scriptHash; - this.key = new KeyPair(this.privateKey); } public override KeyPair GetKey() diff --git a/src/Neo.TestEngine/TestUtils/TestStorageContext.cs b/src/Neo.TestEngine/TestUtils/TestStorageContext.cs deleted file mode 100644 index 943b19f5c..000000000 --- a/src/Neo.TestEngine/TestUtils/TestStorageContext.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Neo.TestingEngine -{ - class TestStorageContext - { - public bool IsReadOnly { get; set; } - public UInt160 ScriptHash { get; set; } - } -} diff --git a/src/Neo.TestEngine/TestUtils/TestWallet.cs b/src/Neo.TestEngine/TestUtils/TestWallet.cs index a0c7d4f62..89bbb1069 100644 --- a/src/Neo.TestEngine/TestUtils/TestWallet.cs +++ b/src/Neo.TestEngine/TestUtils/TestWallet.cs @@ -9,13 +9,21 @@ namespace Neo.TestingEngine public class TestWallet : NEP6Wallet { private Dictionary accounts; + public WalletAccount DefaultAccount { get; private set; } - public TestWallet(UInt160 scriptHash) : base("", ProtocolSettings.Default, "TestWallet") + public TestWallet(UInt160 scriptHash = null) : base("", ProtocolSettings.Default, "TestWallet") { - this.accounts = new Dictionary() + this.accounts = new Dictionary(); + if (scriptHash == null) { - { scriptHash, new TestAccount(scriptHash) } - }; + // mock an account + var mockedPrivateKey = "a8639cbc8dc867fab51487c1ff0565600999ac73136c95454309f4883854efba".HexToBytes(); + DefaultAccount = CreateAccount(mockedPrivateKey); + } + else + { + DefaultAccount = CreateAccount(scriptHash); + } } public override bool ChangePassword(string oldPassword, string newPassword) @@ -30,7 +38,22 @@ public override bool Contains(UInt160 scriptHash) public override WalletAccount CreateAccount(byte[] privateKey) { - throw new NotImplementedException(); + if (privateKey is null) throw new ArgumentNullException(nameof(privateKey)); + KeyPair key = new(privateKey); + if (key.PublicKey.IsInfinity) throw new ArgumentException(null, nameof(privateKey)); + + Contract contract = new() + { + Script = Contract.CreateSignatureRedeemScript(key.PublicKey), + ParameterList = new[] { ContractParameterType.Signature } + }; + + var account = new TestAccount(contract.ScriptHash, privateKey) + { + Contract = contract + }; + AddAccount(account); + return account; } public override WalletAccount CreateAccount(Contract contract, KeyPair key = null) @@ -45,6 +68,14 @@ public override WalletAccount CreateAccount(UInt160 scriptHash) return account; } + private void AddAccount(TestAccount account) + { + if (!accounts.ContainsKey(account.ScriptHash)) + { + accounts[account.ScriptHash] = account; + } + } + public override bool DeleteAccount(UInt160 scriptHash) { if (!this.accounts.ContainsKey(scriptHash)) @@ -72,5 +103,11 @@ public override bool VerifyPassword(string password) { return true; } + + internal void AddSignerAccount(UInt160 scriptHash) + { + // mock for calculating network fee + this.accounts[scriptHash] = DefaultAccount; + } } } From 82a51ea89595bc07952990e93c4df518ea657fd0 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Wed, 26 May 2021 12:04:33 -0300 Subject: [PATCH 48/77] fix tx consistency in input and output --- src/Neo.TestEngine/Engine.cs | 2 +- src/Neo.TestEngine/Helper.cs | 22 ++++++++++++++++------ src/Neo.TestEngine/Program.cs | 2 +- 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index ea07143a1..eb0853099 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -258,7 +258,7 @@ private TestEngine SetupNativeContracts() { Attributes = new TransactionAttribute[0], Script = new byte[0], - Signers = new Signer[] { new Signer() { Account = wallet.DefaultAccount.ScriptHash } }, + Signers = new Signer[] { new Signer() { Account = wallet.DefaultAccount.ScriptHash, Scopes = WitnessScope.CalledByEntry } }, Witnesses = new Witness[0], NetworkFee = 1, Nonce = 2, diff --git a/src/Neo.TestEngine/Helper.cs b/src/Neo.TestEngine/Helper.cs index 0351cd279..fbe1ac4ba 100644 --- a/src/Neo.TestEngine/Helper.cs +++ b/src/Neo.TestEngine/Helper.cs @@ -88,13 +88,23 @@ public static JObject ToJson(this DataCache storage) public static JObject ToSimpleJson(this Transaction tx) { + // build a tx with the mutable fields to have a consistent hash between program input and output + var simpleTx = new Transaction() + { + Signers = tx.Signers, + Witnesses = tx.Witnesses, + Attributes = tx.Attributes, + Script = tx.Script, + ValidUntilBlock = tx.ValidUntilBlock + }; + JObject json = new JObject(); - json["hash"] = tx.Hash.ToString(); - json["size"] = tx.Size; - json["signers"] = tx.Signers.Select(p => p.ToJson()).ToArray(); - json["attributes"] = tx.Attributes.Select(p => p.ToJson()).ToArray(); - json["script"] = Convert.ToBase64String(tx.Script); - json["witnesses"] = tx.Witnesses.Select(p => p.ToJson()).ToArray(); + json["hash"] = simpleTx.Hash.ToString(); + json["size"] = simpleTx.Size; + json["signers"] = simpleTx.Signers.Select(p => p.ToJson()).ToArray(); + json["attributes"] = simpleTx.Attributes.Select(p => p.ToJson()).ToArray(); + json["script"] = Convert.ToBase64String(simpleTx.Script); + json["witnesses"] = simpleTx.Witnesses.Select(p => p.ToJson()).ToArray(); return json; } diff --git a/src/Neo.TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs index ab6df2c5e..89dc2212f 100644 --- a/src/Neo.TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -443,7 +443,7 @@ private static Transaction TxFromJson(JObject txJson) byte[] script; if (txJson.ContainsProperty("script")) { - script = txJson["script"].ToByteArray(false); + script = Convert.FromBase64String(txJson["script"].AsString()); } else if (attributes.Any(attribute => attribute is OracleResponse oracleAttr)) { From f340a1246f97e8c3705b013208812d06fb8fa1ea Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Wed, 26 May 2021 14:14:40 -0300 Subject: [PATCH 49/77] include persisting block in the output --- src/Neo.TestEngine/Engine.cs | 10 +++++++++- src/Neo.TestEngine/Helper.cs | 14 +++++++++++--- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index eb0853099..d39500482 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -213,9 +213,17 @@ public JObject Run(string method, ContractParameter[] args) { if (snapshot.Blocks().Count == 0) { - IncreaseBlockCount(0); + // don't use genesis block as persisting block + IncreaseBlockCount(1); } + var lastBlock = snapshot.GetLastBlock(); + if (lastBlock.Index == 0) + { + // don't use genesis block as persisting block + IncreaseBlockCount(1); + lastBlock = snapshot.GetLastBlock(); + } engine.PersistingBlock.Header = lastBlock.Header; engine.PersistingBlock.Transactions = lastBlock.Transactions; diff --git a/src/Neo.TestEngine/Helper.cs b/src/Neo.TestEngine/Helper.cs index fbe1ac4ba..f99e3d972 100644 --- a/src/Neo.TestEngine/Helper.cs +++ b/src/Neo.TestEngine/Helper.cs @@ -1,6 +1,4 @@ -using Neo.IO.Caching; using Neo.IO.Json; -using Neo.Ledger; using Neo.Network.P2P.Payloads; using Neo.SmartContract; using Neo.SmartContract.Native; @@ -9,7 +7,6 @@ using System; using System.Linq; using Neo.IO; -using System.Collections.Generic; using Neo.Persistence; namespace Neo.TestingEngine @@ -24,6 +21,7 @@ public static JObject ToJson(this TestEngine testEngine) json["gasconsumed"] = (new BigDecimal((decimal)testEngine.GasConsumed, NativeContract.GAS.Decimals)).ToString(); json["resultstack"] = testEngine.ResultStack.ToJson(); + json["currentblock"] = testEngine.PersistingBlock.ToSimpleJson(); if (testEngine.ScriptContainer is Transaction tx) { json["transaction"] = tx.ToSimpleJson(); @@ -86,6 +84,16 @@ public static JObject ToJson(this DataCache storage) return jsonStorage; } + public static JObject ToSimpleJson(this Block block) + { + JObject json = new JObject(); + json["hash"] = block.Hash.ToString(); + json["index"] = block.Index; + json["timestamp"] = block.Timestamp; + json["transactions"] = new JArray(block.Transactions.Select(tx => tx.ToSimpleJson())); + return json; + } + public static JObject ToSimpleJson(this Transaction tx) { // build a tx with the mutable fields to have a consistent hash between program input and output From 211437aa9107ddad3514d94b6e2f9b7eceba5edc Mon Sep 17 00:00:00 2001 From: Shargon Date: Thu, 27 May 2021 09:20:00 +0200 Subject: [PATCH 50/77] Clean enter --- src/Neo.TestEngine/TestUtils/TestEngine.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Neo.TestEngine/TestUtils/TestEngine.cs b/src/Neo.TestEngine/TestUtils/TestEngine.cs index 60dc67da7..1e5cdbfbe 100644 --- a/src/Neo.TestEngine/TestUtils/TestEngine.cs +++ b/src/Neo.TestEngine/TestUtils/TestEngine.cs @@ -141,7 +141,6 @@ public void RunNativeContract(byte[] script, string method, StackItem[] paramete ExecuteTestCaseStandard(0, (ushort)rvcount, mockedNef, new StackItem[0]); } - public void Reset() { this.State = VMState.BREAK; // Required for allow to reuse the same TestEngine From fd27e4e5cde254cfe5c54eef2b26eba96e1831ac Mon Sep 17 00:00:00 2001 From: Shargon Date: Thu, 27 May 2021 09:28:31 +0200 Subject: [PATCH 51/77] Use only privateKey in TestAccount --- src/Neo.TestEngine/Program.cs | 1 - src/Neo.TestEngine/TestUtils/TestAccount.cs | 15 ++++++++++----- src/Neo.TestEngine/TestUtils/TestWallet.cs | 11 +---------- 3 files changed, 11 insertions(+), 16 deletions(-) diff --git a/src/Neo.TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs index 89dc2212f..65d1f2bb1 100644 --- a/src/Neo.TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -153,7 +153,6 @@ public static JObject RunWithJson(JObject json) var methodName = json["method"].AsString(); var parameters = (JArray)json["arguments"]; - SmartContractTest smartContractTestCase; if (json.ContainsProperty("path") && json["path"].AsString().Length > 0) { diff --git a/src/Neo.TestEngine/TestUtils/TestAccount.cs b/src/Neo.TestEngine/TestUtils/TestAccount.cs index b640f5ff7..a96a907d1 100644 --- a/src/Neo.TestEngine/TestUtils/TestAccount.cs +++ b/src/Neo.TestEngine/TestUtils/TestAccount.cs @@ -1,18 +1,23 @@ +using Neo.SmartContract; using Neo.Wallets; +using System; namespace Neo.TestingEngine { class TestAccount : WalletAccount { public override bool HasKey => this.key != null; - private KeyPair key = null; + private readonly KeyPair key = null; - public TestAccount(UInt160 scriptHash, byte[] privKey = null) : base(scriptHash, ProtocolSettings.Default) + public TestAccount(UInt160 scriptHash) : base(scriptHash, ProtocolSettings.Default) { } + public TestAccount(KeyPair privateKey) : base(Contract.CreateSignatureRedeemScript(privateKey.PublicKey).ToScriptHash(), ProtocolSettings.Default) { - if (privKey != null) + key = privateKey ?? throw new ArgumentNullException(nameof(privateKey)); + Contract = new() { - key = new KeyPair(privKey); - } + Script = Contract.CreateSignatureRedeemScript(key.PublicKey), + ParameterList = new[] { ContractParameterType.Signature } + }; } public override KeyPair GetKey() diff --git a/src/Neo.TestEngine/TestUtils/TestWallet.cs b/src/Neo.TestEngine/TestUtils/TestWallet.cs index 89bbb1069..10594310c 100644 --- a/src/Neo.TestEngine/TestUtils/TestWallet.cs +++ b/src/Neo.TestEngine/TestUtils/TestWallet.cs @@ -42,16 +42,7 @@ public override WalletAccount CreateAccount(byte[] privateKey) KeyPair key = new(privateKey); if (key.PublicKey.IsInfinity) throw new ArgumentException(null, nameof(privateKey)); - Contract contract = new() - { - Script = Contract.CreateSignatureRedeemScript(key.PublicKey), - ParameterList = new[] { ContractParameterType.Signature } - }; - - var account = new TestAccount(contract.ScriptHash, privateKey) - { - Contract = contract - }; + var account = new TestAccount(key); AddAccount(account); return account; } From 94ee45bdcd3b8aa23d2101729e5962882f549578 Mon Sep 17 00:00:00 2001 From: Shargon Date: Thu, 27 May 2021 09:37:10 +0200 Subject: [PATCH 52/77] format --- src/Neo.TestEngine/TestUtils/TestAccount.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Neo.TestEngine/TestUtils/TestAccount.cs b/src/Neo.TestEngine/TestUtils/TestAccount.cs index a96a907d1..dbb7e2c25 100644 --- a/src/Neo.TestEngine/TestUtils/TestAccount.cs +++ b/src/Neo.TestEngine/TestUtils/TestAccount.cs @@ -1,4 +1,4 @@ -using Neo.SmartContract; +using Neo.SmartContract; using Neo.Wallets; using System; From f591212efa6fb78134e8a02c4a8e5376c129a9b6 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Fri, 28 May 2021 17:58:00 -0300 Subject: [PATCH 53/77] rename fields and cleanup code --- src/Neo.TestEngine/Helper.cs | 11 ++------- src/Neo.TestEngine/Program.cs | 6 ++--- src/Neo.TestEngine/TestUtils/TestEngine.cs | 11 +++------ .../UnitTest_Block.cs | 12 +++++----- .../UnitTest_CheckWitness.cs | 10 ++++---- .../UnitTest_ContractCall.cs | 8 +++---- .../UnitTest_Invoke.cs | 24 +++++++++---------- .../UnitTest_Notification.cs | 4 ++-- 8 files changed, 37 insertions(+), 49 deletions(-) diff --git a/src/Neo.TestEngine/Helper.cs b/src/Neo.TestEngine/Helper.cs index f99e3d972..b893b59ee 100644 --- a/src/Neo.TestEngine/Helper.cs +++ b/src/Neo.TestEngine/Helper.cs @@ -17,7 +17,7 @@ public static JObject ToJson(this TestEngine testEngine) { var json = new JObject(); - json["vm_state"] = testEngine.State.ToString(); + json["vmstate"] = testEngine.State.ToString(); json["gasconsumed"] = (new BigDecimal((decimal)testEngine.GasConsumed, NativeContract.GAS.Decimals)).ToString(); json["resultstack"] = testEngine.ResultStack.ToJson(); @@ -106,14 +106,7 @@ public static JObject ToSimpleJson(this Transaction tx) ValidUntilBlock = tx.ValidUntilBlock }; - JObject json = new JObject(); - json["hash"] = simpleTx.Hash.ToString(); - json["size"] = simpleTx.Size; - json["signers"] = simpleTx.Signers.Select(p => p.ToJson()).ToArray(); - json["attributes"] = simpleTx.Attributes.Select(p => p.ToJson()).ToArray(); - json["script"] = Convert.ToBase64String(simpleTx.Script); - json["witnesses"] = simpleTx.Witnesses.Select(p => p.ToJson()).ToArray(); - return json; + return simpleTx.ToJson(ProtocolSettings.Default); } private static string GetExceptionMessage(Exception exception) diff --git a/src/Neo.TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs index 65d1f2bb1..5e9f4d319 100644 --- a/src/Neo.TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -190,13 +190,13 @@ public static JObject RunWithJson(JObject json) } // set data for current tx - if (json.ContainsProperty("currentTx")) + if (json.ContainsProperty("currenttx")) { - smartContractTestCase.currentTx = TxFromJson(json["currentTx"]); + smartContractTestCase.currentTx = TxFromJson(json["currenttx"]); } // tx signers - if (json.ContainsProperty("signerAccounts") && json["signerAccounts"] is JArray accounts) + if (json.ContainsProperty("signeraccounts") && json["signeraccounts"] is JArray accounts) { smartContractTestCase.signers = accounts.Select(p => UInt160.Parse(p.AsString())).ToArray(); } diff --git a/src/Neo.TestEngine/TestUtils/TestEngine.cs b/src/Neo.TestEngine/TestUtils/TestEngine.cs index 1e5cdbfbe..1561d0166 100644 --- a/src/Neo.TestEngine/TestUtils/TestEngine.cs +++ b/src/Neo.TestEngine/TestUtils/TestEngine.cs @@ -125,16 +125,11 @@ public bool AddEntryScript(BuildScript script) public void RunNativeContract(byte[] script, string method, StackItem[] parameters, CallFlags flags = CallFlags.All) { - VM.Types.Array paramsArray = new VM.Types.Array(parameters); - ByteString methodName = method; - Integer callFlag = (uint)flags; - - var items = new StackItem[] { methodName, callFlag, paramsArray }; var rvcount = GetMethodReturnCount(method); - var contractScript = new TestScript(script); - var context = InvocationStack.Pop(); - context = CreateContext(contractScript, rvcount, 0); + + InvocationStack.Pop(); + var context = CreateContext(contractScript, rvcount, 0); LoadContext(context); var mockedNef = new TestNefFile(script); diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs index 6cce74b73..0b36c3f43 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_Block.cs @@ -42,8 +42,8 @@ public void Test_Block_Height() Assert.IsNull(result["error"]); // test state - Assert.IsTrue(result.ContainsProperty("vm_state")); - Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + Assert.IsTrue(result.ContainsProperty("vmstate")); + Assert.AreEqual(result["vmstate"].AsString(), VMState.HALT.ToString()); Assert.AreEqual(height, Engine.Instance.Height); } @@ -74,8 +74,8 @@ public void Test_Include_Block() Assert.IsNull(result["error"]); // test state - Assert.IsTrue(result.ContainsProperty("vm_state")); - Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + Assert.IsTrue(result.ContainsProperty("vmstate")); + Assert.AreEqual(result["vmstate"].AsString(), VMState.HALT.ToString()); Assert.AreEqual(height, Engine.Instance.Height); @@ -132,8 +132,8 @@ public void Test_Include_Transaction() Assert.IsNull(result["error"]); // test state - Assert.IsTrue(result.ContainsProperty("vm_state")); - Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + Assert.IsTrue(result.ContainsProperty("vmstate")); + Assert.AreEqual(result["vmstate"].AsString(), VMState.HALT.ToString()); Assert.AreEqual(height, Engine.Instance.Height); diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs index d53dfda7a..dca330406 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs @@ -46,8 +46,8 @@ public void Test_Check_Witness() Assert.IsNull(result["error"]); // vm state must've faulted - Assert.IsTrue(result.ContainsProperty("vm_state")); - Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + Assert.IsTrue(result.ContainsProperty("vmstate")); + Assert.AreEqual(result["vmstate"].AsString(), VMState.HALT.ToString()); // result stack must be empty StackItem wantresult = false; @@ -73,7 +73,7 @@ public void Test_Check_Witness_With_Sign() json["path"] = "./TestClasses/Contract_CheckWitness.nef"; json["method"] = "testWitness"; json["arguments"] = new JArray() { param.ToJson() }; - json["signerAccounts"] = new JArray() { scripthash.ToString() }; + json["signeraccounts"] = new JArray() { scripthash.ToString() }; var args = new string[] { json.AsString() @@ -85,8 +85,8 @@ public void Test_Check_Witness_With_Sign() Assert.IsNull(result["error"]); // vm state must've faulted - Assert.IsTrue(result.ContainsProperty("vm_state")); - Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + Assert.IsTrue(result.ContainsProperty("vmstate")); + Assert.AreEqual(result["vmstate"].AsString(), VMState.HALT.ToString()); // result stack must be empty StackItem wantresult = true; diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs index d0d1aecaf..b5b35deb3 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_ContractCall.cs @@ -43,8 +43,8 @@ public void Test_Json() Assert.IsNull(result["error"]); // test state - Assert.IsTrue(result.ContainsProperty("vm_state")); - Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + Assert.IsTrue(result.ContainsProperty("vmstate")); + Assert.AreEqual(result["vmstate"].AsString(), VMState.HALT.ToString()); // test result StackItem wantresult = new byte[] { 1, 2, 3, 4 }; @@ -81,8 +81,8 @@ public void Test_ContractCall_Void() Assert.IsNull(result["error"]); // test state - Assert.IsTrue(result.ContainsProperty("vm_state")); - Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + Assert.IsTrue(result.ContainsProperty("vmstate")); + Assert.AreEqual(result["vmstate"].AsString(), VMState.HALT.ToString()); // test result Assert.IsTrue(result.ContainsProperty("resultstack")); diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs index e44f35dd2..087534883 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_Invoke.cs @@ -48,8 +48,8 @@ public void Test_Method_Without_Parameters_Void() Assert.IsNull(result["error"]); // test state - Assert.IsTrue(result.ContainsProperty("vm_state")); - Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + Assert.IsTrue(result.ContainsProperty("vmstate")); + Assert.AreEqual(result["vmstate"].AsString(), VMState.HALT.ToString()); // test result Assert.IsTrue(result.ContainsProperty("resultstack")); @@ -73,8 +73,8 @@ public void Test_Method_Without_Parameters_With_Return() Assert.IsNull(result["error"]); // test state - Assert.IsTrue(result.ContainsProperty("vm_state")); - Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + Assert.IsTrue(result.ContainsProperty("vmstate")); + Assert.AreEqual(result["vmstate"].AsString(), VMState.HALT.ToString()); // test result StackItem wantresult = new byte[] { 1, 2, 3, 4 }; @@ -103,8 +103,8 @@ public void Test_Method_With_Parameters() Assert.IsNull(result["error"]); // test state - Assert.IsTrue(result.ContainsProperty("vm_state")); - Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + Assert.IsTrue(result.ContainsProperty("vmstate")); + Assert.AreEqual(result["vmstate"].AsString(), VMState.HALT.ToString()); // test result StackItem wantresult = new byte[] { 1, 2, 3, 16 }; @@ -131,8 +131,8 @@ public void Test_Method_With_Misstyped_Parameters() Assert.IsNotNull(result["error"]); // vm state must've faulted - Assert.IsTrue(result.ContainsProperty("vm_state")); - Assert.AreEqual(result["vm_state"].AsString(), VMState.FAULT.ToString()); + Assert.IsTrue(result.ContainsProperty("vmstate")); + Assert.AreEqual(result["vmstate"].AsString(), VMState.FAULT.ToString()); // result stack must be empty Assert.IsTrue(result.ContainsProperty("resultstack")); @@ -217,8 +217,8 @@ public void Test_Json() Assert.IsNull(result["error"]); // test state - Assert.IsTrue(result.ContainsProperty("vm_state")); - Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + Assert.IsTrue(result.ContainsProperty("vmstate")); + Assert.AreEqual(result["vmstate"].AsString(), VMState.HALT.ToString()); // test result StackItem wantresult = new byte[] { 1, 2, 3, 4 }; @@ -251,8 +251,8 @@ public void Test_Json_With_Parameters() Assert.IsNull(result["error"]); // test state - Assert.IsTrue(result.ContainsProperty("vm_state")); - Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + Assert.IsTrue(result.ContainsProperty("vmstate")); + Assert.AreEqual(result["vmstate"].AsString(), VMState.HALT.ToString()); // test result StackItem wantresult = new byte[] { 1, 2, 3, 16 }; diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs index b666872e8..1e44b8d76 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs @@ -38,8 +38,8 @@ public void Test_Notification() Assert.IsNull(result["error"]); // test state - Assert.IsTrue(result.ContainsProperty("vm_state")); - Assert.AreEqual(result["vm_state"].AsString(), VMState.HALT.ToString()); + Assert.IsTrue(result.ContainsProperty("vmstate")); + Assert.AreEqual(result["vmstate"].AsString(), VMState.HALT.ToString()); // test result StackItem wantresult = 3; From 1aec9f704bcf0ad76de00ac4467ecdbad7ed35bc Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Fri, 28 May 2021 18:23:40 -0300 Subject: [PATCH 54/77] missed field in main --- src/Neo.TestEngine/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Neo.TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs index 5e9f4d319..8fc7bf4c5 100644 --- a/src/Neo.TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -16,7 +16,7 @@ static int Main(string[] args) { JObject result = Run(args); Console.WriteLine(result); - if (!result.ContainsProperty("vm_state")) + if (!result.ContainsProperty("vmstate")) { return -1; } From 1de1ed2740c6bdca98ea8ff4a4d6f2e27daa4414 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Wed, 16 Jun 2021 17:51:50 -0300 Subject: [PATCH 55/77] call updated contract --- src/Neo.TestEngine/Engine.cs | 55 ++++++++++++++++--- src/Neo.TestEngine/Helper.cs | 2 +- src/Neo.TestEngine/TestUtils/BuildScript.cs | 10 +++- src/Neo.TestEngine/TestUtils/TestEngine.cs | 22 ++++++-- .../UnitTest_Notification.cs | 19 ++++--- 5 files changed, 87 insertions(+), 21 deletions(-) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index d39500482..e63bffe9f 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -8,6 +8,7 @@ using Neo.SmartContract.Native; using Neo.VM; using Neo.Wallets; +using System; using System.Collections.Generic; using System.Linq; @@ -80,24 +81,62 @@ private object AddSmartContract(string path) ContractState state; if (!snapshot.ContainsContract(hash)) { - state = new ContractState() + DeployContract(engine.ScriptContext); + state = NativeContract.ContractManagement.GetContract(snapshot, hash); + if (state is null) { - Id = snapshot.GetNextAvailableId(), - Hash = hash, - Nef = engine.Nef, - Manifest = ContractManifest.FromJson(engine.Manifest), - }; - snapshot.TryContractAdd(state); + state = new ContractState() + { + Id = snapshot.GetNextAvailableId(), + Hash = hash, + Nef = engine.Nef, + Manifest = ContractManifest.FromJson(engine.Manifest), + }; + snapshot.TryContractAdd(state); + } } else { state = NativeContract.ContractManagement.GetContract(snapshot, hash); - engine.AddEntryScript(new BuildScript(state.Nef, state.Manifest.ToJson())); + engine.AddEntryScript(new BuildScript(state.Nef, state.Manifest.ToJson(), hash)); } } return engine.ScriptContext; } + private void DeployContract(BuildScript scriptContext) + { + var deploy_method_name = "deploy"; + var deploy_args = new ContractParameter[] + { + new ContractParameter(ContractParameterType.ByteArray) { + Value = scriptContext.Nef.ToArray() + }, + new ContractParameter(ContractParameterType.ByteArray) { + Value = scriptContext.Manifest.ToByteArray(false) + }, + new ContractParameter(ContractParameterType.Any) + }; + + engine.AddEntryScript(NativeContract.ContractManagement.Hash); + byte[] script; + using (ScriptBuilder scriptBuilder = new ScriptBuilder()) + { + scriptBuilder.EmitDynamicCall(NativeContract.ContractManagement.Hash, deploy_method_name, deploy_args); + script = scriptBuilder.ToArray(); + } + var stackItemsArgs = deploy_args.Select(a => a.ToStackItem()).ToArray(); + engine.RunNativeContract(script, deploy_method_name, stackItemsArgs); + + if (engine.State == VMState.FAULT && engine.FaultException.Message?.StartsWith("Contract Already Exists") != true) + { + // deploying a contract already deployed is the only error expected to happen here + throw engine.FaultException; + } + + engine.SetContext(scriptContext); + } + public Engine IncreaseBlockCount(uint newHeight) { var snapshot = (TestDataCache)engine.Snapshot; diff --git a/src/Neo.TestEngine/Helper.cs b/src/Neo.TestEngine/Helper.cs index b893b59ee..8fd181fb7 100644 --- a/src/Neo.TestEngine/Helper.cs +++ b/src/Neo.TestEngine/Helper.cs @@ -18,7 +18,7 @@ public static JObject ToJson(this TestEngine testEngine) var json = new JObject(); json["vmstate"] = testEngine.State.ToString(); - json["gasconsumed"] = (new BigDecimal((decimal)testEngine.GasConsumed, NativeContract.GAS.Decimals)).ToString(); + json["gasconsumed"] = (new BigDecimal((decimal)testEngine.GasConsumedByLastExecution, NativeContract.GAS.Decimals)).ToString(); json["resultstack"] = testEngine.ResultStack.ToJson(); json["currentblock"] = testEngine.PersistingBlock.ToSimpleJson(); diff --git a/src/Neo.TestEngine/TestUtils/BuildScript.cs b/src/Neo.TestEngine/TestUtils/BuildScript.cs index 8edd2af26..07be9fb6d 100644 --- a/src/Neo.TestEngine/TestUtils/BuildScript.cs +++ b/src/Neo.TestEngine/TestUtils/BuildScript.cs @@ -10,6 +10,8 @@ namespace Neo.TestingEngine public class BuildScript { public bool Success => !FromCompilation || (Context != null && Context.Success); + + public UInt160 ScriptHash { get; private set; } public NefFile Nef { get; protected set; } public JObject Manifest { get; protected set; } public JObject DebugInfo { get; protected set; } @@ -17,10 +19,16 @@ public class BuildScript private bool FromCompilation { get; set; } - public BuildScript(NefFile nefFile, JObject manifestJson) + public BuildScript(NefFile nefFile, JObject manifestJson, UInt160 originHash = null) { Nef = nefFile; Manifest = manifestJson; + + if (originHash is null && nefFile != null) + { + originHash = Nef.Script.ToScriptHash(); + } + ScriptHash = originHash; } internal static BuildScript Build(List references = null, params string[] files) diff --git a/src/Neo.TestEngine/TestUtils/TestEngine.cs b/src/Neo.TestEngine/TestUtils/TestEngine.cs index 1561d0166..97c8dfedd 100644 --- a/src/Neo.TestEngine/TestUtils/TestEngine.cs +++ b/src/Neo.TestEngine/TestUtils/TestEngine.cs @@ -23,6 +23,9 @@ public class TestEngine : ApplicationEngine private static readonly List references = new(); + private long previousGasConsumed = 0; + public long GasConsumedByLastExecution => GasConsumed - previousGasConsumed; + public NefFile Nef { get; private set; } public JObject Manifest { get; private set; } public JObject DebugInfo { get; private set; } @@ -69,11 +72,20 @@ public TestEngine(TriggerType trigger = TriggerType.Application, IVerifiable ver public CompilationContext AddEntryScript(params string[] files) { ScriptContext = BuildScript.Build(references, files); - if (ScriptContext.Success) + SetContext(ScriptContext); + + return ScriptContext.Context; + } + + public CompilationContext SetContext(BuildScript context) + { + ScriptContext = context; + + if (context.Success) { - Nef = ScriptContext.Nef; - Manifest = ScriptContext.Manifest; - DebugInfo = ScriptContext.DebugInfo; + Nef = context.Nef; + Manifest = context.Manifest; + DebugInfo = context.DebugInfo; Reset(); } @@ -206,12 +218,14 @@ public EvaluationStack ExecuteTestCaseStandard(int offset, ushort rvcount, param public EvaluationStack ExecuteTestCaseStandard(int offset, ushort rvcount, NefFile contract, params StackItem[] args) { + previousGasConsumed = GasConsumed; var context = InvocationStack.Pop(); context = CreateContext(context.Script, rvcount, offset); LoadContext(context); // Mock contract var contextState = CurrentContext.GetState(); contextState.Contract ??= new ContractState() { Nef = contract }; + contextState.ScriptHash = ScriptContext.ScriptHash; for (var i = args.Length - 1; i >= 0; i--) this.Push(args[i]); var initializeOffset = GetMethodEntryOffset("_initialize"); diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs index 1e44b8d76..367ad8c0a 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_Notification.cs @@ -56,21 +56,26 @@ public void Test_Notification() Assert.IsInstanceOfType(result["notifications"], typeof(JArray)); var notifications = result["notifications"] as JArray; - Assert.IsTrue(notifications.Count == 2); + Assert.IsTrue(notifications.Count == 3); + // emitted Deploy notification when the contract was deployed Assert.IsTrue(notifications[0].ContainsProperty("value")); Assert.IsTrue(notifications[0].ContainsProperty("eventname")); - Assert.AreEqual(notifications[0]["eventname"].AsString(), "event"); - Assert.IsTrue(notifications[0].ContainsProperty("value")); - var firstNotifications = notifications[0]["value"]; - Assert.IsTrue(firstNotifications.ContainsProperty("value")); - Assert.AreEqual((firstNotifications["value"] as JArray)[0].AsString(), arg1.ToJson().ToString()); + Assert.AreEqual(notifications[0]["eventname"].AsString(), "Deploy"); Assert.IsTrue(notifications[1].ContainsProperty("value")); Assert.IsTrue(notifications[1].ContainsProperty("eventname")); Assert.AreEqual(notifications[1]["eventname"].AsString(), "event"); Assert.IsTrue(notifications[1].ContainsProperty("value")); - var secondNotifications = notifications[1]["value"]; + var firstNotifications = notifications[1]["value"]; + Assert.IsTrue(firstNotifications.ContainsProperty("value")); + Assert.AreEqual((firstNotifications["value"] as JArray)[0].AsString(), arg1.ToJson().ToString()); + + Assert.IsTrue(notifications[2].ContainsProperty("value")); + Assert.IsTrue(notifications[2].ContainsProperty("eventname")); + Assert.AreEqual(notifications[2]["eventname"].AsString(), "event"); + Assert.IsTrue(notifications[2].ContainsProperty("value")); + var secondNotifications = notifications[2]["value"]; Assert.IsTrue(secondNotifications.ContainsProperty("value")); Assert.AreEqual((secondNotifications["value"] as JArray)[0].AsString(), arg2.ToJson().ToString()); } From 0033226de2888759bdce149cfefca23b42639a59 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Tue, 13 Jul 2021 13:03:03 -0300 Subject: [PATCH 56/77] include nonce in block helper methods --- src/Neo.TestEngine/Engine.cs | 1 + src/Neo.TestEngine/TestUtils/TestBlockchain.cs | 1 + 2 files changed, 2 insertions(+) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index e63bffe9f..7901fb200 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -345,6 +345,7 @@ private Block CreateBlock(Block originBlock = null) { Index = trimmedBlock.Index + 1, Timestamp = trimmedBlock.Header.Timestamp + TestBlockchain.TheNeoSystem.Settings.MillisecondsPerBlock, + Nonce = trimmedBlock.Header.Nonce, Witness = new Witness() { InvocationScript = new byte[0], diff --git a/src/Neo.TestEngine/TestUtils/TestBlockchain.cs b/src/Neo.TestEngine/TestUtils/TestBlockchain.cs index caa07d6db..5d8a888f9 100644 --- a/src/Neo.TestEngine/TestUtils/TestBlockchain.cs +++ b/src/Neo.TestEngine/TestUtils/TestBlockchain.cs @@ -97,6 +97,7 @@ public static TrimmedBlock Trim(this Block block) Version = block.Version, PrevHash = block.PrevHash, MerkleRoot = block.MerkleRoot, + Nonce = block.Nonce, Timestamp = block.Timestamp, Index = block.Index, NextConsensus = block.NextConsensus, From 7dded4338e39495719b9ab8dae9e93a4bf89de44 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Wed, 15 Sep 2021 18:02:25 -0300 Subject: [PATCH 57/77] Improve error messages on the TestEngine when the types are incorrect --- src/Neo.TestEngine/Program.cs | 75 ++++++++++++++++++++++++++++++----- 1 file changed, 64 insertions(+), 11 deletions(-) diff --git a/src/Neo.TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs index 3285e8c06..2ea39a3a9 100644 --- a/src/Neo.TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -171,7 +171,11 @@ public static JObject RunWithJson(JObject json) } else { - var scriptHash = UInt160.Parse(json["scripthash"].AsString()); + if (!UInt160.TryParse(json["scripthash"].AsString(), out var scriptHash)) + { + throw new FormatException(GetInvalidTypeMessage("UInt160", "scripthash")); + } + smartContractTestCase = new SmartContractTest(scriptHash, methodName, parameters); } @@ -196,7 +200,10 @@ public static JObject RunWithJson(JObject json) // set the current heigh if (json.ContainsProperty("height")) { - smartContractTestCase.currentHeight = uint.Parse(json["height"].AsString()); + if (!uint.TryParse(json["height"].AsString(), out smartContractTestCase.currentHeight)) + { + throw new FormatException(GetInvalidTypeMessage("uint", "height")); + } } // set data for current tx @@ -208,7 +215,14 @@ public static JObject RunWithJson(JObject json) // tx signers if (json.ContainsProperty("signeraccounts") && json["signeraccounts"] is JArray accounts) { - smartContractTestCase.signers = accounts.Select(p => UInt160.Parse(p.AsString())).ToArray(); + smartContractTestCase.signers = accounts.Select(p => + { + if (!UInt160.TryParse(p.AsString(), out var newAccount)) + { + throw new FormatException(GetInvalidTypeMessage("UInt160", "signeraccounts")); + } + return newAccount; + }).ToArray(); } return Run(smartContractTestCase); } @@ -308,9 +322,14 @@ private static Dictionary GetStorageFromJson(JObject js var key = (PrimitiveType)ContractParameter.FromJson(jsonKey["key"]).ToStackItem(); var value = ContractParameter.FromJson(jsonValue["value"]).ToStackItem(); + if (!int.TryParse(jsonKey["id"].AsString(), out var storageKeyId)) + { + throw new FormatException(GetInvalidTypeMessage("int", "storageKeyId")); + } + var storageKey = new StorageKey() { - Id = int.Parse(jsonKey["id"].AsString()), + Id = storageKeyId, Key = key.GetSpan().ToArray() }; @@ -394,12 +413,22 @@ private static ContractParameter[] GetStackItemParameters(JArray parameters) private static Block BlockFromJson(JObject blockJson) { var transactions = blockJson["transactions"] as JArray; + + if (!uint.TryParse(blockJson["index"].AsString(), out var blockIndex)) + { + throw new FormatException(GetInvalidTypeMessage("uint", "blockIndex")); + } + if (!ulong.TryParse(blockJson["timestamp"].AsString(), out var blockTimestamp)) + { + throw new FormatException(GetInvalidTypeMessage("ulong", "blockTimestamp")); + } + return new Block() { Header = new Header() { - Index = uint.Parse(blockJson["index"].AsString()), - Timestamp = ulong.Parse(blockJson["timestamp"].AsString()) + Index = blockIndex, + Timestamp = blockTimestamp }, Transactions = transactions.Select(b => TxFromJson(b)).ToArray() }; @@ -413,10 +442,18 @@ private static Transaction TxFromJson(JObject txJson) if (txJson.ContainsProperty("signers") && txJson["signers"] is JArray signersJson) { - accounts = signersJson.Select(p => new Signer() + accounts = signersJson.Select(p => { - Account = UInt160.Parse(p["account"].AsString()), - Scopes = WitnessScope.CalledByEntry + if (!UInt160.TryParse(p["account"].AsString(), out var signerAccount)) + { + throw new FormatException(GetInvalidTypeMessage("UInt160", "signerAccount")); + } + + return new Signer() + { + Account = signerAccount, + Scopes = WitnessScope.CalledByEntry + }; }).ToArray(); } else @@ -490,12 +527,16 @@ private static TransactionAttribute TxAttributeFromJson(JObject txAttributeJson) if (!Enum.TryParse(txAttributeJson["code"].AsString(), out var responseCode)) { - throw new ArgumentException(); + throw new ArgumentException(GetInvalidTypeMessage("OracleResponseCode", "oracleResponseCode")); + } + if (!ulong.TryParse(txAttributeJson["id"].AsString(), out var oracleId)) + { + throw new ArgumentException(GetInvalidTypeMessage("ulong", "oracleResponseId")); } return new OracleResponse() { - Id = ulong.Parse(txAttributeJson["id"].AsString()), + Id = oracleId, Code = responseCode, Result = Convert.FromBase64String(txAttributeJson["result"].AsString()) }; @@ -527,5 +568,17 @@ private static JObject BuildJsonException(string message) json["error"] = message; return json; } + + private static string GetInvalidTypeMessage(string expectedType, string argumentId = null) + { + if (argumentId is null) + { + return $"Invalid value were given. Expected {expectedType}"; + } + else + { + return $"Invalid value for {argumentId}. Expected {expectedType}"; + } + } } } From 02be35ff75dff8ee98f7822982d98dcd59049bed Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Wed, 15 Sep 2021 18:04:19 -0300 Subject: [PATCH 58/77] format --- src/Neo.TestEngine/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Neo.TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs index 2ea39a3a9..e28b73504 100644 --- a/src/Neo.TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -219,7 +219,7 @@ public static JObject RunWithJson(JObject json) { if (!UInt160.TryParse(p.AsString(), out var newAccount)) { - throw new FormatException(GetInvalidTypeMessage("UInt160", "signeraccounts")); + throw new FormatException(GetInvalidTypeMessage("UInt160", "signerAccount")); } return newAccount; }).ToArray(); From c2dbad469d8f919c9058f2a148eee2b9efb2300f Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Wed, 15 Sep 2021 19:21:20 -0300 Subject: [PATCH 59/77] interface to signer witness scope --- src/Neo.TestEngine/Engine.cs | 9 ++++----- src/Neo.TestEngine/Program.cs | 21 ++++++++++++++++++--- src/Neo.TestEngine/SmartContractTest.cs | 4 ++-- 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index 1f094178a..c44beb60e 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -190,16 +190,15 @@ public Engine SetStorage(Dictionary storage) return this; } - public Engine SetSigners(UInt160[] signerAccounts) + public Engine SetSigners(Signer[] signers) { - if (signerAccounts.Length > 0) + if (signers.Length > 0) { var newSigners = new List(); - foreach (var account in signerAccounts) + foreach (var signer in signers) { - var signer = new Signer() { Account = account, Scopes = WitnessScope.CalledByEntry }; newSigners.Add(signer); - wallet.AddSignerAccount(account); + wallet.AddSignerAccount(signer.Account); } currentTx.Signers = newSigners.Concat(currentTx.Signers).ToArray(); } diff --git a/src/Neo.TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs index e28b73504..3364d63ba 100644 --- a/src/Neo.TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -215,13 +215,28 @@ public static JObject RunWithJson(JObject json) // tx signers if (json.ContainsProperty("signeraccounts") && json["signeraccounts"] is JArray accounts) { - smartContractTestCase.signers = accounts.Select(p => + smartContractTestCase.signers = accounts.Select(accountJson => { - if (!UInt160.TryParse(p.AsString(), out var newAccount)) + if (!UInt160.TryParse(accountJson["account"].AsString(), out var newAccount)) { throw new FormatException(GetInvalidTypeMessage("UInt160", "signerAccount")); } - return newAccount; + + WitnessScope scopes; + if (!accountJson.ContainsProperty("scopes")) + { + scopes = WitnessScope.CalledByEntry; + } + else if (!Enum.TryParse(accountJson["scopes"].AsString(), out scopes)) + { + throw new FormatException(GetInvalidTypeMessage("WitnessScope", "signerScope")); + } + + return new Signer() + { + Account = newAccount, + Scopes = scopes + }; }).ToArray(); } return Run(smartContractTestCase); diff --git a/src/Neo.TestEngine/SmartContractTest.cs b/src/Neo.TestEngine/SmartContractTest.cs index d017c8c16..328637b7e 100644 --- a/src/Neo.TestEngine/SmartContractTest.cs +++ b/src/Neo.TestEngine/SmartContractTest.cs @@ -24,7 +24,7 @@ public class SmartContractTest public Dictionary storage; public List contracts; public uint currentHeight = 0; - public UInt160[] signers; + public Signer[] signers; public Block[] blocks; public Transaction currentTx; @@ -44,7 +44,7 @@ private SmartContractTest(string method, JArray parameters) methodParameters = parameters; storage = new Dictionary(); contracts = new List(); - signers = new UInt160[] { }; + signers = new Signer[] { }; blocks = new Block[] { }; } } From 4fddf69da59cb728bd8212cea963a7c585a5738a Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Thu, 16 Sep 2021 17:03:21 -0300 Subject: [PATCH 60/77] fix unit test --- tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs b/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs index dca330406..3b00f67f3 100644 --- a/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs +++ b/tests/Neo.TestEngine.UnitTests/UnitTest_CheckWitness.cs @@ -73,7 +73,10 @@ public void Test_Check_Witness_With_Sign() json["path"] = "./TestClasses/Contract_CheckWitness.nef"; json["method"] = "testWitness"; json["arguments"] = new JArray() { param.ToJson() }; - json["signeraccounts"] = new JArray() { scripthash.ToString() }; + + var signer = new JObject(); + signer["account"] = scripthash.ToString(); + json["signeraccounts"] = new JArray() { signer }; var args = new string[] { json.AsString() From e8c6ed288f204b5c597ca25bb2c00b7c2cd8bf1b Mon Sep 17 00:00:00 2001 From: Merl111 Date: Wed, 20 Oct 2021 17:25:19 +0200 Subject: [PATCH 61/77] feat, add handling for InteropInterface wrapped iterators --- src/Neo.TestEngine/Helper.cs | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/src/Neo.TestEngine/Helper.cs b/src/Neo.TestEngine/Helper.cs index e26cb3a09..8b1f19adf 100644 --- a/src/Neo.TestEngine/Helper.cs +++ b/src/Neo.TestEngine/Helper.cs @@ -16,8 +16,8 @@ using Neo.VM.Types; using System; using System.Linq; -using Neo.IO; using Neo.Persistence; +using Neo.SmartContract.Iterators; namespace Neo.TestingEngine { @@ -46,7 +46,30 @@ public static JObject ToJson(this TestEngine testEngine) public static JObject ToJson(this EvaluationStack stack) { - return new JArray(stack.Select(p => p.ToJson())); + JArray jarr = new(); + foreach (var item in stack) + { + if (item is InteropInterface interopInterface && interopInterface.GetInterface() is IIterator iterator) + { + var max = 100; + JObject json = item.ToJson(); + JArray array = new(); + while (max > 0 && iterator.Next()) + { + array.Add(iterator.Value().ToJson()); + max--; + } + json["iterator"] = array; + json["truncated"] = iterator.Next(); + jarr.Add(json); + } + else + { + jarr.Add(item.ToJson()); + } + } + + return jarr; } public static JObject ToJson(this NotifyEventArgs notification) From e68accf8d6bc609ac26e6e6fbc503de9ddbc60cd Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Tue, 16 Nov 2021 17:29:18 -0300 Subject: [PATCH 62/77] dotnet format --- src/Neo.TestEngine/Engine.cs | 16 ++++++++-------- src/Neo.TestEngine/Extensions/TestExtensions.cs | 2 +- src/Neo.TestEngine/Program.cs | 6 +++--- src/Neo.TestEngine/SmartContractTest.cs | 2 +- src/Neo.TestEngine/TestContract.cs | 2 +- src/Neo.TestEngine/TestUtils/BuildScript.cs | 8 ++++---- src/Neo.TestEngine/TestUtils/TestAccount.cs | 2 +- src/Neo.TestEngine/TestUtils/TestBlockchain.cs | 2 +- src/Neo.TestEngine/TestUtils/TestDataCache.cs | 6 +++--- src/Neo.TestEngine/TestUtils/TestEngine.cs | 2 +- src/Neo.TestEngine/TestUtils/TestWallet.cs | 4 ++-- 11 files changed, 26 insertions(+), 26 deletions(-) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index c44beb60e..90f589304 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -26,7 +26,7 @@ namespace Neo.TestingEngine { public class Engine { - private static Engine instance = null; + private static Engine? instance = null; public static Engine Instance { get @@ -39,10 +39,10 @@ public static Engine Instance } } - private TestEngine engine = null; - private Transaction currentTx = null; + private TestEngine? engine = null; + private Transaction? currentTx = null; private ECPoint PubKey => wallet.DefaultAccount.GetKey().PublicKey; - private TestWallet wallet = null; + private TestWallet? wallet = null; private Engine() { @@ -153,7 +153,7 @@ public Engine IncreaseBlockCount(uint newHeight) if (snapshot.Blocks().Count <= newHeight) { Block newBlock; - Block lastBlock = null; + Block? lastBlock = null; if (snapshot.Blocks().Count == 0) { newBlock = TestBlockchain.TheNeoSystem.GenesisBlock; @@ -214,7 +214,7 @@ public Engine AddBlock(Block block) { if (engine.Snapshot is TestDataCache snapshot) { - Block currentBlock = null; + Block? currentBlock = null; if (Height < block.Index || snapshot.Blocks().Count == 0) { IncreaseBlockCount(block.Index); @@ -334,9 +334,9 @@ private TestEngine SetupNativeContracts() return engine; } - private Block CreateBlock(Block originBlock = null) + private Block CreateBlock(Block? originBlock = null) { - TrimmedBlock trimmedBlock = null; + TrimmedBlock? trimmedBlock = null; var blocks = engine.Snapshot.Blocks(); if (blocks.Count > 0) { diff --git a/src/Neo.TestEngine/Extensions/TestExtensions.cs b/src/Neo.TestEngine/Extensions/TestExtensions.cs index 2ceb84e44..d638f2b65 100644 --- a/src/Neo.TestEngine/Extensions/TestExtensions.cs +++ b/src/Neo.TestEngine/Extensions/TestExtensions.cs @@ -42,7 +42,7 @@ public static void DeleteContract(this DataCache snapshot, UInt160 hash) } } - public static void DeployNativeContracts(this DataCache snapshot, Block persistingBlock = null) + public static void DeployNativeContracts(this DataCache snapshot, Block? persistingBlock = null) { persistingBlock ??= new NeoSystem(ProtocolSettings.Default).GenesisBlock; var method = typeof(ContractManagement).GetMethod("OnPersist", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); diff --git a/src/Neo.TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs index 3364d63ba..eb338bcc9 100644 --- a/src/Neo.TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -348,7 +348,7 @@ private static Dictionary GetStorageFromJson(JObject js Key = key.GetSpan().ToArray() }; - StorageItem storageItem = null; + StorageItem? storageItem = null; if (value != StackItem.Null) { storageItem = new StorageItem(value.GetSpan().ToArray()); @@ -524,7 +524,7 @@ private static Transaction TxFromJson(JObject txJson) }; } - private static TransactionAttribute TxAttributeFromJson(JObject txAttributeJson) + private static TransactionAttribute? TxAttributeFromJson(JObject txAttributeJson) { if (!txAttributeJson.ContainsProperty("type")) { @@ -584,7 +584,7 @@ private static JObject BuildJsonException(string message) return json; } - private static string GetInvalidTypeMessage(string expectedType, string argumentId = null) + private static string GetInvalidTypeMessage(string expectedType, string? argumentId = null) { if (argumentId is null) { diff --git a/src/Neo.TestEngine/SmartContractTest.cs b/src/Neo.TestEngine/SmartContractTest.cs index 328637b7e..7e64c2787 100644 --- a/src/Neo.TestEngine/SmartContractTest.cs +++ b/src/Neo.TestEngine/SmartContractTest.cs @@ -18,7 +18,7 @@ namespace Neo.TestingEngine public class SmartContractTest { public readonly UInt160 scriptHash = null; - public readonly string nefPath = null; + public readonly string? nefPath = null; public readonly string methodName; public JArray methodParameters; public Dictionary storage; diff --git a/src/Neo.TestEngine/TestContract.cs b/src/Neo.TestEngine/TestContract.cs index cd88cd737..c96a66cd1 100644 --- a/src/Neo.TestEngine/TestContract.cs +++ b/src/Neo.TestEngine/TestContract.cs @@ -15,7 +15,7 @@ namespace Neo.TestingEngine public class TestContract { internal string nefPath; - internal object buildScript = null; + internal object? buildScript = null; public TestContract(string path) { diff --git a/src/Neo.TestEngine/TestUtils/BuildScript.cs b/src/Neo.TestEngine/TestUtils/BuildScript.cs index daec55af6..0ff4a1020 100644 --- a/src/Neo.TestEngine/TestUtils/BuildScript.cs +++ b/src/Neo.TestEngine/TestUtils/BuildScript.cs @@ -41,7 +41,7 @@ public BuildScript(NefFile nefFile, JObject manifestJson, UInt160 originHash = n ScriptHash = originHash; } - internal static BuildScript Build(List references = null, params string[] files) + internal static BuildScript Build(List? references = null, params string[] files) { BuildScript script; if (files.Length == 1 && Path.GetExtension(files[0]).ToLowerInvariant() == ".nef") @@ -61,9 +61,9 @@ internal static BuildScript Build(List references = null, par } else { - NefFile nef = null; - JObject manifest = null; - JObject debuginfo = null; + NefFile? nef = null; + JObject? manifest = null; + JObject? debuginfo = null; var options = new Options { diff --git a/src/Neo.TestEngine/TestUtils/TestAccount.cs b/src/Neo.TestEngine/TestUtils/TestAccount.cs index 264aed568..495d2d814 100644 --- a/src/Neo.TestEngine/TestUtils/TestAccount.cs +++ b/src/Neo.TestEngine/TestUtils/TestAccount.cs @@ -17,7 +17,7 @@ namespace Neo.TestingEngine class TestAccount : WalletAccount { public override bool HasKey => this.key != null; - private readonly KeyPair key = null; + private readonly KeyPair? key = null; public TestAccount(UInt160 scriptHash) : base(scriptHash, ProtocolSettings.Default) { } public TestAccount(KeyPair privateKey) : base(Contract.CreateSignatureRedeemScript(privateKey.PublicKey).ToScriptHash(), ProtocolSettings.Default) diff --git a/src/Neo.TestEngine/TestUtils/TestBlockchain.cs b/src/Neo.TestEngine/TestUtils/TestBlockchain.cs index f1781e129..9546664e8 100644 --- a/src/Neo.TestEngine/TestUtils/TestBlockchain.cs +++ b/src/Neo.TestEngine/TestUtils/TestBlockchain.cs @@ -34,7 +34,7 @@ static TestBlockchain() TheNeoSystem = new NeoSystem(ProtocolSettings.Default); } - public static StorageKey CreateStorageKey(this NativeContract contract, byte prefix, ISerializable key = null) + public static StorageKey CreateStorageKey(this NativeContract contract, byte prefix, ISerializable? key = null) { var k = new KeyBuilder(contract.Id, prefix); if (key != null) k = k.Add(key); diff --git a/src/Neo.TestEngine/TestUtils/TestDataCache.cs b/src/Neo.TestEngine/TestUtils/TestDataCache.cs index 31270e34d..d0b5039ce 100644 --- a/src/Neo.TestEngine/TestUtils/TestDataCache.cs +++ b/src/Neo.TestEngine/TestUtils/TestDataCache.cs @@ -20,7 +20,7 @@ public class TestDataCache : DataCache { private readonly Dictionary dict = new(); - public TestDataCache(Block persistingBlock = null) + public TestDataCache(Block? persistingBlock = null) { this.DeployNativeContracts(persistingBlock); } @@ -40,7 +40,7 @@ protected override bool ContainsInternal(StorageKey key) return dict.ContainsKey(key); } - protected override StorageItem GetInternal(StorageKey key) + protected override StorageItem? GetInternal(StorageKey key) { if (!dict.TryGetValue(key, out var value)) { @@ -55,7 +55,7 @@ protected override StorageItem GetInternal(StorageKey key) return dict.Select(u => (u.Key, u.Value)); } - protected override StorageItem TryGetInternal(StorageKey key) + protected override StorageItem? TryGetInternal(StorageKey key) { return dict.TryGetValue(key, out var value) ? value : null; } diff --git a/src/Neo.TestEngine/TestUtils/TestEngine.cs b/src/Neo.TestEngine/TestUtils/TestEngine.cs index f691f0893..9acc2ac74 100644 --- a/src/Neo.TestEngine/TestUtils/TestEngine.cs +++ b/src/Neo.TestEngine/TestUtils/TestEngine.cs @@ -74,7 +74,7 @@ static TestEngine() } } - public TestEngine(TriggerType trigger = TriggerType.Application, IVerifiable verificable = null, DataCache snapshot = null, Block persistingBlock = null, SmartContract.Diagnostic diagnostic = null) + public TestEngine(TriggerType trigger = TriggerType.Application, IVerifiable? verificable = null, DataCache? snapshot = null, Block? persistingBlock = null, SmartContract.Diagnostic? diagnostic = null) : base(trigger, verificable, snapshot, persistingBlock, ProtocolSettings.Default, TestGas, diagnostic) { } diff --git a/src/Neo.TestEngine/TestUtils/TestWallet.cs b/src/Neo.TestEngine/TestUtils/TestWallet.cs index f1aac261d..dccc5cd33 100644 --- a/src/Neo.TestEngine/TestUtils/TestWallet.cs +++ b/src/Neo.TestEngine/TestUtils/TestWallet.cs @@ -57,7 +57,7 @@ public override WalletAccount CreateAccount(byte[] privateKey) return account; } - public override WalletAccount CreateAccount(Contract contract, KeyPair key = null) + public override WalletAccount CreateAccount(Contract contract, KeyPair? key = null) { throw new NotImplementedException(); } @@ -86,7 +86,7 @@ public override bool DeleteAccount(UInt160 scriptHash) return accounts.Remove(scriptHash); } - public override WalletAccount GetAccount(UInt160 scriptHash) + public override WalletAccount? GetAccount(UInt160 scriptHash) { if (!this.accounts.ContainsKey(scriptHash)) { From e64dedd4f6c74792edeb04a54fb25db9a371c72a Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Thu, 25 Nov 2021 15:09:59 -0300 Subject: [PATCH 63/77] dotnet format --- .../Neo.Compiler.CSharp.csproj | 2 +- .../Neo.SmartContract.Framework.csproj | 2 +- .../Neo.SmartContract.Template.csproj | 2 +- src/Neo.TestEngine/Neo.TestEngine.csproj | 19 +---- src/Neo.TestEngine/SmartContractTest.cs | 2 +- src/Neo.TestEngine/TestUtils/BuildScript.cs | 2 +- src/Neo.TestEngine/TestUtils/TestWallet.cs | 2 +- .../Neo.Compiler.CSharp.UnitTests.csproj | 2 +- .../TestClasses/Contract_Event.cs | 6 +- .../TestClasses/Contract_Initializer.cs | 14 ++-- .../TestClasses/Contract_Interfaces.cs | 78 +++++++++---------- .../TestClasses/Contract_Partial.2.cs | 2 +- ...o.SmartContract.Framework.UnitTests.csproj | 2 +- .../TestClasses/Contract_StdLib.cs | 16 ++-- 14 files changed, 69 insertions(+), 82 deletions(-) diff --git a/src/Neo.Compiler.CSharp/Neo.Compiler.CSharp.csproj b/src/Neo.Compiler.CSharp/Neo.Compiler.CSharp.csproj index 9e5b23743..9aada6e57 100644 --- a/src/Neo.Compiler.CSharp/Neo.Compiler.CSharp.csproj +++ b/src/Neo.Compiler.CSharp/Neo.Compiler.CSharp.csproj @@ -1,4 +1,4 @@ - + Neo.Compiler.CSharp diff --git a/src/Neo.SmartContract.Framework/Neo.SmartContract.Framework.csproj b/src/Neo.SmartContract.Framework/Neo.SmartContract.Framework.csproj index 66991944d..a81f22a00 100644 --- a/src/Neo.SmartContract.Framework/Neo.SmartContract.Framework.csproj +++ b/src/Neo.SmartContract.Framework/Neo.SmartContract.Framework.csproj @@ -1,4 +1,4 @@ - + Neo.SmartContract.Framework diff --git a/src/Neo.SmartContract.Template/Neo.SmartContract.Template.csproj b/src/Neo.SmartContract.Template/Neo.SmartContract.Template.csproj index 378937f38..d21c865bb 100644 --- a/src/Neo.SmartContract.Template/Neo.SmartContract.Template.csproj +++ b/src/Neo.SmartContract.Template/Neo.SmartContract.Template.csproj @@ -1,4 +1,4 @@ - + Neo.SmartContract.Template diff --git a/src/Neo.TestEngine/Neo.TestEngine.csproj b/src/Neo.TestEngine/Neo.TestEngine.csproj index de21d620f..0e0257e40 100644 --- a/src/Neo.TestEngine/Neo.TestEngine.csproj +++ b/src/Neo.TestEngine/Neo.TestEngine.csproj @@ -23,22 +23,9 @@ - + + scfx + - - - - - neo - - - - diff --git a/src/Neo.TestEngine/SmartContractTest.cs b/src/Neo.TestEngine/SmartContractTest.cs index 7e64c2787..9a3cc9ea5 100644 --- a/src/Neo.TestEngine/SmartContractTest.cs +++ b/src/Neo.TestEngine/SmartContractTest.cs @@ -17,7 +17,7 @@ namespace Neo.TestingEngine { public class SmartContractTest { - public readonly UInt160 scriptHash = null; + public readonly UInt160? scriptHash = null; public readonly string? nefPath = null; public readonly string methodName; public JArray methodParameters; diff --git a/src/Neo.TestEngine/TestUtils/BuildScript.cs b/src/Neo.TestEngine/TestUtils/BuildScript.cs index 0ff4a1020..eaf89576b 100644 --- a/src/Neo.TestEngine/TestUtils/BuildScript.cs +++ b/src/Neo.TestEngine/TestUtils/BuildScript.cs @@ -29,7 +29,7 @@ public class BuildScript private bool FromCompilation { get; set; } - public BuildScript(NefFile nefFile, JObject manifestJson, UInt160 originHash = null) + public BuildScript(NefFile nefFile, JObject manifestJson, UInt160? originHash = null) { Nef = nefFile; Manifest = manifestJson; diff --git a/src/Neo.TestEngine/TestUtils/TestWallet.cs b/src/Neo.TestEngine/TestUtils/TestWallet.cs index dccc5cd33..cf814040c 100644 --- a/src/Neo.TestEngine/TestUtils/TestWallet.cs +++ b/src/Neo.TestEngine/TestUtils/TestWallet.cs @@ -21,7 +21,7 @@ public class TestWallet : NEP6Wallet private Dictionary accounts; public WalletAccount DefaultAccount { get; private set; } - public TestWallet(UInt160 scriptHash = null) : base("", ProtocolSettings.Default, "TestWallet") + public TestWallet(UInt160? scriptHash = null) : base("", ProtocolSettings.Default, "TestWallet") { this.accounts = new Dictionary(); if (scriptHash == null) diff --git a/tests/Neo.Compiler.CSharp.UnitTests/Neo.Compiler.CSharp.UnitTests.csproj b/tests/Neo.Compiler.CSharp.UnitTests/Neo.Compiler.CSharp.UnitTests.csproj index cb8750091..f74e14369 100644 --- a/tests/Neo.Compiler.CSharp.UnitTests/Neo.Compiler.CSharp.UnitTests.csproj +++ b/tests/Neo.Compiler.CSharp.UnitTests/Neo.Compiler.CSharp.UnitTests.csproj @@ -1,4 +1,4 @@ - + net6.0 diff --git a/tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract_Event.cs b/tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract_Event.cs index fbe68c5ad..895c5a355 100644 --- a/tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract_Event.cs +++ b/tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract_Event.cs @@ -12,10 +12,10 @@ public class Contract_Event : SmartContract.Framework.SmartContract [DisplayName("transfer")] public static event Action Transferred; - public static void Main(string method, object[] args) - { + public static void Main(string method, object[] args) + { MyStaticVar1 = 1; - MyStaticVar2 = true; + MyStaticVar2 = true; } } } diff --git a/tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract_Initializer.cs b/tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract_Initializer.cs index 291471c5f..db35d573e 100644 --- a/tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract_Initializer.cs +++ b/tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract_Initializer.cs @@ -5,8 +5,8 @@ namespace Neo.Compiler.CSharp.UnitTests.TestClasses { public class Contract_Initializer : SmartContract.Framework.SmartContract { - public class data - { + public class data + { public int A = 1; public int B = 2; } @@ -19,10 +19,10 @@ public int sum() public int sum1(int a, int b) { - var x = new data - { + var x = new data + { A = a, - B = b + B = b }; return x.A + x.B; } @@ -30,8 +30,8 @@ public int sum1(int a, int b) public int sum2(int a, int b) { var x = new data(); - x.A = a; - x.B = b; + x.A = a; + x.B = b; return x.A + x.B; } } diff --git a/tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract_Interfaces.cs b/tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract_Interfaces.cs index af68bce8f..70d578a83 100644 --- a/tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract_Interfaces.cs +++ b/tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract_Interfaces.cs @@ -1,48 +1,48 @@ -using Neo.SmartContract.Framework.Services; -using System.Numerics; +using Neo.SmartContract.Framework.Services; +using System.Numerics; namespace Neo.Compiler.CSharp.UnitTests.TestClasses -{ - interface IStorageMap - { - TValue this[TKey account] { get; set; } - } - - class AccountStorage : IStorageMap - { - readonly StorageMap map; - - public AccountStorage() - { - map = new StorageMap(Storage.CurrentContext, nameof(AccountStorage)); - } - - public BigInteger this[UInt160 account] - { - get => (BigInteger)map.Get(account); - set => map.Put(account, value); - } +{ + interface IStorageMap + { + TValue this[TKey account] { get; set; } + } + + class AccountStorage : IStorageMap + { + readonly StorageMap map; + + public AccountStorage() + { + map = new StorageMap(Storage.CurrentContext, nameof(AccountStorage)); + } + + public BigInteger this[UInt160 account] + { + get => (BigInteger)map.Get(account); + set => map.Put(account, value); + } } public class Contract_Interfaces : SmartContract.Framework.SmartContract { - AccountStorage accountStorage = new(); - IStorageMap Accounts => accountStorage; - - public void TransferAll(UInt160 from, UInt160 to) - { - Accounts[to] = Accounts[from] + Accounts[to]; - Accounts[from] = 0; - } - - public void SetValue(UInt160 addr, BigInteger amount) - { - Accounts[addr] = amount; - } - - public BigInteger GetValue(UInt160 addr) - { - return Accounts[addr]; + AccountStorage accountStorage = new(); + IStorageMap Accounts => accountStorage; + + public void TransferAll(UInt160 from, UInt160 to) + { + Accounts[to] = Accounts[from] + Accounts[to]; + Accounts[from] = 0; + } + + public void SetValue(UInt160 addr, BigInteger amount) + { + Accounts[addr] = amount; + } + + public BigInteger GetValue(UInt160 addr) + { + return Accounts[addr]; } } } diff --git a/tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract_Partial.2.cs b/tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract_Partial.2.cs index ea73b5f6f..83d8b9089 100644 --- a/tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract_Partial.2.cs +++ b/tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract_Partial.2.cs @@ -1,6 +1,6 @@ namespace Neo.Compiler.CSharp.UnitTests.TestClasses { - public partial class Contract_Partial + public partial class Contract_Partial { public static int test2() { diff --git a/tests/Neo.SmartContract.Framework.UnitTests/Neo.SmartContract.Framework.UnitTests.csproj b/tests/Neo.SmartContract.Framework.UnitTests/Neo.SmartContract.Framework.UnitTests.csproj index f81087eaa..46a32d7fe 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/Neo.SmartContract.Framework.UnitTests.csproj +++ b/tests/Neo.SmartContract.Framework.UnitTests/Neo.SmartContract.Framework.UnitTests.csproj @@ -1,4 +1,4 @@ - + net6.0 diff --git a/tests/Neo.SmartContract.Framework.UnitTests/TestClasses/Contract_StdLib.cs b/tests/Neo.SmartContract.Framework.UnitTests/TestClasses/Contract_StdLib.cs index 273ac678a..abf7e98ba 100644 --- a/tests/Neo.SmartContract.Framework.UnitTests/TestClasses/Contract_StdLib.cs +++ b/tests/Neo.SmartContract.Framework.UnitTests/TestClasses/Contract_StdLib.cs @@ -47,13 +47,13 @@ public static string itoa(int value, int @base) public static int memoryCompare(ByteString str1, ByteString str2) { return StdLib.MemoryCompare(str1, str2); - } - + } + public static int memorySearch1(ByteString mem, ByteString value) { return StdLib.MemorySearch(mem, value); - } - + } + public static int memorySearch2(ByteString mem, ByteString value, int start) { return StdLib.MemorySearch(mem, value, start); @@ -62,13 +62,13 @@ public static int memorySearch2(ByteString mem, ByteString value, int start) public static int memorySearch3(ByteString mem, ByteString value, int start, bool backward) { return StdLib.MemorySearch(mem, value, start, backward); - } - + } + public static string[] stringSplit1(string str, string separator) { return StdLib.StringSplit(str, separator); - } - + } + public static string[] stringSplit2(string str, string separator, bool removeEmptyEntries) { return StdLib.StringSplit(str, separator, removeEmptyEntries); From 2ebe4f9477cfc3198e7f1bf15fb931a251b43bc1 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Thu, 25 Nov 2021 17:05:33 -0300 Subject: [PATCH 64/77] change nullable types --- src/Neo.TestEngine/Engine.cs | 8 ++++---- src/Neo.TestEngine/SmartContractTest.cs | 2 +- src/Neo.TestEngine/TestUtils/BuildScript.cs | 6 +++--- src/Neo.TestEngine/TestUtils/TestAccount.cs | 2 +- src/Neo.TestEngine/TestUtils/TestEngine.cs | 14 +++++++------- src/Neo.TestEngine/TestUtils/TestHashIndexState.cs | 4 ++-- 6 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index 90f589304..bd7b2923a 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -39,16 +39,16 @@ public static Engine Instance } } - private TestEngine? engine = null; + private TestEngine engine; private Transaction? currentTx = null; private ECPoint PubKey => wallet.DefaultAccount.GetKey().PublicKey; - private TestWallet? wallet = null; + private TestWallet wallet; private Engine() { var _ = TestBlockchain.TheNeoSystem; wallet = new TestWallet(); - Reset(); + engine = SetupNativeContracts(); } public uint Height => NativeContract.Ledger.CurrentIndex(engine.Snapshot); @@ -79,7 +79,7 @@ public Engine AddSmartContract(TestContract contract) return this; } - private object AddSmartContract(string path) + private object? AddSmartContract(string path) { engine.AddEntryScript(path); diff --git a/src/Neo.TestEngine/SmartContractTest.cs b/src/Neo.TestEngine/SmartContractTest.cs index 9a3cc9ea5..642f90012 100644 --- a/src/Neo.TestEngine/SmartContractTest.cs +++ b/src/Neo.TestEngine/SmartContractTest.cs @@ -26,7 +26,7 @@ public class SmartContractTest public uint currentHeight = 0; public Signer[] signers; public Block[] blocks; - public Transaction currentTx; + public Transaction? currentTx; public SmartContractTest(string path, string method, JArray parameters) : this(method, parameters) { diff --git a/src/Neo.TestEngine/TestUtils/BuildScript.cs b/src/Neo.TestEngine/TestUtils/BuildScript.cs index eaf89576b..cf2399f0a 100644 --- a/src/Neo.TestEngine/TestUtils/BuildScript.cs +++ b/src/Neo.TestEngine/TestUtils/BuildScript.cs @@ -21,11 +21,11 @@ public class BuildScript { public bool Success => !FromCompilation || (Context != null && Context.Success); - public UInt160 ScriptHash { get; private set; } + public UInt160? ScriptHash { get; private set; } public NefFile Nef { get; protected set; } public JObject Manifest { get; protected set; } - public JObject DebugInfo { get; protected set; } - public CompilationContext Context { get; protected set; } + public JObject? DebugInfo { get; protected set; } + public CompilationContext? Context { get; protected set; } private bool FromCompilation { get; set; } diff --git a/src/Neo.TestEngine/TestUtils/TestAccount.cs b/src/Neo.TestEngine/TestUtils/TestAccount.cs index 495d2d814..e577b20a3 100644 --- a/src/Neo.TestEngine/TestUtils/TestAccount.cs +++ b/src/Neo.TestEngine/TestUtils/TestAccount.cs @@ -30,7 +30,7 @@ public TestAccount(KeyPair privateKey) : base(Contract.CreateSignatureRedeemScri }; } - public override KeyPair GetKey() + public override KeyPair? GetKey() { return this.key; } diff --git a/src/Neo.TestEngine/TestUtils/TestEngine.cs b/src/Neo.TestEngine/TestUtils/TestEngine.cs index 9acc2ac74..356fa077a 100644 --- a/src/Neo.TestEngine/TestUtils/TestEngine.cs +++ b/src/Neo.TestEngine/TestUtils/TestEngine.cs @@ -36,15 +36,15 @@ public class TestEngine : ApplicationEngine private long previousGasConsumed = 0; public long GasConsumedByLastExecution => GasConsumed - previousGasConsumed; - public NefFile Nef { get; private set; } - public JObject Manifest { get; private set; } - public JObject DebugInfo { get; private set; } + public NefFile? Nef { get; private set; } + public JObject? Manifest { get; private set; } + public JObject? DebugInfo { get; private set; } - internal BuildScript ScriptContext { get; set; } + internal BuildScript? ScriptContext { get; set; } public void ClearNotifications() { - typeof(ApplicationEngine).GetField("notifications", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).SetValue(this, null); + typeof(ApplicationEngine).GetField("notifications", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)?.SetValue(this, null); } static TestEngine() @@ -79,7 +79,7 @@ public TestEngine(TriggerType trigger = TriggerType.Application, IVerifiable? ve { } - public CompilationContext AddEntryScript(params string[] files) + public CompilationContext? AddEntryScript(params string[] files) { ScriptContext = BuildScript.Build(references, files); SetContext(ScriptContext); @@ -87,7 +87,7 @@ public CompilationContext AddEntryScript(params string[] files) return ScriptContext.Context; } - public CompilationContext SetContext(BuildScript context) + public CompilationContext? SetContext(BuildScript context) { ScriptContext = context; diff --git a/src/Neo.TestEngine/TestUtils/TestHashIndexState.cs b/src/Neo.TestEngine/TestUtils/TestHashIndexState.cs index 3078015df..00a2fa87d 100644 --- a/src/Neo.TestEngine/TestUtils/TestHashIndexState.cs +++ b/src/Neo.TestEngine/TestUtils/TestHashIndexState.cs @@ -17,7 +17,7 @@ namespace Neo.TestingEngine { public class TestHashIndexState : IInteroperable { - public UInt256 Hash; + public UInt256? Hash; public uint Index; internal void FromStackItem(StackItem stackItem) @@ -32,7 +32,7 @@ void IInteroperable.FromStackItem(StackItem stackItem) this.FromStackItem(stackItem); } - internal StackItem ToStackItem(ReferenceCounter referenceCounter) + internal StackItem ToStackItem(ReferenceCounter? referenceCounter) { return new Struct(referenceCounter) { Hash.ToArray(), Index }; } From 475f1735db1ea11e593d569edcb1ba8ea7ad9d08 Mon Sep 17 00:00:00 2001 From: luc10921 Date: Mon, 22 Nov 2021 18:43:13 -0300 Subject: [PATCH 65/77] Make the TestEngine a global dotnet tool (similar to neoxp) --- src/Neo.TestEngine/Neo.TestEngine.csproj | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Neo.TestEngine/Neo.TestEngine.csproj b/src/Neo.TestEngine/Neo.TestEngine.csproj index 0e0257e40..b505f7eab 100644 --- a/src/Neo.TestEngine/Neo.TestEngine.csproj +++ b/src/Neo.TestEngine/Neo.TestEngine.csproj @@ -15,6 +15,8 @@ TestingEngine TestingEngine true + true + neotest From 46849a814c793820aba266cffab47d3eac1806cb Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Thu, 25 Nov 2021 17:23:30 -0300 Subject: [PATCH 66/77] run test engine unit tests --- .github/workflows/main.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 0cfcc2ef2..99ee4d75a 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -28,6 +28,8 @@ jobs: run: dotnet test tests/Neo.Compiler.CSharp.UnitTests /p:CollectCoverage=true /p:CoverletOutput=${GITHUB_WORKSPACE}/coverage/ - name: Test Neo.SmartContract.Framework.UnitTests run: dotnet test tests/Neo.SmartContract.Framework.UnitTests /p:CollectCoverage=true /p:CoverletOutput=${GITHUB_WORKSPACE}/coverage/lcov /p:MergeWith=${GITHUB_WORKSPACE}/coverage/coverage.json /p:Exclude=\"[Neo.Compiler.CSharp.UnitTests]*\" /p:CoverletOutputFormat=lcov + - name: Test Neo.TestEngine.UnitTests + run: dotnet test tests/Neo.TestEngine.UnitTests.UnitTests /p:CollectCoverage=true /p:CoverletOutput=${GITHUB_WORKSPACE}/coverage/lcov /p:MergeWith=${GITHUB_WORKSPACE}/coverage/coverage.json /p:Exclude=\"[Neo.Compiler.CSharp.UnitTests]*\" /p:CoverletOutputFormat=lcov - name: Coveralls uses: coverallsapp/github-action@master with: From 83c4f6ba901c9313a1ef93daf4e2ee1fc24d8253 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Thu, 25 Nov 2021 17:26:45 -0300 Subject: [PATCH 67/77] wrong path --- .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 99ee4d75a..b516f09b8 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -29,7 +29,7 @@ jobs: - name: Test Neo.SmartContract.Framework.UnitTests run: dotnet test tests/Neo.SmartContract.Framework.UnitTests /p:CollectCoverage=true /p:CoverletOutput=${GITHUB_WORKSPACE}/coverage/lcov /p:MergeWith=${GITHUB_WORKSPACE}/coverage/coverage.json /p:Exclude=\"[Neo.Compiler.CSharp.UnitTests]*\" /p:CoverletOutputFormat=lcov - name: Test Neo.TestEngine.UnitTests - run: dotnet test tests/Neo.TestEngine.UnitTests.UnitTests /p:CollectCoverage=true /p:CoverletOutput=${GITHUB_WORKSPACE}/coverage/lcov /p:MergeWith=${GITHUB_WORKSPACE}/coverage/coverage.json /p:Exclude=\"[Neo.Compiler.CSharp.UnitTests]*\" /p:CoverletOutputFormat=lcov + run: dotnet test tests/Neo.TestEngine.UnitTests /p:CollectCoverage=true /p:CoverletOutput=${GITHUB_WORKSPACE}/coverage/lcov /p:MergeWith=${GITHUB_WORKSPACE}/coverage/coverage.json /p:Exclude=\"[Neo.Compiler.CSharp.UnitTests]*\" /p:CoverletOutputFormat=lcov - name: Coveralls uses: coverallsapp/github-action@master with: From 4bfdd8901e345f4bdba6128b786c85bd8ce933bd Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Wed, 6 Jul 2022 17:28:51 -0300 Subject: [PATCH 68/77] enhance transaction operations --- src/Neo.TestEngine/Engine.cs | 22 +++++++++- src/Neo.TestEngine/Helper.cs | 9 ++-- src/Neo.TestEngine/Program.cs | 43 ++++++++++++++++--- src/Neo.TestEngine/SmartContractTest.cs | 4 +- src/Neo.TestEngine/TestBlock.cs | 27 ++++++++++++ .../TestUtils/TestBlockchain.cs | 18 ++++++++ 6 files changed, 111 insertions(+), 12 deletions(-) create mode 100644 src/Neo.TestEngine/TestBlock.cs diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index 54f854f99..1a0f56902 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -217,6 +217,17 @@ internal void SetTxAttributes(TransactionAttribute[] attributes) currentTx.Attributes = attributes.Where(attr => attr != null).ToArray(); } + public Engine AddBlock(TestBlock block) + { + var snapshot = engine.Snapshot; + var result = AddBlock(block.Block); + foreach (var txState in block.Transactions) + { + snapshot.AddOrUpdateTransactionState(txState.Transaction, txState.State); + } + return result; + } + public Engine AddBlock(Block block) { var snapshot = engine.Snapshot; @@ -320,6 +331,7 @@ public JObject Run(string method, ContractParameter[] args) currentTx.ValidUntilBlock = engine.Snapshot.GetLastBlock().Index + ProtocolSettings.Default.MaxValidUntilBlockIncrement; currentTx.SystemFee = engine.GasConsumed; currentTx.NetworkFee = wallet.CalculateNetworkFee(engine.Snapshot, currentTx); + engine.Snapshot.AddOrUpdateTransactionState(currentTx, engine.State); return engine.ToJson(); } @@ -330,7 +342,15 @@ private TestEngine SetupNativeContracts() { Attributes = new TransactionAttribute[0], Script = new byte[0], - Signers = new Signer[] { new Signer() { Account = wallet.DefaultAccount.ScriptHash, Scopes = WitnessScope.CalledByEntry } }, + Signers = new Signer[] { + new Signer() { + Account = wallet.DefaultAccount.ScriptHash, + Scopes = WitnessScope.CalledByEntry, + AllowedContracts = new UInt160[] { }, + AllowedGroups = new ECPoint[] { }, + Rules = new WitnessRule[] { } + } + }, Witnesses = new Witness[0], NetworkFee = 1, Nonce = 2, diff --git a/src/Neo.TestEngine/Helper.cs b/src/Neo.TestEngine/Helper.cs index f8e19f1fe..f79997cf5 100644 --- a/src/Neo.TestEngine/Helper.cs +++ b/src/Neo.TestEngine/Helper.cs @@ -35,7 +35,7 @@ public static JObject ToJson(this TestEngine testEngine) json["currentblock"] = testEngine.PersistingBlock.ToSimpleJson(); if (testEngine.ScriptContainer is Transaction tx) { - json["transaction"] = tx.ToSimpleJson(); + json["transaction"] = tx.ToSimpleJson(testEngine.State); } json["storage"] = testEngine.Snapshot.ToJson(); @@ -128,7 +128,7 @@ public static JObject ToSimpleJson(this Block block) return json; } - public static JObject ToSimpleJson(this Transaction tx) + public static JObject ToSimpleJson(this Transaction tx, VMState txState = VMState.NONE) { // build a tx with the mutable fields to have a consistent hash between program input and output var simpleTx = new Transaction() @@ -140,7 +140,10 @@ public static JObject ToSimpleJson(this Transaction tx) ValidUntilBlock = tx.ValidUntilBlock }; - return simpleTx.ToJson(ProtocolSettings.Default); + var json = simpleTx.ToJson(ProtocolSettings.Default); + json["state"] = txState.ToString(); + + return json; } private static string GetExceptionMessage(Exception exception) diff --git a/src/Neo.TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs index bb4978be3..1fd2cbf05 100644 --- a/src/Neo.TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -11,6 +11,7 @@ using Neo.IO.Json; using Neo.Network.P2P.Payloads; using Neo.SmartContract; +using Neo.SmartContract.Native; using Neo.VM; using Neo.VM.Types; using System; @@ -235,7 +236,10 @@ public static JObject RunWithJson(JObject json) return new Signer() { Account = newAccount, - Scopes = scopes + Scopes = scopes, + AllowedContracts = new UInt160[] { }, + AllowedGroups = new Cryptography.ECC.ECPoint[] { }, + Rules = new WitnessRule[] { } }; }).ToArray(); } @@ -266,7 +270,7 @@ public static JObject Run(SmartContractTest smartContractTest) Engine.Instance.AddSmartContract(contract); } - foreach (var block in smartContractTest.blocks.OrderBy(b => b.Index)) + foreach (var block in smartContractTest.blocks.OrderBy(b => b.Block.Index)) { Engine.Instance.AddBlock(block); } @@ -425,7 +429,7 @@ private static ContractParameter[] GetStackItemParameters(JArray parameters) return items.ToArray(); } - private static Block BlockFromJson(JObject blockJson) + private static TestBlock BlockFromJson(JObject blockJson) { var transactions = blockJson["transactions"] as JArray; @@ -438,15 +442,18 @@ private static Block BlockFromJson(JObject blockJson) throw new FormatException(GetInvalidTypeMessage("ulong", "blockTimestamp")); } - return new Block() + var txStates = transactions.Select(tx => TxStateFromJson(tx)).ToArray(); + var block = new Block() { Header = new Header() { Index = blockIndex, Timestamp = blockTimestamp }, - Transactions = transactions.Select(b => TxFromJson(b)).ToArray() + Transactions = txStates.Select(tx => tx.Transaction).ToArray() }; + + return new TestBlock(block, txStates); } private static Transaction TxFromJson(JObject txJson) @@ -467,7 +474,10 @@ private static Transaction TxFromJson(JObject txJson) return new Signer() { Account = signerAccount, - Scopes = WitnessScope.CalledByEntry + Scopes = WitnessScope.CalledByEntry, + AllowedContracts = new UInt160[] { }, + AllowedGroups = new Cryptography.ECC.ECPoint[] { }, + Rules = new WitnessRule[] { } }; }).ToArray(); } @@ -524,6 +534,27 @@ private static Transaction TxFromJson(JObject txJson) }; } + private static TransactionState TxStateFromJson(JObject txJson) + { + Transaction tx = TxFromJson(txJson); + + VMState state; + if (!txJson.ContainsProperty("state")) + { + state = VMState.NONE; + } + else if (!Enum.TryParse(txJson["state"].AsString(), out state)) + { + throw new FormatException(GetInvalidTypeMessage("VMState", "transactionState")); + } + + return new TransactionState() + { + Transaction = tx, + State = state + }; + } + private static TransactionAttribute? TxAttributeFromJson(JObject txAttributeJson) { if (!txAttributeJson.ContainsProperty("type")) diff --git a/src/Neo.TestEngine/SmartContractTest.cs b/src/Neo.TestEngine/SmartContractTest.cs index cf58d42c5..db74ba3de 100644 --- a/src/Neo.TestEngine/SmartContractTest.cs +++ b/src/Neo.TestEngine/SmartContractTest.cs @@ -25,7 +25,7 @@ public class SmartContractTest public List contracts; public uint currentHeight = 0; public Signer[] signers; - public Block[] blocks; + public TestBlock[] blocks; public Transaction? currentTx; public SmartContractTest(string path, string method, JArray parameters) : this(method, parameters) @@ -45,7 +45,7 @@ private SmartContractTest(string method, JArray parameters) storage = new Dictionary(); contracts = new List(); signers = new Signer[] { }; - blocks = new Block[] { }; + blocks = new TestBlock[] { }; } } } diff --git a/src/Neo.TestEngine/TestBlock.cs b/src/Neo.TestEngine/TestBlock.cs new file mode 100644 index 000000000..dd5860471 --- /dev/null +++ b/src/Neo.TestEngine/TestBlock.cs @@ -0,0 +1,27 @@ +// Copyright (C) 2015-2022 The Neo Project. +// +// The Neo.Compiler.CSharp is free software distributed under the 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.SmartContract.Native; + +namespace Neo.TestingEngine +{ + public class TestBlock + { + internal Block Block { get; } + internal TransactionState[] Transactions { get; } + + public TestBlock(Block block, TransactionState[] txs) + { + Block = block; + Transactions = txs; + } + } +} diff --git a/src/Neo.TestEngine/TestUtils/TestBlockchain.cs b/src/Neo.TestEngine/TestUtils/TestBlockchain.cs index d7ba3d061..17c80f758 100644 --- a/src/Neo.TestEngine/TestUtils/TestBlockchain.cs +++ b/src/Neo.TestEngine/TestUtils/TestBlockchain.cs @@ -252,5 +252,23 @@ public static void AddOrUpdateTransactions(this DataCache snapshot, Transaction[ snapshot.TransactionAddOrUpdate(states.ToArray()); snapshot.InnerCommit(); } + + public static void AddOrUpdateTransactionState(this DataCache snapshot, Transaction tx, VMState state, int blockIndex = -1) + { + uint index = blockIndex >= 0 ? (uint)blockIndex : NativeContract.Ledger.CurrentIndex(snapshot); + var transaction = tx; + if (snapshot.ContainsTransaction(tx)) + { + transaction = NativeContract.Ledger.GetTransaction(snapshot, tx.Hash); + } + + var txState = new TransactionState() + { + BlockIndex = index, + State = state, + Transaction = tx + }; + snapshot.TransactionAddOrUpdate(new TransactionState[] { txState }); + } } } From 7445246ad5fa806929a136db9d8ae4e6c38a8c1d Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Thu, 4 Aug 2022 15:44:10 -0300 Subject: [PATCH 69/77] Support to set the calling script hash --- src/Neo.TestEngine/Engine.cs | 6 ++++++ src/Neo.TestEngine/Helper.cs | 1 + src/Neo.TestEngine/Program.cs | 17 +++++++++++++++++ src/Neo.TestEngine/SmartContractTest.cs | 1 + src/Neo.TestEngine/TestUtils/TestEngine.cs | 10 +++++++++- 5 files changed, 34 insertions(+), 1 deletion(-) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index 1a0f56902..4c51561f5 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -72,6 +72,12 @@ public Engine SetEntryScript(UInt160 contractHash) return this; } + public Engine SetCallingScript(UInt160 contractHash) + { + engine.callingScriptHash = contractHash; + return this; + } + public Engine AddSmartContract(TestContract contract) { var state = AddSmartContract(contract.nefPath); diff --git a/src/Neo.TestEngine/Helper.cs b/src/Neo.TestEngine/Helper.cs index f79997cf5..8353b22b7 100644 --- a/src/Neo.TestEngine/Helper.cs +++ b/src/Neo.TestEngine/Helper.cs @@ -31,6 +31,7 @@ public static JObject ToJson(this TestEngine testEngine) json["gasconsumed"] = (new BigDecimal((decimal)testEngine.GasConsumedByLastExecution, NativeContract.GAS.Decimals)).ToString(); json["resultstack"] = testEngine.ResultStack.ToJson(); json["executedscripthash"] = testEngine.executedScriptHash.ToString(); + json["callingscripthash"] = testEngine.callingScriptHash?.ToString(); json["currentblock"] = testEngine.PersistingBlock.ToSimpleJson(); if (testEngine.ScriptContainer is Transaction tx) diff --git a/src/Neo.TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs index 1fd2cbf05..c21772c7d 100644 --- a/src/Neo.TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -243,6 +243,18 @@ public static JObject RunWithJson(JObject json) }; }).ToArray(); } + + // calling script hash + if (json.ContainsProperty("callingscripthash")) + { + UInt160? callingScriptHash = null; + if (json["callingscripthash"] != null && !UInt160.TryParse(json["callingscripthash"].AsString(), out callingScriptHash)) + { + throw new FormatException(GetInvalidTypeMessage("UInt160", "callingscripthash")); + } + + smartContractTestCase.callingScriptHash = callingScriptHash; + } return Run(smartContractTestCase); } catch (Exception e) @@ -293,6 +305,11 @@ public static JObject Run(SmartContractTest smartContractTest) Engine.Instance.SetEntryScript(smartContractTest.scriptHash); } + if (smartContractTest.callingScriptHash != null) + { + Engine.Instance.SetCallingScript(smartContractTest.callingScriptHash); + } + var stackParams = GetStackItemParameters(smartContractTest.methodParameters); return Engine.Instance.Run(smartContractTest.methodName, stackParams); } diff --git a/src/Neo.TestEngine/SmartContractTest.cs b/src/Neo.TestEngine/SmartContractTest.cs index db74ba3de..ec346af3e 100644 --- a/src/Neo.TestEngine/SmartContractTest.cs +++ b/src/Neo.TestEngine/SmartContractTest.cs @@ -25,6 +25,7 @@ public class SmartContractTest public List contracts; public uint currentHeight = 0; public Signer[] signers; + public UInt160? callingScriptHash = null; public TestBlock[] blocks; public Transaction? currentTx; diff --git a/src/Neo.TestEngine/TestUtils/TestEngine.cs b/src/Neo.TestEngine/TestUtils/TestEngine.cs index b81bd5b0c..36cbb64b1 100644 --- a/src/Neo.TestEngine/TestUtils/TestEngine.cs +++ b/src/Neo.TestEngine/TestUtils/TestEngine.cs @@ -35,6 +35,7 @@ public class TestEngine : ApplicationEngine private long previousGasConsumed = 0; internal UInt160 executedScriptHash { get; private set; } + internal UInt160 callingScriptHash { get; set; } public long GasConsumedByLastExecution => GasConsumed - previousGasConsumed; public NefFile? Nef { get; private set; } @@ -154,6 +155,12 @@ public bool AddEntryScript(BuildScript script) return true; } + public bool SetCallingScript(UInt160 contractHash) + { + callingScriptHash = CallingScriptHash; + return true; + } + public void RunNativeContract(byte[] script, string method, StackItem[] parameters, CallFlags flags = CallFlags.All) { var rvcount = GetMethodReturnCount(method); @@ -245,7 +252,8 @@ public EvaluationStack ExecuteTestCaseStandard(int offset, ushort rvcount, NefFi // Mock contract var contextState = CurrentContext.GetState(); contextState.Contract ??= new ContractState() { Nef = contract }; - contextState.ScriptHash = ScriptContext.ScriptHash; + contextState.ScriptHash = ScriptContext?.ScriptHash; + contextState.CallingScriptHash = callingScriptHash; for (var i = args.Length - 1; i >= 0; i--) this.Push(args[i]); var initializeOffset = GetMethodEntryOffset("_initialize"); From cd39ea96abd9e732b3f29a2192de7d7ee0e35c7a Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Fri, 30 Sep 2022 15:59:51 -0300 Subject: [PATCH 70/77] Manifest access raising null pointer exception --- src/Neo.TestEngine/TestUtils/TestEngine.cs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/Neo.TestEngine/TestUtils/TestEngine.cs b/src/Neo.TestEngine/TestUtils/TestEngine.cs index ecf1c86a5..472358e15 100644 --- a/src/Neo.TestEngine/TestUtils/TestEngine.cs +++ b/src/Neo.TestEngine/TestUtils/TestEngine.cs @@ -15,6 +15,7 @@ using Neo.Network.P2P.Payloads; using Neo.Persistence; using Neo.SmartContract; +using Neo.SmartContract.Manifest; using Neo.SmartContract.Native; using Neo.VM; using Neo.VM.Types; @@ -171,7 +172,7 @@ public void RunNativeContract(byte[] script, string method, StackItem[] paramete LoadContext(context); var mockedNef = new TestNefFile(script); - ExecuteTestCaseStandard(0, (ushort)rvcount, mockedNef, new StackItem[0]); + ExecuteTestCaseStandard(0, (ushort)rvcount, mockedNef, new ContractManifest(), new StackItem[0]); } public void Reset() @@ -225,24 +226,29 @@ private int GetMethodReturnCount(string methodname) public EvaluationStack ExecuteTestCaseStandard(string methodname, params StackItem[] args) { - return ExecuteTestCaseStandard(methodname, Nef, args); + return ExecuteTestCaseStandard(methodname, Nef, ContractManifest.FromJson(Manifest), args); } public EvaluationStack ExecuteTestCaseStandard(string methodname, NefFile contract, params StackItem[] args) + { + return ExecuteTestCaseStandard(methodname, contract, ContractManifest.FromJson(Manifest), args); + } + + public EvaluationStack ExecuteTestCaseStandard(string methodname, NefFile contract, ContractManifest manifest, params StackItem[] args) { var offset = GetMethodEntryOffset(methodname); if (offset == -1) throw new Exception("Can't find method : " + methodname); var rvcount = GetMethodReturnCount(methodname); if (rvcount == -1) throw new Exception("Can't find method return count : " + methodname); - return ExecuteTestCaseStandard(offset, (ushort)rvcount, contract, args); + return ExecuteTestCaseStandard(offset, (ushort)rvcount, contract, manifest, args); } public EvaluationStack ExecuteTestCaseStandard(int offset, ushort rvcount, params StackItem[] args) { - return ExecuteTestCaseStandard(offset, rvcount, Nef, args); + return ExecuteTestCaseStandard(offset, rvcount, Nef, ContractManifest.FromJson(Manifest), args); } - public EvaluationStack ExecuteTestCaseStandard(int offset, ushort rvcount, NefFile contract, params StackItem[] args) + public EvaluationStack ExecuteTestCaseStandard(int offset, ushort rvcount, NefFile contract, ContractManifest manifest, params StackItem[] args) { executedScriptHash = EntryScriptHash; previousGasConsumed = GasConsumed; @@ -263,7 +269,7 @@ public EvaluationStack ExecuteTestCaseStandard(int offset, ushort rvcount, NefFi // Mock contract var contextState = CurrentContext.GetState(); - contextState.Contract ??= new ContractState() { Nef = contract }; + contextState.Contract ??= new ContractState() { Nef = contract, Manifest = manifest }; contextState.ScriptHash = ScriptContext?.ScriptHash; contextState.CallingContext = callingContext; From 92b9e1ddb2fd0fcafa50f151c09b12a86412ea5b Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Fri, 30 Sep 2022 17:51:40 -0300 Subject: [PATCH 71/77] Block hashes on input --- src/Neo.TestEngine/Program.cs | 15 +++++++++++---- src/Neo.TestEngine/TestBlock.cs | 4 +++- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/Neo.TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs index 38c23a702..16d2055cc 100644 --- a/src/Neo.TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -449,17 +449,24 @@ private static ContractParameter[] GetStackItemParameters(JArray parameters) private static TestBlock BlockFromJson(JToken blockJson) { - var transactions = blockJson["transactions"] as JArray; + JObject blockJsonObject = (JObject)blockJson; + var transactions = blockJsonObject["transactions"] as JArray; - if (!uint.TryParse(blockJson["index"].AsString(), out var blockIndex)) + if (!uint.TryParse(blockJsonObject["index"].AsString(), out var blockIndex)) { throw new FormatException(GetInvalidTypeMessage("uint", "blockIndex")); } - if (!ulong.TryParse(blockJson["timestamp"].AsString(), out var blockTimestamp)) + if (!ulong.TryParse(blockJsonObject["timestamp"].AsString(), out var blockTimestamp)) { throw new FormatException(GetInvalidTypeMessage("ulong", "blockTimestamp")); } + UInt256? blockHash; + if (!blockJsonObject.ContainsProperty("hash") || !UInt256.TryParse(blockJsonObject["hash"].AsString(), out blockHash)) + { + blockHash = null; + } + var txStates = transactions.Select(tx => TxStateFromJson(tx)).ToArray(); var block = new Block() { @@ -471,7 +478,7 @@ private static TestBlock BlockFromJson(JToken blockJson) Transactions = txStates.Select(tx => tx.Transaction).ToArray() }; - return new TestBlock(block, txStates); + return new TestBlock(block, txStates, blockHash); } private static Transaction TxFromJson(JToken txJson) diff --git a/src/Neo.TestEngine/TestBlock.cs b/src/Neo.TestEngine/TestBlock.cs index dd5860471..88f946e7a 100644 --- a/src/Neo.TestEngine/TestBlock.cs +++ b/src/Neo.TestEngine/TestBlock.cs @@ -16,11 +16,13 @@ namespace Neo.TestingEngine public class TestBlock { internal Block Block { get; } + internal UInt256? Hash { get; } internal TransactionState[] Transactions { get; } - public TestBlock(Block block, TransactionState[] txs) + public TestBlock(Block block, TransactionState[] txs, UInt256? blockHash = null) { Block = block; + Hash = blockHash; Transactions = txs; } } From 2e330a1e3590dd97ed04c4912f0c1c2e1182c566 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 7 Nov 2022 19:07:31 -0300 Subject: [PATCH 72/77] Script hash mocking --- src/Neo.TestEngine/Engine.cs | 2 +- src/Neo.TestEngine/TestUtils/BuildScript.cs | 4 +++- src/Neo.TestEngine/TestUtils/Helper.cs | 18 ++++++++++++++++++ src/Neo.TestEngine/TestUtils/TestEngine.cs | 8 ++++++-- 4 files changed, 28 insertions(+), 4 deletions(-) create mode 100644 src/Neo.TestEngine/TestUtils/Helper.cs diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index fae97e0e3..8b0d7abb7 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -91,7 +91,7 @@ public Engine AddSmartContract(TestContract contract) if (engine.ScriptContext?.Success == true) { - var hash = engine.Nef.Script.Span.ToScriptHash(); + var hash = TestHelper.GetContractHash(engine.Nef.CheckSum, ContractManifest.FromJson(engine.Manifest).Name); var snapshot = engine.Snapshot; ContractState state; diff --git a/src/Neo.TestEngine/TestUtils/BuildScript.cs b/src/Neo.TestEngine/TestUtils/BuildScript.cs index 00b4e49d9..45c234c6e 100644 --- a/src/Neo.TestEngine/TestUtils/BuildScript.cs +++ b/src/Neo.TestEngine/TestUtils/BuildScript.cs @@ -13,6 +13,7 @@ using Neo.IO; using Neo.Json; using Neo.SmartContract; +using Neo.SmartContract.Manifest; using System.Collections.Generic; using System.IO; @@ -37,7 +38,8 @@ public BuildScript(NefFile nefFile, JObject manifestJson, UInt160? originHash = if (originHash is null && nefFile != null) { - originHash = Nef.Script.Span.ToScriptHash(); + ContractManifest parsedManifest = ContractManifest.FromJson(manifestJson); + originHash = TestHelper.GetContractHash(nefFile.CheckSum, parsedManifest.Name); } ScriptHash = originHash; } diff --git a/src/Neo.TestEngine/TestUtils/Helper.cs b/src/Neo.TestEngine/TestUtils/Helper.cs new file mode 100644 index 000000000..8e0892d2f --- /dev/null +++ b/src/Neo.TestEngine/TestUtils/Helper.cs @@ -0,0 +1,18 @@ +using Neo.VM; +using Neo.SmartContract; + +namespace Neo.TestingEngine +{ + internal class TestHelper + { + public static UInt160 GetContractHash(uint nefCheckSum, string name) + { + using var sb = new ScriptBuilder(); + sb.Emit(OpCode.ABORT); + sb.EmitPush(nefCheckSum); + sb.EmitPush(name); + + return sb.ToArray().ToScriptHash(); + } + } +} diff --git a/src/Neo.TestEngine/TestUtils/TestEngine.cs b/src/Neo.TestEngine/TestUtils/TestEngine.cs index 472358e15..69544be2a 100644 --- a/src/Neo.TestEngine/TestUtils/TestEngine.cs +++ b/src/Neo.TestEngine/TestUtils/TestEngine.cs @@ -137,7 +137,7 @@ public bool AddEntryScript(UInt160 contractHash) public bool AddEntryScript(BuildScript script) { - var contractHash = script.Nef.Script.Span.ToScriptHash(); + var contractHash = TestHelper.GetContractHash(script.Nef.CheckSum, ContractManifest.FromJson(script.Manifest).Name); var contract = NativeContract.ContractManagement.GetContract(Snapshot, contractHash); if (contract != null) @@ -188,7 +188,11 @@ public void Reset() this.LoadScript(Nef.Script); // Mock contract var contextState = CurrentContext.GetState(); - contextState.Contract ??= new ContractState { Nef = Nef }; + var contractManifest = ContractManifest.FromJson(Manifest); + var contractHash = TestHelper.GetContractHash(Nef.CheckSum, contractManifest.Name); + + contextState.Contract ??= new ContractState { Nef = Nef, Manifest = contractManifest, Hash = contractHash }; + contextState.ScriptHash = contractHash; } } From c2ef0aeab96fcaef6c687f9bedb082198ef08fb5 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Fri, 9 Dec 2022 17:40:46 -0300 Subject: [PATCH 73/77] fix signers witness scope --- src/Neo.TestEngine/Engine.cs | 2 +- src/Neo.TestEngine/Program.cs | 73 +++++++++------------- src/Neo.TestEngine/TestUtils/TestEngine.cs | 9 ++- 3 files changed, 37 insertions(+), 47 deletions(-) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index 8b0d7abb7..e288031b0 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -213,7 +213,7 @@ public Engine SetSigners(Signer[] signers) newSigners.Add(signer); wallet.AddSignerAccount(signer.Account); } - currentTx.Signers = newSigners.Concat(currentTx.Signers).ToArray(); + currentTx.Signers = newSigners.ToArray(); } return this; } diff --git a/src/Neo.TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs index 16d2055cc..1a5d01102 100644 --- a/src/Neo.TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -216,33 +216,7 @@ public static JObject RunWithJson(JObject json) // tx signers if (json.ContainsProperty("signeraccounts") && json["signeraccounts"] is JArray accounts) { - smartContractTestCase.signers = accounts.Select(account => - { - JObject accountJson = (JObject)account; - if (!UInt160.TryParse(accountJson["account"].AsString(), out var newAccount)) - { - throw new FormatException(GetInvalidTypeMessage("UInt160", "signerAccount")); - } - - WitnessScope scopes; - if (!accountJson.ContainsProperty("scopes")) - { - scopes = WitnessScope.CalledByEntry; - } - else if (!Enum.TryParse(accountJson["scopes"].AsString(), out scopes)) - { - throw new FormatException(GetInvalidTypeMessage("WitnessScope", "signerScope")); - } - - return new Signer() - { - Account = newAccount, - Scopes = scopes, - AllowedContracts = new UInt160[] { }, - AllowedGroups = new Cryptography.ECC.ECPoint[] { }, - Rules = new WitnessRule[] { } - }; - }).ToArray(); + smartContractTestCase.signers = accounts.Select(account => SignerFromJson(account)).ToArray(); } // calling script hash @@ -481,6 +455,34 @@ private static TestBlock BlockFromJson(JToken blockJson) return new TestBlock(block, txStates, blockHash); } + private static Signer SignerFromJson(JToken signerJson) + { + JObject accountJson = (JObject)signerJson; + if (!UInt160.TryParse(accountJson["account"].AsString(), out var signerAccount)) + { + throw new FormatException(GetInvalidTypeMessage("UInt160", "signerAccount")); + } + + WitnessScope scopes; + if (!accountJson.ContainsProperty("scopes")) + { + scopes = WitnessScope.CalledByEntry; + } + else if (!Enum.TryParse(accountJson["scopes"].AsString(), out scopes)) + { + throw new FormatException(GetInvalidTypeMessage("WitnessScope", "signerScope")); + } + + return new Signer() + { + Account = signerAccount, + Scopes = scopes, + AllowedContracts = new UInt160[] { }, + AllowedGroups = new Cryptography.ECC.ECPoint[] { }, + Rules = new WitnessRule[] { } + }; + } + private static Transaction TxFromJson(JToken txJson) { JObject txJsonObject = (JObject)txJson; @@ -490,22 +492,7 @@ private static Transaction TxFromJson(JToken txJson) if (txJsonObject.ContainsProperty("signers") && txJsonObject["signers"] is JArray signersJson) { - accounts = signersJson.Select(p => - { - if (!UInt160.TryParse(p["account"].AsString(), out var signerAccount)) - { - throw new FormatException(GetInvalidTypeMessage("UInt160", "signerAccount")); - } - - return new Signer() - { - Account = signerAccount, - Scopes = WitnessScope.CalledByEntry, - AllowedContracts = new UInt160[] { }, - AllowedGroups = new Cryptography.ECC.ECPoint[] { }, - Rules = new WitnessRule[] { } - }; - }).ToArray(); + accounts = signersJson.Select(p => SignerFromJson(p)).ToArray(); } else { diff --git a/src/Neo.TestEngine/TestUtils/TestEngine.cs b/src/Neo.TestEngine/TestUtils/TestEngine.cs index 69544be2a..ee9e45d6f 100644 --- a/src/Neo.TestEngine/TestUtils/TestEngine.cs +++ b/src/Neo.TestEngine/TestUtils/TestEngine.cs @@ -257,16 +257,19 @@ public EvaluationStack ExecuteTestCaseStandard(int offset, ushort rvcount, NefFi executedScriptHash = EntryScriptHash; previousGasConsumed = GasConsumed; var context = InvocationStack.Pop(); - ExecutionContext? callingContext = null; + ExecutionContext? callingContext = context; + var callingState = context.GetState(); // Mock Calling Script Hash if (callingScriptHash is not null) { - callingContext = context; - var callingState = context.GetState(); callingState.Contract ??= new ContractState() { Hash = callingScriptHash }; callingState.ScriptHash = callingScriptHash; } + else if (ScriptContainer is Transaction currentTx) // Mock Signer Script Hash + { + callingState.ScriptHash = currentTx.Signers[0].Account; + } context = CreateContext(context.Script, rvcount, offset); LoadContext(context); From 6768e3424bcd8a1eae10b9f112fc262ce0f9d348 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Fri, 9 Dec 2022 19:46:13 -0300 Subject: [PATCH 74/77] fix signer nullable variables causing unexpected errors --- src/Neo.TestEngine/Program.cs | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/src/Neo.TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs index 1a5d01102..7ae8d8e40 100644 --- a/src/Neo.TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -463,23 +463,19 @@ private static Signer SignerFromJson(JToken signerJson) throw new FormatException(GetInvalidTypeMessage("UInt160", "signerAccount")); } - WitnessScope scopes; if (!accountJson.ContainsProperty("scopes")) { - scopes = WitnessScope.CalledByEntry; - } - else if (!Enum.TryParse(accountJson["scopes"].AsString(), out scopes)) - { - throw new FormatException(GetInvalidTypeMessage("WitnessScope", "signerScope")); + accountJson["scopes"] = WitnessScope.CalledByEntry.ToString(); } + var parsedSigner = Signer.FromJson(accountJson); return new Signer() { - Account = signerAccount, - Scopes = scopes, - AllowedContracts = new UInt160[] { }, - AllowedGroups = new Cryptography.ECC.ECPoint[] { }, - Rules = new WitnessRule[] { } + Account = parsedSigner.Account, + Scopes = parsedSigner.Scopes, + AllowedContracts = parsedSigner.AllowedContracts ?? new UInt160[0], + AllowedGroups = parsedSigner.AllowedGroups ?? new Cryptography.ECC.ECPoint[0], + Rules = parsedSigner.Rules ?? new WitnessRule[0] }; } From f0296dfe03ff67f2bb03ca84caf817255c7465f0 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 12 Dec 2022 14:19:36 -0300 Subject: [PATCH 75/77] fix invalid reference counter on arguments --- src/Neo.TestEngine/Engine.cs | 2 +- .../Extensions/TestExtensions.cs | 39 ++++++++++++++++++- .../TestClasses/Contract_ContractCall.cs | 2 +- 3 files changed, 39 insertions(+), 4 deletions(-) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index e288031b0..897650e96 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -313,7 +313,7 @@ public JObject Run(string method, ContractParameter[] args) snapshot.SetCurrentBlockHash(lastBlock.Index, lastBlock.Hash); } - var stackItemsArgs = args.Select(a => a.ToStackItem()).ToArray(); + var stackItemsArgs = args.Select(a => a.ToStackItem(engine.ReferenceCounter)).ToArray(); if (engine.ScriptContext is BuildNative native) { byte[] script; diff --git a/src/Neo.TestEngine/Extensions/TestExtensions.cs b/src/Neo.TestEngine/Extensions/TestExtensions.cs index a4beaa01c..aaee1cf98 100644 --- a/src/Neo.TestEngine/Extensions/TestExtensions.cs +++ b/src/Neo.TestEngine/Extensions/TestExtensions.cs @@ -13,8 +13,11 @@ using Neo.Persistence; using Neo.SmartContract; using Neo.SmartContract.Native; +using Neo.VM; +using Neo.VM.Types; using System; using System.Linq; +using Array = Neo.VM.Types.Array; namespace Neo.TestingEngine { @@ -22,6 +25,38 @@ public static class TestExtensions { private const byte Prefix_NextAvailableId = 15; + public static StackItem ToStackItem(this ContractParameter parameter, ReferenceCounter referenceCounter) + { + var stackItem = parameter.ToStackItem(); + return SetReferenceCounter(stackItem, referenceCounter); + } + + private static StackItem SetReferenceCounter(StackItem stackItem, ReferenceCounter referenceCounter) + { + if (stackItem is CompoundType) + { + if (stackItem is Map map) + { + var newStackItem = new Map(referenceCounter); + foreach (var (key, value) in map) + { + newStackItem[key] = value; + } + stackItem = newStackItem; + } + else if (stackItem is Array array) + { + stackItem = new Array(referenceCounter, array.SubItems); + } + else if (stackItem is Struct stackStruct) + { + stackItem = new Struct(referenceCounter, stackStruct); + } + } + + return stackItem; + } + public static void ContractAdd(this DataCache snapshot, ContractState contract) { var key = new KeyBuilder(-1, 8).Add(contract.Hash); @@ -51,13 +86,13 @@ public static void DeployNativeContracts(this DataCache snapshot, Block? persist var method = typeof(ContractManagement).GetMethod("OnPersist", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); var engine = new TestEngine(TriggerType.OnPersist, null, snapshot, persistingBlock); - engine.LoadScript(Array.Empty()); + engine.LoadScript(System.Array.Empty()); method.Invoke(NativeContract.ContractManagement, new object[] { engine }); engine.Snapshot.InnerCommit(); var method2 = typeof(LedgerContract).GetMethod("PostPersist", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); engine = new TestEngine(TriggerType.OnPersist, null, snapshot, persistingBlock); - engine.LoadScript(Array.Empty()); + engine.LoadScript(System.Array.Empty()); method2.Invoke(NativeContract.Ledger, new object[] { engine }); engine.Snapshot.InnerCommit(); } diff --git a/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_ContractCall.cs b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_ContractCall.cs index a93d8f37e..3ef0b44fb 100644 --- a/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_ContractCall.cs +++ b/tests/Neo.TestEngine.UnitTests/TestClasses/Contract_ContractCall.cs @@ -3,7 +3,7 @@ namespace Neo.TestEngine.UnitTests.TestClasses { - [Contract("0x4281dd379f0831b4131f9bc3433299e4fda02e68")] + [Contract("0xfaf5e0e43f3fdeb58cdae3c1630a1db650b05403")] public class Contract1 { public static extern byte[] testArgs1(byte a); From 9421daf373b6e598b541b4aaae5dcb771aff9c6c Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Tue, 13 Dec 2022 16:53:07 -0300 Subject: [PATCH 76/77] keep executing script hash consistent with deploy --- src/Neo.TestEngine/Engine.cs | 1 + src/Neo.TestEngine/TestUtils/Helper.cs | 1 + 2 files changed, 2 insertions(+) diff --git a/src/Neo.TestEngine/Engine.cs b/src/Neo.TestEngine/Engine.cs index 897650e96..f62381371 100644 --- a/src/Neo.TestEngine/Engine.cs +++ b/src/Neo.TestEngine/Engine.cs @@ -41,6 +41,7 @@ public static Engine Instance private TestEngine engine; private Transaction? currentTx = null; + public UInt160 Sender => currentTx?.Sender; private ECPoint PubKey => wallet.DefaultAccount.GetKey().PublicKey; private TestWallet wallet; diff --git a/src/Neo.TestEngine/TestUtils/Helper.cs b/src/Neo.TestEngine/TestUtils/Helper.cs index 8e0892d2f..124482d3f 100644 --- a/src/Neo.TestEngine/TestUtils/Helper.cs +++ b/src/Neo.TestEngine/TestUtils/Helper.cs @@ -9,6 +9,7 @@ public static UInt160 GetContractHash(uint nefCheckSum, string name) { using var sb = new ScriptBuilder(); sb.Emit(OpCode.ABORT); + sb.EmitPush(Engine.Instance.Sender); sb.EmitPush(nefCheckSum); sb.EmitPush(name); From 138176b47accdc09ec5c757ab60080f0f4e2e3b4 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Tue, 13 Dec 2022 19:03:07 -0300 Subject: [PATCH 77/77] incorrect sender being used to deploy other contracts --- src/Neo.TestEngine/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Neo.TestEngine/Program.cs b/src/Neo.TestEngine/Program.cs index 7ae8d8e40..379136e1e 100644 --- a/src/Neo.TestEngine/Program.cs +++ b/src/Neo.TestEngine/Program.cs @@ -263,7 +263,6 @@ public static JObject Run(SmartContractTest smartContractTest) } Engine.Instance.IncreaseBlockCount(smartContractTest.currentHeight); - Engine.Instance.SetSigners(smartContractTest.signers); if (smartContractTest.currentTx != null) { @@ -280,6 +279,7 @@ public static JObject Run(SmartContractTest smartContractTest) Engine.Instance.SetEntryScript(smartContractTest.scriptHash); } + Engine.Instance.SetSigners(smartContractTest.signers); if (smartContractTest.callingScriptHash != null) { Engine.Instance.SetCallingScript(smartContractTest.callingScriptHash);