From 955096cb063aac2695034cace7b18f494ac10577 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Tue, 3 Sep 2024 08:36:19 +0800 Subject: [PATCH 01/83] Add whitelist solution --- AElf.All.sln | 14 +++++++++++++ src/AElf.Launcher/appsettings.Production.json | 4 ++-- src/AElf.Launcher/appsettings.json | 8 +++---- .../AElf.Sdk.CSharp.Internal.csproj | 16 ++++++++++++++ src/AElf.Sdk.CSharp.Internal/AssemblyInfo.cs | 3 +++ .../InternalBuiltIns.cs | 21 +++++++++++++++++++ .../AElf.Sdk.CSharp.Spec.csproj | 10 +++++++++ src/AElf.Sdk.CSharp.Spec/IBuiltIns.cs | 6 ++++++ src/AElf.Sdk.CSharp/AElf.Sdk.CSharp.csproj | 4 ++++ 9 files changed, 80 insertions(+), 6 deletions(-) create mode 100644 src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj create mode 100644 src/AElf.Sdk.CSharp.Internal/AssemblyInfo.cs create mode 100644 src/AElf.Sdk.CSharp.Internal/InternalBuiltIns.cs create mode 100644 src/AElf.Sdk.CSharp.Spec/AElf.Sdk.CSharp.Spec.csproj create mode 100644 src/AElf.Sdk.CSharp.Spec/IBuiltIns.cs diff --git a/AElf.All.sln b/AElf.All.sln index 34ad27a9ac..782e186970 100644 --- a/AElf.All.sln +++ b/AElf.All.sln @@ -385,6 +385,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AElf.Kernel.FeatureDisable. EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AElf.Kernel.FeatureDisable.Core", "src\AElf.Kernel.FeatureDisable.Core\AElf.Kernel.FeatureDisable.Core.csproj", "{659A7C7A-44C9-424E-B4F6-D1D3656F7AD4}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AElf.Sdk.CSharp.Spec", "src\AElf.Sdk.CSharp.Spec\AElf.Sdk.CSharp.Spec.csproj", "{45A77C41-142E-4296-A14A-D53067EC8B75}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AElf.Sdk.CSharp.Internal", "src\AElf.Sdk.CSharp.Internal\AElf.Sdk.CSharp.Internal.csproj", "{A77380A7-E425-45A3-BF3F-F865DA4F3F4E}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -1107,6 +1111,14 @@ Global {659A7C7A-44C9-424E-B4F6-D1D3656F7AD4}.Debug|Any CPU.Build.0 = Debug|Any CPU {659A7C7A-44C9-424E-B4F6-D1D3656F7AD4}.Release|Any CPU.ActiveCfg = Release|Any CPU {659A7C7A-44C9-424E-B4F6-D1D3656F7AD4}.Release|Any CPU.Build.0 = Release|Any CPU + {45A77C41-142E-4296-A14A-D53067EC8B75}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {45A77C41-142E-4296-A14A-D53067EC8B75}.Debug|Any CPU.Build.0 = Debug|Any CPU + {45A77C41-142E-4296-A14A-D53067EC8B75}.Release|Any CPU.ActiveCfg = Release|Any CPU + {45A77C41-142E-4296-A14A-D53067EC8B75}.Release|Any CPU.Build.0 = Release|Any CPU + {A77380A7-E425-45A3-BF3F-F865DA4F3F4E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A77380A7-E425-45A3-BF3F-F865DA4F3F4E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A77380A7-E425-45A3-BF3F-F865DA4F3F4E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A77380A7-E425-45A3-BF3F-F865DA4F3F4E}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -1301,5 +1313,7 @@ Global {A4ACE6D2-4CF8-4B52-93C9-BB8BEC0C098E} = {90B310B4-C2DB-419E-B5EE-97FA096B62CC} {8C0D86A4-D1A7-4B61-AC44-755F5AC75D67} = {4E54480A-D155-43ED-9736-1A5BE7957211} {659A7C7A-44C9-424E-B4F6-D1D3656F7AD4} = {90B310B4-C2DB-419E-B5EE-97FA096B62CC} + {45A77C41-142E-4296-A14A-D53067EC8B75} = {798BAA50-825B-4DD9-83E2-77A9EE6EBE09} + {A77380A7-E425-45A3-BF3F-F865DA4F3F4E} = {798BAA50-825B-4DD9-83E2-77A9EE6EBE09} EndGlobalSection EndGlobal diff --git a/src/AElf.Launcher/appsettings.Production.json b/src/AElf.Launcher/appsettings.Production.json index 14aeb670bf..d321f10b7f 100644 --- a/src/AElf.Launcher/appsettings.Production.json +++ b/src/AElf.Launcher/appsettings.Production.json @@ -1,7 +1,7 @@ { "ConnectionStrings": { - "BlockchainDb": "redis://localhost:6379?db=1", - "StateDb": "redis://localhost:6379?db=1" + "BlockchainDb": "redis://localhost:8881?db=1", + "StateDb": "redis://localhost:8882?db=1" }, "WebApp": { "TransactionResultStatusCacheSeconds": 180 diff --git a/src/AElf.Launcher/appsettings.json b/src/AElf.Launcher/appsettings.json index 7e3d567c35..c4e11c7af8 100644 --- a/src/AElf.Launcher/appsettings.json +++ b/src/AElf.Launcher/appsettings.json @@ -5,12 +5,12 @@ "AllowedHosts": "*", "CorsOrigins": "*", "ConnectionStrings": { - "BlockchainDb": "redis://localhost:6379?db=1", - "StateDb": "redis://localhost:6379?db=1" + "BlockchainDb": "redis://localhost:6666?db=1", + "StateDb": "redis://localhost:6666?db=1" }, "Account": { - "NodeAccount": "", - "NodeAccountPassword": "" + "NodeAccount": "2E2zpf8zMzZBenM4eqtKJhX2m91UxhR1aPEw7hpBNhnJmzbkbp", + "NodeAccountPassword": "12345678" }, "Network": { "BootNodes": [], diff --git a/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj b/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj new file mode 100644 index 0000000000..ffd588c16e --- /dev/null +++ b/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj @@ -0,0 +1,16 @@ + + + + Exe + net8.0 + enable + enable + + + + + all + + + + diff --git a/src/AElf.Sdk.CSharp.Internal/AssemblyInfo.cs b/src/AElf.Sdk.CSharp.Internal/AssemblyInfo.cs new file mode 100644 index 0000000000..1b80097c7f --- /dev/null +++ b/src/AElf.Sdk.CSharp.Internal/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("AElf.Sdk.CSharp")] \ No newline at end of file diff --git a/src/AElf.Sdk.CSharp.Internal/InternalBuiltIns.cs b/src/AElf.Sdk.CSharp.Internal/InternalBuiltIns.cs new file mode 100644 index 0000000000..24c8dcb548 --- /dev/null +++ b/src/AElf.Sdk.CSharp.Internal/InternalBuiltIns.cs @@ -0,0 +1,21 @@ +// using System; +// using AElf.Sdk.CSharp.Spec; +// +// namespace AElf.Sdk.CSharp.Internal; +// +// internal class InternalBuiltIns : IBuiltIns +// { +// public bool Ed25519Verify(byte[] signature, byte[] message, byte[] publicKey) +// { +// try +// { +// var instance =ebex.Security.Cryptography.Ed25519(); +// instance.FromPublicKey(publicKey); +// return instance.VerifyMessage(message, signature); +// } +// catch (Exception e) +// { +// return false; +// } +// } +// } \ No newline at end of file diff --git a/src/AElf.Sdk.CSharp.Spec/AElf.Sdk.CSharp.Spec.csproj b/src/AElf.Sdk.CSharp.Spec/AElf.Sdk.CSharp.Spec.csproj new file mode 100644 index 0000000000..2f4fc77656 --- /dev/null +++ b/src/AElf.Sdk.CSharp.Spec/AElf.Sdk.CSharp.Spec.csproj @@ -0,0 +1,10 @@ + + + + Exe + net8.0 + enable + enable + + + diff --git a/src/AElf.Sdk.CSharp.Spec/IBuiltIns.cs b/src/AElf.Sdk.CSharp.Spec/IBuiltIns.cs new file mode 100644 index 0000000000..bb4a5a7de2 --- /dev/null +++ b/src/AElf.Sdk.CSharp.Spec/IBuiltIns.cs @@ -0,0 +1,6 @@ +namespace AElf.Sdk.CSharp.Spec; + +public interface IBuiltIns +{ + bool Ed25519Verify(byte[] signature, byte[] message, byte[] publicKey); +} \ No newline at end of file diff --git a/src/AElf.Sdk.CSharp/AElf.Sdk.CSharp.csproj b/src/AElf.Sdk.CSharp/AElf.Sdk.CSharp.csproj index 3d27d43369..1127de5481 100644 --- a/src/AElf.Sdk.CSharp/AElf.Sdk.CSharp.csproj +++ b/src/AElf.Sdk.CSharp/AElf.Sdk.CSharp.csproj @@ -13,6 +13,10 @@ + + + all + From 47595fc0d928889f05de1e1aaece49978445833c Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Tue, 3 Sep 2024 16:42:53 +0800 Subject: [PATCH 02/83] Resolve issue of compilation and running, and add unit-test --- src/AElf.Launcher/appsettings.Production.json | 4 +- .../ContractCodeLoadContext.cs | 2 +- .../AElf.Sdk.CSharp.Internal.csproj | 18 +++++--- .../InternalBuiltIns.cs | 46 ++++++++++--------- .../AElf.Sdk.CSharp.Spec.csproj | 1 - src/AElf.Sdk.CSharp/AElf.Sdk.CSharp.csproj | 5 +- .../CSharpSmartContractAbstract.cs | 3 ++ .../CSharpSmartContractContext.cs | 12 ++++- .../AElf.Sdk.CSharp.Tests.csproj | 6 +++ .../CSharpSmartContractContextTests.cs | 46 +++++++++++++++++++ .../ed25519_testdata.json | 44 ++++++++++++++++++ 11 files changed, 151 insertions(+), 36 deletions(-) create mode 100644 test/AElf.Sdk.CSharp.Tests/ed25519_testdata.json diff --git a/src/AElf.Launcher/appsettings.Production.json b/src/AElf.Launcher/appsettings.Production.json index d321f10b7f..14aeb670bf 100644 --- a/src/AElf.Launcher/appsettings.Production.json +++ b/src/AElf.Launcher/appsettings.Production.json @@ -1,7 +1,7 @@ { "ConnectionStrings": { - "BlockchainDb": "redis://localhost:8881?db=1", - "StateDb": "redis://localhost:8882?db=1" + "BlockchainDb": "redis://localhost:6379?db=1", + "StateDb": "redis://localhost:6379?db=1" }, "WebApp": { "TransactionResultStatusCacheSeconds": 180 diff --git a/src/AElf.Runtime.CSharp.Core/ContractCodeLoadContext.cs b/src/AElf.Runtime.CSharp.Core/ContractCodeLoadContext.cs index 507ef7bdcc..c8df9a2114 100644 --- a/src/AElf.Runtime.CSharp.Core/ContractCodeLoadContext.cs +++ b/src/AElf.Runtime.CSharp.Core/ContractCodeLoadContext.cs @@ -28,7 +28,7 @@ protected override Assembly Load(AssemblyName assemblyName) /// private Assembly LoadFromFolderOrDefault(AssemblyName assemblyName) { - if (assemblyName.Name.StartsWith("AElf.Sdk")) + if ("AElf.Sdk.CSharp".Equals(assemblyName.Name)) { // Sdk assembly should NOT be shared using var stream = _sdkStreamManager.GetStream(assemblyName); diff --git a/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj b/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj index ffd588c16e..7557797899 100644 --- a/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj +++ b/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj @@ -1,16 +1,22 @@  - Exe net8.0 - enable - enable + AElf.Sdk.CSharp.Internal + true + latest + Types for the C# smart contract SDK. + AElf.Sdk.CSharp.Internal - + - + all - + + + + + diff --git a/src/AElf.Sdk.CSharp.Internal/InternalBuiltIns.cs b/src/AElf.Sdk.CSharp.Internal/InternalBuiltIns.cs index 24c8dcb548..990e0f49ce 100644 --- a/src/AElf.Sdk.CSharp.Internal/InternalBuiltIns.cs +++ b/src/AElf.Sdk.CSharp.Internal/InternalBuiltIns.cs @@ -1,21 +1,25 @@ -// using System; -// using AElf.Sdk.CSharp.Spec; -// -// namespace AElf.Sdk.CSharp.Internal; -// -// internal class InternalBuiltIns : IBuiltIns -// { -// public bool Ed25519Verify(byte[] signature, byte[] message, byte[] publicKey) -// { -// try -// { -// var instance =ebex.Security.Cryptography.Ed25519(); -// instance.FromPublicKey(publicKey); -// return instance.VerifyMessage(message, signature); -// } -// catch (Exception e) -// { -// return false; -// } -// } -// } \ No newline at end of file +using System; +using AElf.Sdk.CSharp.Spec; + +namespace AElf.Sdk.CSharp.Internal; + +internal class InternalBuiltIns : IBuiltIns +{ + public static void Initialize() + { + // call this method to ensure this assembly is loaded in the runtime. + } + public bool Ed25519Verify(byte[] signature, byte[] message, byte[] publicKey) + { + try + { + var instance = new Rebex.Security.Cryptography.Ed25519(); + instance.FromPublicKey(publicKey); + return instance.VerifyMessage(message, signature); + } + catch (Exception e) + { + return false; + } + } +} \ No newline at end of file diff --git a/src/AElf.Sdk.CSharp.Spec/AElf.Sdk.CSharp.Spec.csproj b/src/AElf.Sdk.CSharp.Spec/AElf.Sdk.CSharp.Spec.csproj index 2f4fc77656..3a63532952 100644 --- a/src/AElf.Sdk.CSharp.Spec/AElf.Sdk.CSharp.Spec.csproj +++ b/src/AElf.Sdk.CSharp.Spec/AElf.Sdk.CSharp.Spec.csproj @@ -1,7 +1,6 @@  - Exe net8.0 enable enable diff --git a/src/AElf.Sdk.CSharp/AElf.Sdk.CSharp.csproj b/src/AElf.Sdk.CSharp/AElf.Sdk.CSharp.csproj index 1127de5481..00cf548872 100644 --- a/src/AElf.Sdk.CSharp/AElf.Sdk.CSharp.csproj +++ b/src/AElf.Sdk.CSharp/AElf.Sdk.CSharp.csproj @@ -13,10 +13,7 @@ - - - all - + diff --git a/src/AElf.Sdk.CSharp/CSharpSmartContractAbstract.cs b/src/AElf.Sdk.CSharp/CSharpSmartContractAbstract.cs index 31d642fdf0..5553b6eb5a 100644 --- a/src/AElf.Sdk.CSharp/CSharpSmartContractAbstract.cs +++ b/src/AElf.Sdk.CSharp/CSharpSmartContractAbstract.cs @@ -1,5 +1,6 @@ using AElf.Kernel.SmartContract; using AElf.Types; +using AElf.Sdk.CSharp.Spec; namespace AElf.Sdk.CSharp; @@ -20,4 +21,6 @@ protected void Assert(bool asserted, string message = "Assertion failed!") } internal abstract void InternalInitialize(ISmartContractBridgeContext bridgeContext); + + public IBuiltIns BuiltIns { get; internal set; } } \ No newline at end of file diff --git a/src/AElf.Sdk.CSharp/CSharpSmartContractContext.cs b/src/AElf.Sdk.CSharp/CSharpSmartContractContext.cs index 5e3ed6c94a..96eeae7eac 100644 --- a/src/AElf.Sdk.CSharp/CSharpSmartContractContext.cs +++ b/src/AElf.Sdk.CSharp/CSharpSmartContractContext.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; using AElf.Kernel.SmartContract; +using AElf.Sdk.CSharp.Internal; +using AElf.Sdk.CSharp.Spec; using AElf.Types; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; @@ -12,11 +14,14 @@ namespace AElf.Sdk.CSharp; /// base class for smart contracts (Context property). It provides access to properties and methods useful for /// implementing the logic in smart contracts. /// -public class CSharpSmartContractContext : ISmartContractBridgeContext +public class CSharpSmartContractContext : ISmartContractBridgeContext, IBuiltIns { + private IBuiltIns BuiltInsImplementation { get; } + public CSharpSmartContractContext(ISmartContractBridgeContext smartContractBridgeContextImplementation) { SmartContractBridgeContextImplementation = smartContractBridgeContextImplementation; + BuiltInsImplementation = new InternalBuiltIns(); } public ISmartContractBridgeContext SmartContractBridgeContextImplementation { get; } @@ -391,4 +396,9 @@ public bool ECVrfVerify(byte[] pubKey, byte[] alpha, byte[] pi, out byte[] beta) { return SmartContractBridgeContextImplementation.ECVrfVerify(pubKey, alpha, pi, out beta); } + + public bool Ed25519Verify(byte[] signature, byte[] message, byte[] publicKey) + { + return BuiltInsImplementation.Ed25519Verify(signature, message, publicKey); + } } \ No newline at end of file diff --git a/test/AElf.Sdk.CSharp.Tests/AElf.Sdk.CSharp.Tests.csproj b/test/AElf.Sdk.CSharp.Tests/AElf.Sdk.CSharp.Tests.csproj index b7379a81dc..91ff826eca 100644 --- a/test/AElf.Sdk.CSharp.Tests/AElf.Sdk.CSharp.Tests.csproj +++ b/test/AElf.Sdk.CSharp.Tests/AElf.Sdk.CSharp.Tests.csproj @@ -30,4 +30,10 @@ + + + + all + + \ No newline at end of file diff --git a/test/AElf.Sdk.CSharp.Tests/CSharpSmartContractContextTests.cs b/test/AElf.Sdk.CSharp.Tests/CSharpSmartContractContextTests.cs index 4e0f98d97a..48dcf22768 100644 --- a/test/AElf.Sdk.CSharp.Tests/CSharpSmartContractContextTests.cs +++ b/test/AElf.Sdk.CSharp.Tests/CSharpSmartContractContextTests.cs @@ -1,3 +1,4 @@ +using System; using AElf.Cryptography; using AElf.Kernel; using AElf.Kernel.SmartContract; @@ -12,6 +13,51 @@ namespace AElf.Sdk.CSharp.Tests; public class CSharpSmartContractContextTests : SdkCSharpTestBase { + [Fact] + public void Verify_Ed25519Verify() + { + var bridgeContext = GetRequiredService().Create(); + var origin = SampleAddress.AddressList[0]; + bridgeContext.TransactionContext = new TransactionContext + { + Origin = origin, + Transaction = new Transaction + { + From = SampleAddress.AddressList[1], + To = SampleAddress.AddressList[2] + } + }; + var contractContext = new CSharpSmartContractContext(bridgeContext); + var publicKey = "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"; + var message = ""; + var signature = "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"; + var ed25519VerifyResult = contractContext.Ed25519Verify( + ByteArrayHelper.HexStringToByteArray(signature), + ByteArrayHelper.HexStringToByteArray(message), + ByteArrayHelper.HexStringToByteArray(publicKey)); + ed25519VerifyResult.ShouldBe(true); + + var contractContext1 = new CSharpSmartContractContext(bridgeContext); + var publicKey1 = "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"; + var message1 = "1"; + var signature1 = "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"; + Should.Throw(() => contractContext1.Ed25519Verify( + ByteArrayHelper.HexStringToByteArray(signature1), + ByteArrayHelper.HexStringToByteArray(message1), + ByteArrayHelper.HexStringToByteArray(publicKey1))); + + // var contractContext2 = new CSharpSmartContractContext(bridgeContext); + // var publicKey2 = "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c"; + // var message2 = "72"; + // var signature2 = "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00"; + // var ed25519VerifyResult2 = contractContext2.Ed25519Verify( + // ByteArrayHelper.HexStringToByteArray(signature2), + // ByteArrayHelper.HexStringToByteArray(message2), + // ByteArrayHelper.HexStringToByteArray(publicKey2)); + // ed25519VerifyResult2.ShouldBe(true); + + } + [Fact] public void Verify_Transaction_Origin_SetValue() { diff --git a/test/AElf.Sdk.CSharp.Tests/ed25519_testdata.json b/test/AElf.Sdk.CSharp.Tests/ed25519_testdata.json new file mode 100644 index 0000000000..60d4a2bad4 --- /dev/null +++ b/test/AElf.Sdk.CSharp.Tests/ed25519_testdata.json @@ -0,0 +1,44 @@ +[ + { + "secret_key": "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", + "public_key": "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", + "message": "", + "signed": "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b", + "signature": "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b" + }, + { + "secret_key": "4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb", + "public_key": "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c", + "message": "72", + "signed": "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c0072", + "signature": "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00" + }, + { + "secret_key": "c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7", + "public_key": "fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025", + "message": "af82", + "signed": "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40aaf82", + "signature": "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a" + }, + { + "secret_key": "0d4a05b07352a5436e180356da0ae6efa0345ff7fb1572575772e8005ed978e9", + "public_key": "e61a185bcef2613a6c7cb79763ce945d3b245d76114dd440bcf5f2dc1aa57057", + "message": "cbc77b", + "signed": "d9868d52c2bebce5f3fa5a79891970f309cb6591e3e1702a70276fa97c24b3a8e58606c38c9758529da50ee31b8219cba45271c689afa60b0ea26c99db19b00ccbc77b", + "signature": "d9868d52c2bebce5f3fa5a79891970f309cb6591e3e1702a70276fa97c24b3a8e58606c38c9758529da50ee31b8219cba45271c689afa60b0ea26c99db19b00c" + }, + { + "secret_key": "6df9340c138cc188b5fe4464ebaa3f7fc206a2d55c3434707e74c9fc04e20ebb", + "public_key": "c0dac102c4533186e25dc43128472353eaabdb878b152aeb8e001f92d90233a7", + "message": "5f4c8989", + "signed": "124f6fc6b0d100842769e71bd530664d888df8507df6c56dedfdb509aeb93416e26b918d38aa06305df3095697c18b2aa832eaa52edc0ae49fbae5a85e150c075f4c8989", + "signature": "124f6fc6b0d100842769e71bd530664d888df8507df6c56dedfdb509aeb93416e26b918d38aa06305df3095697c18b2aa832eaa52edc0ae49fbae5a85e150c07" + }, + { + "secret_key": "b780381a65edf8b78f6945e8dbec7941ac049fd4c61040cf0c324357975a293c", + "public_key": "e253af0766804b869bb1595be9765b534886bbaab8305bf50dbc7f899bfb5f01", + "message": "18b6bec097", + "signed": "b2fc46ad47af464478c199e1f8be169f1be6327c7f9a0a6689371ca94caf04064a01b22aff1520abd58951341603faed768cf78ce97ae7b038abfe456aa17c0918b6bec097", + "signature": "b2fc46ad47af464478c199e1f8be169f1be6327c7f9a0a6689371ca94caf04064a01b22aff1520abd58951341603faed768cf78ce97ae7b038abfe456aa17c09" + } +] \ No newline at end of file From 53f389cec61bd4c2b059ad001ad53803c1decc9e Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Wed, 4 Sep 2024 17:16:56 +0800 Subject: [PATCH 03/83] Revert appsettings.json --- src/AElf.Launcher/appsettings.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/AElf.Launcher/appsettings.json b/src/AElf.Launcher/appsettings.json index c4e11c7af8..7e3d567c35 100644 --- a/src/AElf.Launcher/appsettings.json +++ b/src/AElf.Launcher/appsettings.json @@ -5,12 +5,12 @@ "AllowedHosts": "*", "CorsOrigins": "*", "ConnectionStrings": { - "BlockchainDb": "redis://localhost:6666?db=1", - "StateDb": "redis://localhost:6666?db=1" + "BlockchainDb": "redis://localhost:6379?db=1", + "StateDb": "redis://localhost:6379?db=1" }, "Account": { - "NodeAccount": "2E2zpf8zMzZBenM4eqtKJhX2m91UxhR1aPEw7hpBNhnJmzbkbp", - "NodeAccountPassword": "12345678" + "NodeAccount": "", + "NodeAccountPassword": "" }, "Network": { "BootNodes": [], From a57f39eafeb020e1144cd367956a96c3a6d77513 Mon Sep 17 00:00:00 2001 From: gldeng Date: Wed, 4 Sep 2024 18:12:51 +0800 Subject: [PATCH 04/83] feat(zkp): Add methods required for supporting zkp verification over Bn254 --- .../Validators/Method/ArrayValidator.cs | 3 +- .../AElf.Sdk.CSharp.Internal.csproj | 10 ++- .../InternalBuiltIns.cs | 36 +++++++++++ src/AElf.Sdk.CSharp.Spec/IBuiltIns.cs | 4 ++ .../CSharpSmartContractContext.cs | 55 ++++++++++++----- src/AElf.Types/Types/BigIntValue.cs | 61 ++++++++++++++++++- 6 files changed, 150 insertions(+), 19 deletions(-) diff --git a/src/AElf.CSharp.CodeOps/Validators/Method/ArrayValidator.cs b/src/AElf.CSharp.CodeOps/Validators/Method/ArrayValidator.cs index 5a58387f14..08fced5f36 100644 --- a/src/AElf.CSharp.CodeOps/Validators/Method/ArrayValidator.cs +++ b/src/AElf.CSharp.CodeOps/Validators/Method/ArrayValidator.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Threading; using AElf.CSharp.Core; +using AElf.Types; using Mono.Cecil; using Mono.Cecil.Cil; using Volo.Abp.DependencyInjection; @@ -24,7 +25,7 @@ public class ArrayValidator : IValidator, ITransientDependency .LimitByTotalSize(typeof(decimal), sizeof(decimal)) .LimitByTotalSize(typeof(char), sizeof(char)) .LimitByTotalSize(typeof(String), 128) // Need to limit the size of strings by disallowing String.Concat - + .LimitByTotalSize(typeof(BigIntValue), 128) // It isn't possible to estimate runtime sizes for below, so limit by count .LimitByCount(typeof(Type), 5) .LimitByCount(typeof(Object), 5) // Support object in Linq queries diff --git a/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj b/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj index 7557797899..7f5bd490af 100644 --- a/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj +++ b/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj @@ -10,13 +10,19 @@ - + + all + + + all + + all - + diff --git a/src/AElf.Sdk.CSharp.Internal/InternalBuiltIns.cs b/src/AElf.Sdk.CSharp.Internal/InternalBuiltIns.cs index 990e0f49ce..0d61e255b8 100644 --- a/src/AElf.Sdk.CSharp.Internal/InternalBuiltIns.cs +++ b/src/AElf.Sdk.CSharp.Internal/InternalBuiltIns.cs @@ -1,5 +1,7 @@ using System; using AElf.Sdk.CSharp.Spec; +using Bn254.Net; +using Nethereum.Util; namespace AElf.Sdk.CSharp.Internal; @@ -9,6 +11,7 @@ public static void Initialize() { // call this method to ensure this assembly is loaded in the runtime. } + public bool Ed25519Verify(byte[] signature, byte[] message, byte[] publicKey) { try @@ -22,4 +25,37 @@ public bool Ed25519Verify(byte[] signature, byte[] message, byte[] publicKey) return false; } } + + public byte[] Keccak256(byte[] message) + { + return Sha3Keccack.Current.CalculateHash(message); + } + + public (byte[] x, byte[] y) Bn254G1Mul(byte[] x1, byte[] y1, byte[] s) + { + var (xUInt256, yUInt256) = Bn254.Net.Bn254.Mul(UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), + UInt256.FromBigEndianBytes(s)); + return (xUInt256.ToBigEndianBytes(), yUInt256.ToBigEndianBytes()); + } + + public (byte[] x3, byte[] y3) Bn254G1Add(byte[] x1, byte[] y1, byte[] x2, byte[] y2) + { + var (x3UInt256, y3UInt256) = Bn254.Net.Bn254.Add(UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), + UInt256.FromBigEndianBytes(x2), UInt256.FromBigEndianBytes(y2)); + return (x3UInt256.ToBigEndianBytes(), y3UInt256.ToBigEndianBytes()); + } + + public bool Bn254Pairing((byte[], byte[], byte[], byte[], byte[], byte[])[] input) + { + var elements = new (UInt256, UInt256, UInt256, UInt256, UInt256, UInt256)[input.Length]; + for (var i = 0; i < input.Length; i++) + { + var (x1, y1, x2, y2, x3, y3) = input[i]; + elements[i] = (UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), + UInt256.FromBigEndianBytes(x2), UInt256.FromBigEndianBytes(y2), + UInt256.FromBigEndianBytes(x3), UInt256.FromBigEndianBytes(y3)); + } + + return Bn254.Net.Bn254.Pairing(elements); + } } \ No newline at end of file diff --git a/src/AElf.Sdk.CSharp.Spec/IBuiltIns.cs b/src/AElf.Sdk.CSharp.Spec/IBuiltIns.cs index bb4a5a7de2..f19de71ebe 100644 --- a/src/AElf.Sdk.CSharp.Spec/IBuiltIns.cs +++ b/src/AElf.Sdk.CSharp.Spec/IBuiltIns.cs @@ -3,4 +3,8 @@ public interface IBuiltIns { bool Ed25519Verify(byte[] signature, byte[] message, byte[] publicKey); + byte[] Keccak256(byte[] message); + (byte[] x, byte[] y) Bn254G1Mul(byte[] x1, byte[] y1, byte[] s); + (byte[] x3, byte[] y3) Bn254G1Add(byte[] x1, byte[] y1, byte[] x2, byte[] y2); + bool Bn254Pairing((byte[], byte[], byte[], byte[], byte[], byte[])[] input); } \ No newline at end of file diff --git a/src/AElf.Sdk.CSharp/CSharpSmartContractContext.cs b/src/AElf.Sdk.CSharp/CSharpSmartContractContext.cs index 96eeae7eac..146c0ba31c 100644 --- a/src/AElf.Sdk.CSharp/CSharpSmartContractContext.cs +++ b/src/AElf.Sdk.CSharp/CSharpSmartContractContext.cs @@ -17,7 +17,7 @@ namespace AElf.Sdk.CSharp; public class CSharpSmartContractContext : ISmartContractBridgeContext, IBuiltIns { private IBuiltIns BuiltInsImplementation { get; } - + public CSharpSmartContractContext(ISmartContractBridgeContext smartContractBridgeContextImplementation) { SmartContractBridgeContextImplementation = smartContractBridgeContextImplementation; @@ -90,7 +90,7 @@ public void FireLogEvent(LogEvent logEvent) /// The height of the block that contains the transaction before charging. /// public Transaction Transaction => SmartContractBridgeContextImplementation.Transaction; - + /// /// The time included in the current blocks header. /// @@ -153,7 +153,7 @@ public void DeployContract(Address address, SmartContractRegistration registrati { SmartContractBridgeContextImplementation.DeployContract(address, registration, name); } - + /// /// Update a smart contract (only the genesis contract can call it). /// @@ -164,17 +164,21 @@ public void UpdateContract(Address address, SmartContractRegistration registrati { SmartContractBridgeContextImplementation.UpdateContract(address, registration, name); } - + public ContractInfoDto DeploySmartContract(Address address, SmartContractRegistration registration, Hash name) { - return SmartContractBridgeContextImplementation.DeploySmartContract(address,registration,name); + return SmartContractBridgeContextImplementation.DeploySmartContract(address, registration, name); } - public ContractInfoDto UpdateSmartContract(Address address, SmartContractRegistration registration, Hash name,string previousContractVersion) + + public ContractInfoDto UpdateSmartContract(Address address, SmartContractRegistration registration, Hash name, + string previousContractVersion) { - return SmartContractBridgeContextImplementation.UpdateSmartContract(address,registration,name,previousContractVersion); + return SmartContractBridgeContextImplementation.UpdateSmartContract(address, registration, name, + previousContractVersion); } - public ContractVersionCheckDto CheckContractVersion(string previousContractVersion, SmartContractRegistration registration) + public ContractVersionCheckDto CheckContractVersion(string previousContractVersion, + SmartContractRegistration registration) { return SmartContractBridgeContextImplementation.CheckContractVersion(previousContractVersion, registration); } @@ -226,13 +230,14 @@ public void SendVirtualInline(Hash fromVirtualAddress, Address toAddress, string SmartContractBridgeContextImplementation.SendVirtualInline(fromVirtualAddress, toAddress, methodName, args); } - - public void SendVirtualInline(Hash fromVirtualAddress, Address toAddress, string methodName, ByteString args,bool logTransaction) + + public void SendVirtualInline(Hash fromVirtualAddress, Address toAddress, string methodName, ByteString args, + bool logTransaction) { SmartContractBridgeContextImplementation.SendVirtualInline(fromVirtualAddress, toAddress, methodName, - args,logTransaction); + args, logTransaction); } - + /// /// Sends a virtual inline transaction to another contract. This method is only available to system smart contract. @@ -250,7 +255,7 @@ public void SendVirtualInlineBySystemContract(Hash fromVirtualAddress, Address t SmartContractBridgeContextImplementation.SendVirtualInlineBySystemContract(fromVirtualAddress, toAddress, methodName, args); } - + public void SendVirtualInlineBySystemContract(Hash fromVirtualAddress, Address toAddress, string methodName, ByteString args, bool logTransaction) { @@ -391,14 +396,34 @@ public Address ConvertVirtualAddressToContractAddressWithContractHashName(Hash v return SmartContractBridgeContextImplementation.ConvertVirtualAddressToContractAddressWithContractHashName( virtualAddress); } - + public bool ECVrfVerify(byte[] pubKey, byte[] alpha, byte[] pi, out byte[] beta) { return SmartContractBridgeContextImplementation.ECVrfVerify(pubKey, alpha, pi, out beta); } - + public bool Ed25519Verify(byte[] signature, byte[] message, byte[] publicKey) { return BuiltInsImplementation.Ed25519Verify(signature, message, publicKey); } + + public byte[] Keccak256(byte[] message) + { + return BuiltInsImplementation.Keccak256(message); + } + + public (byte[] x, byte[] y) Bn254G1Mul(byte[] x1, byte[] y1, byte[] s) + { + return BuiltInsImplementation.Bn254G1Mul(x1, y1, s); + } + + public (byte[] x3, byte[] y3) Bn254G1Add(byte[] x1, byte[] y1, byte[] x2, byte[] y2) + { + return BuiltInsImplementation.Bn254G1Add(x1, y1, x2, y2); + } + + public bool Bn254Pairing((byte[], byte[], byte[], byte[], byte[], byte[])[] input) + { + return BuiltInsImplementation.Bn254Pairing(input); + } } \ No newline at end of file diff --git a/src/AElf.Types/Types/BigIntValue.cs b/src/AElf.Types/Types/BigIntValue.cs index 38ddc94df6..f65c8897a3 100644 --- a/src/AElf.Types/Types/BigIntValue.cs +++ b/src/AElf.Types/Types/BigIntValue.cs @@ -5,9 +5,30 @@ namespace AElf.Types { - public partial class BigIntValue : IComparable, IComparable { + #region Frequent Values + + public static BigIntValue Zero => new BigIntValue { Value = "0" }; + public static BigIntValue One => new BigIntValue { Value = "1" }; + + #endregion + + public static BigIntValue FromBigEndianBytes(byte[] bigEndianBytes) + { + var bigInteger = new BigInteger(bigEndianBytes, true, true); + return new BigIntValue + { + Value = bigInteger.ToString() + }; + } + + public byte[] ToBigEndianBytes() + { + var bigInteger = ConvertStringToBigInteger(Value); + return bigInteger.ToByteArray(true, true); + } + public int CompareTo(object obj) { if (!(obj is BigIntValue bigInt)) throw new InvalidOperationException(); @@ -126,6 +147,43 @@ private static bool LessThan(in BigIntValue a, in BigIntValue b) return aBigInt < bBigInt; } + #region Operators + + public static BigIntValue operator %(BigIntValue a, BigIntValue b) + { + return BigInteger.Remainder(ConvertStringToBigInteger(a.Value), ConvertStringToBigInteger(b.Value)) + .ToString(); + } + + public static BigIntValue operator +(BigIntValue a, BigIntValue b) + { + return BigInteger.Add(ConvertStringToBigInteger(a.Value), ConvertStringToBigInteger(b.Value)).ToString(); + } + + public static BigIntValue operator -(BigIntValue a, BigIntValue b) + { + return BigInteger.Subtract(ConvertStringToBigInteger(a.Value), ConvertStringToBigInteger(b.Value)) + .ToString(); + } + + public static BigIntValue operator *(BigIntValue a, BigIntValue b) + { + return BigInteger.Multiply(ConvertStringToBigInteger(a.Value), ConvertStringToBigInteger(b.Value)) + .ToString(); + } + + public static bool operator ==(BigIntValue a, BigIntValue b) + { + return ConvertStringToBigInteger(a?.Value ?? "0") == ConvertStringToBigInteger(b?.Value ?? "0"); + } + + public static bool operator !=(BigIntValue a, BigIntValue b) + { + return !(a == b); + } + + #endregion + #region < <= > >= public static bool operator <(in BigIntValue a, in BigIntValue b) @@ -149,5 +207,6 @@ private static bool LessThan(in BigIntValue a, in BigIntValue b) } #endregion + } } \ No newline at end of file From b66e60c1643f3ccaa32ef9100f5b938014bf2c85 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Sun, 29 Sep 2024 15:23:46 +0800 Subject: [PATCH 05/83] Change version to 8.0.402 in sonarqube.yaml --- .github/workflows/sonarqube.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/sonarqube.yaml b/.github/workflows/sonarqube.yaml index dbfca652b6..468b1a3057 100644 --- a/.github/workflows/sonarqube.yaml +++ b/.github/workflows/sonarqube.yaml @@ -15,7 +15,7 @@ jobs: with: dotnet-version: '8.0' - name: Create temporary global.json - run: echo '{"sdk":{"version":"8.0.303"}}' > ./global.json + run: echo '{"sdk":{"version":"8.0.402"}}' > ./global.json - name: Set up JDK 17 uses: actions/setup-java@v1 with: From 6469d74f51ae58d793ad0ffaf220f9841398c822 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Sun, 29 Sep 2024 15:29:24 +0800 Subject: [PATCH 06/83] Change version of sdk --- .github/workflows/sonarqube.yaml | 2 +- global.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/sonarqube.yaml b/.github/workflows/sonarqube.yaml index 468b1a3057..b87ff0cf93 100644 --- a/.github/workflows/sonarqube.yaml +++ b/.github/workflows/sonarqube.yaml @@ -15,7 +15,7 @@ jobs: with: dotnet-version: '8.0' - name: Create temporary global.json - run: echo '{"sdk":{"version":"8.0.402"}}' > ./global.json + run: echo '{"sdk":{"version":"8.0.*"}}' > ./global.json - name: Set up JDK 17 uses: actions/setup-java@v1 with: diff --git a/global.json b/global.json index 1978c843c7..686e090626 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "8.0.303" + "version": "8.0.402" } } \ No newline at end of file From 00d0b6e2c03b1880f57094be735a411a0f5984bf Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Sun, 29 Sep 2024 15:35:45 +0800 Subject: [PATCH 07/83] Change version of sdk --- global.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/global.json b/global.json index 686e090626..70976d298f 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "8.0.402" + "version": "8.0.*" } } \ No newline at end of file From 77e2d11f402ed5a71143a55bdb634ec990bda72b Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Sun, 29 Sep 2024 17:05:18 +0800 Subject: [PATCH 08/83] Add sources --- nuget.config | 3 +++ 1 file changed, 3 insertions(+) diff --git a/nuget.config b/nuget.config index 8b19203c51..e75cd52656 100644 --- a/nuget.config +++ b/nuget.config @@ -1,6 +1,9 @@ + + + \ No newline at end of file From 0c5cf130d48f8aefbf5b88745110c4a5dd3deeca Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Tue, 8 Oct 2024 13:56:00 +0800 Subject: [PATCH 09/83] Change versions and add whitelist --- src/AElf.CSharp.CodeOps/AElf.CSharp.CodeOps.csproj | 2 -- .../Validators/Whitelist/IWhitelistProvider.cs | 9 +++++++++ .../AElf.Sdk.CSharp.Internal.csproj | 3 ++- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/AElf.CSharp.CodeOps/AElf.CSharp.CodeOps.csproj b/src/AElf.CSharp.CodeOps/AElf.CSharp.CodeOps.csproj index dc5501294c..e4cd5517c8 100644 --- a/src/AElf.CSharp.CodeOps/AElf.CSharp.CodeOps.csproj +++ b/src/AElf.CSharp.CodeOps/AElf.CSharp.CodeOps.csproj @@ -10,8 +10,6 @@ - - diff --git a/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs b/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs index 4f3ec683be..1d50b2d12d 100644 --- a/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs +++ b/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs @@ -62,6 +62,15 @@ private void WhitelistSystemTypes(Whitelist whitelist) .Type("Func`1", Permission.Allowed) // Required for protobuf generated code .Type("Func`2", Permission.Allowed) // Required for protobuf generated code .Type("Func`3", Permission.Allowed) // Required for protobuf generated code + .Type("Func`4", Permission.Allowed) + .Type("ValueTuple`1", Permission.Allowed) + .Type("ValueTuple`2", Permission.Allowed) + .Type("ValueTuple`3", Permission.Allowed) + .Type("ValueTuple`4", Permission.Allowed) + .Type("ValueTuple`5", Permission.Allowed) + .Type("ValueTuple`6", Permission.Allowed) + .Type("ValueTuple`7", Permission.Allowed) + .Type("ValueTuple`8", Permission.Allowed) .Type("Nullable`1", Permission.Allowed) // Required for protobuf generated code .Type(typeof(BitConverter), Permission.Denied, member => member .Member(nameof(BitConverter.GetBytes), Permission.Allowed)) diff --git a/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj b/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj index 7f5bd490af..39b69c4352 100644 --- a/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj +++ b/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj @@ -10,7 +10,8 @@ - + + all From 4e5b3aadab39820c2eaab97f0f8fb069cf2056a4 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Tue, 8 Oct 2024 15:09:23 +0800 Subject: [PATCH 10/83] Remove poseidon and groth16 in IWhitelistProvider.cs --- .../Validators/Whitelist/IWhitelistProvider.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs b/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs index b5db05aad4..1d50b2d12d 100644 --- a/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs +++ b/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs @@ -49,8 +49,6 @@ private void WhitelistAssemblies(Whitelist whitelist) .Assembly(typeof(IMethod).Assembly, Trust.Full) // AElf.CSharp.Core .Assembly(typeof(SecretSharingHelper).Assembly, Trust.Partial) // AElf.Cryptography .Assembly(typeof(ISmartContractBridgeContext).Assembly, Trust.Full) // AElf.Kernel.SmartContract.Shared - .Assembly(typeof(Groth16.Net.Verifier).Assembly, Trust.Full) // AElf.Cryptography.ECDSA - .Assembly(typeof(Poseidon.Net.Poseidon).Assembly, Trust.Full) ; } From aa43d7b0c8f1a1dafd42dce8cde06dfcc70b6003 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Thu, 7 Nov 2024 15:02:01 +0800 Subject: [PATCH 11/83] Add config for auto-publishing --- .../AElf.Blockchains.MainChain.csproj | 2 ++ .../AElf.Blockchains.SideChain.csproj | 2 ++ .../AElf.Kernel.FeatureDisable.Core.csproj | 2 ++ .../AElf.Kernel.FeatureDisable.csproj | 2 ++ src/AElf.Sdk.CSharp.Spec/AElf.Sdk.CSharp.Spec.csproj | 2 ++ 5 files changed, 10 insertions(+) diff --git a/src/AElf.Blockchains.MainChain/AElf.Blockchains.MainChain.csproj b/src/AElf.Blockchains.MainChain/AElf.Blockchains.MainChain.csproj index c99ca2bf21..7097bb2748 100644 --- a/src/AElf.Blockchains.MainChain/AElf.Blockchains.MainChain.csproj +++ b/src/AElf.Blockchains.MainChain/AElf.Blockchains.MainChain.csproj @@ -5,6 +5,8 @@ 0436 Main module for a mainchain node. + Release + true diff --git a/src/AElf.Blockchains.SideChain/AElf.Blockchains.SideChain.csproj b/src/AElf.Blockchains.SideChain/AElf.Blockchains.SideChain.csproj index 9364aac96b..063a9d5ebf 100644 --- a/src/AElf.Blockchains.SideChain/AElf.Blockchains.SideChain.csproj +++ b/src/AElf.Blockchains.SideChain/AElf.Blockchains.SideChain.csproj @@ -3,6 +3,8 @@ net8.0 Main module for a sidechain node. + Release + true 1701;1702 diff --git a/src/AElf.Kernel.FeatureDisable.Core/AElf.Kernel.FeatureDisable.Core.csproj b/src/AElf.Kernel.FeatureDisable.Core/AElf.Kernel.FeatureDisable.Core.csproj index 7b39f518d5..991781b591 100644 --- a/src/AElf.Kernel.FeatureDisable.Core/AElf.Kernel.FeatureDisable.Core.csproj +++ b/src/AElf.Kernel.FeatureDisable.Core/AElf.Kernel.FeatureDisable.Core.csproj @@ -4,6 +4,8 @@ net8.0 enable enable + Release + true diff --git a/src/AElf.Kernel.FeatureDisable/AElf.Kernel.FeatureDisable.csproj b/src/AElf.Kernel.FeatureDisable/AElf.Kernel.FeatureDisable.csproj index fae7fc0cdf..04323c5ffe 100644 --- a/src/AElf.Kernel.FeatureDisable/AElf.Kernel.FeatureDisable.csproj +++ b/src/AElf.Kernel.FeatureDisable/AElf.Kernel.FeatureDisable.csproj @@ -4,6 +4,8 @@ net8.0 enable enable + Release + true diff --git a/src/AElf.Sdk.CSharp.Spec/AElf.Sdk.CSharp.Spec.csproj b/src/AElf.Sdk.CSharp.Spec/AElf.Sdk.CSharp.Spec.csproj index 3a63532952..81ab49bf3a 100644 --- a/src/AElf.Sdk.CSharp.Spec/AElf.Sdk.CSharp.Spec.csproj +++ b/src/AElf.Sdk.CSharp.Spec/AElf.Sdk.CSharp.Spec.csproj @@ -4,6 +4,8 @@ net8.0 enable enable + Release + true From 534f24b099b8bd743b49279f87a0eb89b57b0417 Mon Sep 17 00:00:00 2001 From: eanzhao Date: Sat, 9 Nov 2024 13:22:00 +0800 Subject: [PATCH 12/83] Now some of inline txs will have their own tx id via layered method name. --- .../PlainTransactionExecutingService.cs | 91 ++++++++++++++++++- .../Application/BlockExecutingService.cs | 19 ++-- 2 files changed, 98 insertions(+), 12 deletions(-) diff --git a/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs b/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs index 79b09034f9..df67cec50b 100644 --- a/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs +++ b/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs @@ -3,6 +3,7 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using AElf.CSharp.Core.Extension; using AElf.Kernel.FeatureDisable.Core; using AElf.Kernel.SmartContract.Domain; using AElf.Kernel.SmartContract.Infrastructure; @@ -71,7 +72,7 @@ public async Task> ExecuteAsync(TransactionExecutingDto var transactionExecutionTask = Task.Run(() => ExecuteOneAsync(singleTxExecutingDto, cancellationToken), cancellationToken); - trace = await transactionExecutionTask.WithCancellation(cancellationToken); + trace = await transactionExecutionTask; } catch (OperationCanceledException) { @@ -90,7 +91,7 @@ public async Task> ExecuteAsync(TransactionExecutingDto var result = GetTransactionResult(trace, transactionExecutingDto.BlockHeader.Height); var returnSet = GetReturnSet(trace, result); - returnSets.Add(returnSet); + returnSets.AddRange(returnSet); } return returnSets; @@ -175,14 +176,22 @@ protected virtual async Task ExecuteOneAsync( #endregion + var methodName = txContext.Transaction.MethodName; + var originMethodName = MaybeRecoverInlineTransactionFunctionName(methodName); + txContext.Transaction.MethodName = originMethodName; + await executive.ApplyAsync(txContext); if (txContext.Trace.IsSuccessful()) + { + // Maybe layered method name. + txContext.Transaction.MethodName = methodName; await ExecuteInlineTransactions(singleTxExecutingDto.Depth, singleTxExecutingDto.CurrentBlockTime, txContext, internalStateCache, internalChainContext, singleTxExecutingDto.OriginTransactionId, cancellationToken); + } #region PostTransaction @@ -221,8 +230,33 @@ private async Task ExecuteInlineTransactions(int depth, Timestamp currentBlockTi { var trace = txContext.Trace; internalStateCache.Update(txContext.Trace.GetStateSets()); + + var methodNameCount = new Dictionary(); foreach (var inlineTx in txContext.Trace.InlineTransactions) { + var needTxId = NeedTransactionId(inlineTx.MethodName); + if (needTxId) + { + if (!methodNameCount.TryAdd(inlineTx.MethodName, 0)) + { + methodNameCount[inlineTx.MethodName]++; + inlineTx.MethodName = + GenerateLayeredMethodNameForInlineTransaction( + txContext.Transaction.MethodName, + inlineTx.MethodName, + methodNameCount[inlineTx.MethodName] + ); + } + else + { + inlineTx.MethodName = GenerateLayeredMethodNameForInlineTransaction( + txContext.Transaction.MethodName, + inlineTx.MethodName, + 0 + ); + } + } + var singleTxExecutingDto = new SingleTransactionExecutingDto { Depth = depth + 1, @@ -246,6 +280,23 @@ private async Task ExecuteInlineTransactions(int depth, Timestamp currentBlockTi } } + private static string GenerateLayeredMethodNameForInlineTransaction(string txContextMethodName, string inlineFunctionName, int index) + { + inlineFunctionName = inlineFunctionName.StartsWith('.') ? inlineFunctionName[1..] : inlineFunctionName; + return $"{txContextMethodName}.{inlineFunctionName}.{index}"; + } + + private static string MaybeRecoverInlineTransactionFunctionName(string methodName) + { + var parts = methodName.Split('.'); + return parts.Length > 1 ? parts[^2] : methodName; + } + + private static bool NeedTransactionId(string methodName) + { + return methodName.Contains('.'); + } + private async Task ExecutePluginOnPreTransactionStageAsync(IExecutive executive, ITransactionContext txContext, Timestamp currentBlockTime, @@ -393,7 +444,7 @@ private TransactionResult GetTransactionResult(TransactionTrace trace, long bloc return txResult; } - private ExecutionReturnSet GetReturnSet(TransactionTrace trace, TransactionResult result) + private IEnumerable GetReturnSet(TransactionTrace trace, TransactionResult result) { var returnSet = new ExecutionReturnSet { @@ -402,12 +453,44 @@ private ExecutionReturnSet GetReturnSet(TransactionTrace trace, TransactionResul Bloom = result.Bloom, TransactionResult = result }; + var returnSets = new List { returnSet }; if (trace.IsSuccessful()) { var transactionExecutingStateSets = trace.GetStateSets(); returnSet = GetReturnSet(returnSet, transactionExecutingStateSets); returnSet.ReturnValue = trace.ReturnValue; + + var inlineTxWithIdList = trace.InlineTransactions.Where(tx => NeedTransactionId(tx.MethodName)); + foreach (var inlineTx in inlineTxWithIdList) + { + var inlineTxId = inlineTx.GetHash(); + var inlineReturnSet = new ExecutionReturnSet + { + TransactionId = inlineTxId, + Status = TransactionResultStatus.Mined, + TransactionResult = new TransactionResult + { + TransactionId = inlineTxId, + BlockNumber = result.BlockNumber, + Status = TransactionResultStatus.Mined + } + }; + + // No need to execute GetReturnSet method, because changes are already set to `returnSet1`. + + returnSets.Add(inlineReturnSet); + + // TODO: Maybe we need to add a new log for inline tx with id created. + var log = new VirtualTransactionCreated + { + From = inlineTx.From, + To = inlineTx.To, + MethodName = inlineTx.MethodName, + Params = inlineTx.Params, + }; + returnSet.TransactionResult.Logs.Add(log.ToLogEvent()); + } } else { @@ -426,7 +509,7 @@ private ExecutionReturnSet GetReturnSet(TransactionTrace trace, TransactionResul var reads = trace.GetFlattenedReads(); foreach (var read in reads) returnSet.StateAccesses[read.Key] = read.Value; - return returnSet; + return returnSets; } private ExecutionReturnSet GetReturnSet(ExecutionReturnSet returnSet, diff --git a/src/AElf.Kernel.SmartContractExecution/Application/BlockExecutingService.cs b/src/AElf.Kernel.SmartContractExecution/Application/BlockExecutingService.cs index 6dcfca3178..2bf62a5c30 100644 --- a/src/AElf.Kernel.SmartContractExecution/Application/BlockExecutingService.cs +++ b/src/AElf.Kernel.SmartContractExecution/Application/BlockExecutingService.cs @@ -68,15 +68,16 @@ await _transactionExecutingService.ExecuteAsync( if (!cancellationToken.IsCancellationRequested && cancellable.Count > 0) { + var txExecutingDto = new TransactionExecutingDto + { + BlockHeader = blockHeader, + Transactions = cancellable, + PartialBlockStateSet = returnSetCollection.ToBlockStateSet() + }; cancellableReturnSets = await _transactionExecutingService.ExecuteAsync( - new TransactionExecutingDto - { - BlockHeader = blockHeader, - Transactions = cancellable, - PartialBlockStateSet = returnSetCollection.ToBlockStateSet() - }, - cancellationToken); + txExecutingDto, cancellationToken); returnSetCollection.AddRange(cancellableReturnSets); + cancellable = txExecutingDto.Transactions.ToList(); Logger.LogTrace("Executed cancellable txs"); } @@ -119,7 +120,9 @@ private Task FillBlockAfterExecutionAsync(BlockHeader header, var allExecutedTransactionIds = transactions.Select(x => x.GetHash()).ToList(); var orderedReturnSets = executionReturnSetCollection.GetExecutionReturnSetList() - .OrderBy(d => allExecutedTransactionIds.IndexOf(d.TransactionId)).ToList(); + .OrderBy(d => allExecutedTransactionIds.IndexOf(d.TransactionId) >= 0 ? allExecutedTransactionIds.IndexOf(d.TransactionId) : int.MaxValue) + .ThenBy(d => d.TransactionId) + .ToList(); var block = new Block { From 46e54c54aaa66cb64f90bee31c5ddfc885179086 Mon Sep 17 00:00:00 2001 From: eanzhao Date: Sat, 9 Nov 2024 13:57:04 +0800 Subject: [PATCH 13/83] Improve layered method name. --- ...EDPoSContract_ProcessConsensusInformation.cs | 17 +++++++++++++---- .../PlainTransactionExecutingService.cs | 12 +++++++----- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/contract/AElf.Contracts.Consensus.AEDPoS/AEDPoSContract_ProcessConsensusInformation.cs b/contract/AElf.Contracts.Consensus.AEDPoS/AEDPoSContract_ProcessConsensusInformation.cs index 88632c10ff..4067e98345 100644 --- a/contract/AElf.Contracts.Consensus.AEDPoS/AEDPoSContract_ProcessConsensusInformation.cs +++ b/contract/AElf.Contracts.Consensus.AEDPoS/AEDPoSContract_ProcessConsensusInformation.cs @@ -127,10 +127,19 @@ private void ProcessNextRound(NextRoundInput input) { var minersCount = GetMinersCount(nextRound); if (minersCount != 0 && State.ElectionContract.Value != null) - State.ElectionContract.UpdateMinersCount.Send(new UpdateMinersCountInput - { - MinersCount = minersCount - }); + { + // State.ElectionContract.UpdateMinersCount.Send(new UpdateMinersCountInput + // { + // MinersCount = minersCount + // }); + // TODO: Fix this if feature verified. + Context.SendInline(State.ElectionContract.Value, + $".{nameof(State.ElectionContract.UpdateMinersCount)}", + new UpdateMinersCountInput + { + MinersCount = minersCount + }); + } } } diff --git a/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs b/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs index df67cec50b..8bbd56d88d 100644 --- a/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs +++ b/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs @@ -242,7 +242,7 @@ private async Task ExecuteInlineTransactions(int depth, Timestamp currentBlockTi methodNameCount[inlineTx.MethodName]++; inlineTx.MethodName = GenerateLayeredMethodNameForInlineTransaction( - txContext.Transaction.MethodName, + txContext.Transaction, inlineTx.MethodName, methodNameCount[inlineTx.MethodName] ); @@ -250,7 +250,7 @@ private async Task ExecuteInlineTransactions(int depth, Timestamp currentBlockTi else { inlineTx.MethodName = GenerateLayeredMethodNameForInlineTransaction( - txContext.Transaction.MethodName, + txContext.Transaction, inlineTx.MethodName, 0 ); @@ -280,10 +280,12 @@ private async Task ExecuteInlineTransactions(int depth, Timestamp currentBlockTi } } - private static string GenerateLayeredMethodNameForInlineTransaction(string txContextMethodName, string inlineFunctionName, int index) + private static string GenerateLayeredMethodNameForInlineTransaction(Transaction parentTx, string inlineFunctionName, + int index) { + var parentTxMethodName = parentTx.MethodName; inlineFunctionName = inlineFunctionName.StartsWith('.') ? inlineFunctionName[1..] : inlineFunctionName; - return $"{txContextMethodName}.{inlineFunctionName}.{index}"; + return $"{parentTx.GetHash().ToHex()}.{parentTxMethodName}.{inlineFunctionName}.{index}"; } private static string MaybeRecoverInlineTransactionFunctionName(string methodName) @@ -477,7 +479,7 @@ private IEnumerable GetReturnSet(TransactionTrace trace, Tra } }; - // No need to execute GetReturnSet method, because changes are already set to `returnSet1`. + // No need to execute GetReturnSet method, because changes are already set to `returnSet`. returnSets.Add(inlineReturnSet); From be03fce6b16791749adc253bf0d90c10ccdcfadc Mon Sep 17 00:00:00 2001 From: eanzhao Date: Sat, 9 Nov 2024 16:44:05 +0800 Subject: [PATCH 14/83] Put inline txs to block body. --- ...PoSContract_ProcessConsensusInformation.cs | 23 ++++++++++--------- protobuf/aedpos_contract.proto | 3 +++ .../PlainTransactionExecutingService.cs | 11 +++++++-- .../Application/BlockExecutingService.cs | 6 +++++ 4 files changed, 30 insertions(+), 13 deletions(-) diff --git a/contract/AElf.Contracts.Consensus.AEDPoS/AEDPoSContract_ProcessConsensusInformation.cs b/contract/AElf.Contracts.Consensus.AEDPoS/AEDPoSContract_ProcessConsensusInformation.cs index 4067e98345..0a01c8cf52 100644 --- a/contract/AElf.Contracts.Consensus.AEDPoS/AEDPoSContract_ProcessConsensusInformation.cs +++ b/contract/AElf.Contracts.Consensus.AEDPoS/AEDPoSContract_ProcessConsensusInformation.cs @@ -84,6 +84,14 @@ private void ProcessConsensusInformation(dynamic input, [CallerMemberName] strin // Clear cache. _processingBlockMinerPubkey = null; + + // TODO: Clear this if feature verified. + Context.SendInline(Context.Self, $".{nameof(DoNothing)}", new Empty()); + } + + public override Empty DoNothing(Empty input) + { + return new Empty(); } /// @@ -128,17 +136,10 @@ private void ProcessNextRound(NextRoundInput input) var minersCount = GetMinersCount(nextRound); if (minersCount != 0 && State.ElectionContract.Value != null) { - // State.ElectionContract.UpdateMinersCount.Send(new UpdateMinersCountInput - // { - // MinersCount = minersCount - // }); - // TODO: Fix this if feature verified. - Context.SendInline(State.ElectionContract.Value, - $".{nameof(State.ElectionContract.UpdateMinersCount)}", - new UpdateMinersCountInput - { - MinersCount = minersCount - }); + State.ElectionContract.UpdateMinersCount.Send(new UpdateMinersCountInput + { + MinersCount = minersCount + }); } } } diff --git a/protobuf/aedpos_contract.proto b/protobuf/aedpos_contract.proto index d06f5d5ccf..7519a5e82b 100644 --- a/protobuf/aedpos_contract.proto +++ b/protobuf/aedpos_contract.proto @@ -41,6 +41,9 @@ service AEDPoSContract { // Update consensus tiny block information. rpc UpdateTinyBlockInformation (TinyBlockInput) returns (google.protobuf.Empty) { } + + rpc DoNothing (google.protobuf.Empty) returns (google.protobuf.Empty) { + } // Set the maximum count of miners, by default, is unlimited. // If you want to control the count of miners, you need to set it through parliament. diff --git a/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs b/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs index 8bbd56d88d..b4369eaeaf 100644 --- a/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs +++ b/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs @@ -4,6 +4,7 @@ using System.Threading; using System.Threading.Tasks; using AElf.CSharp.Core.Extension; +using AElf.Kernel.Blockchain.Application; using AElf.Kernel.FeatureDisable.Core; using AElf.Kernel.SmartContract.Domain; using AElf.Kernel.SmartContract.Infrastructure; @@ -24,14 +25,17 @@ public class PlainTransactionExecutingService : IPlainTransactionExecutingServic private readonly ISmartContractExecutiveService _smartContractExecutiveService; private readonly ITransactionContextFactory _transactionContextFactory; private readonly IFeatureDisableService _featureDisableService; + private readonly IBlockchainService _blockchainService; public PlainTransactionExecutingService(ISmartContractExecutiveService smartContractExecutiveService, IEnumerable postPlugins, IEnumerable prePlugins, - ITransactionContextFactory transactionContextFactory, IFeatureDisableService featureDisableService) + ITransactionContextFactory transactionContextFactory, IFeatureDisableService featureDisableService, + IBlockchainService blockchainService) { _smartContractExecutiveService = smartContractExecutiveService; _transactionContextFactory = transactionContextFactory; _featureDisableService = featureDisableService; + _blockchainService = blockchainService; _prePlugins = GetUniquePlugins(prePlugins); _postPlugins = GetUniquePlugins(postPlugins); Logger = NullLogger.Instance; @@ -255,6 +259,8 @@ private async Task ExecuteInlineTransactions(int depth, Timestamp currentBlockTi 0 ); } + + await _blockchainService.AddTransactionsAsync([inlineTx]); } var singleTxExecutingDto = new SingleTransactionExecutingDto @@ -483,6 +489,7 @@ private IEnumerable GetReturnSet(TransactionTrace trace, Tra returnSets.Add(inlineReturnSet); + Logger.LogWarning($"Inline tx id: {inlineTx.GetHash().ToHex()}\n{inlineTx}"); // TODO: Maybe we need to add a new log for inline tx with id created. var log = new VirtualTransactionCreated { @@ -491,7 +498,7 @@ private IEnumerable GetReturnSet(TransactionTrace trace, Tra MethodName = inlineTx.MethodName, Params = inlineTx.Params, }; - returnSet.TransactionResult.Logs.Add(log.ToLogEvent()); + returnSet.TransactionResult.Logs.Add(log.ToLogEvent(inlineTx.To)); } } else diff --git a/src/AElf.Kernel.SmartContractExecution/Application/BlockExecutingService.cs b/src/AElf.Kernel.SmartContractExecution/Application/BlockExecutingService.cs index 2bf62a5c30..3fe89db6bc 100644 --- a/src/AElf.Kernel.SmartContractExecution/Application/BlockExecutingService.cs +++ b/src/AElf.Kernel.SmartContractExecution/Application/BlockExecutingService.cs @@ -123,6 +123,12 @@ private Task FillBlockAfterExecutionAsync(BlockHeader header, .OrderBy(d => allExecutedTransactionIds.IndexOf(d.TransactionId) >= 0 ? allExecutedTransactionIds.IndexOf(d.TransactionId) : int.MaxValue) .ThenBy(d => d.TransactionId) .ToList(); + + var inlineTxIds = orderedReturnSets + .Where(returnSet => !allExecutedTransactionIds.Contains(returnSet.TransactionId)) + .Select(returnSet => returnSet.TransactionId) + .ToList(); + allExecutedTransactionIds.AddRange(inlineTxIds); var block = new Block { From 8291fb1aac15fd4395e746e5660d34fbcc07ed0c Mon Sep 17 00:00:00 2001 From: eanzhao Date: Mon, 11 Nov 2024 11:47:06 +0800 Subject: [PATCH 15/83] Fix block sync issue. --- .../Application/BlockExecutingService.cs | 9 +++++++-- .../Application/TransactionValidationService.cs | 4 ++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/AElf.Kernel.SmartContractExecution/Application/BlockExecutingService.cs b/src/AElf.Kernel.SmartContractExecution/Application/BlockExecutingService.cs index 3fe89db6bc..e7538a59b0 100644 --- a/src/AElf.Kernel.SmartContractExecution/Application/BlockExecutingService.cs +++ b/src/AElf.Kernel.SmartContractExecution/Application/BlockExecutingService.cs @@ -55,8 +55,13 @@ public async Task ExecuteBlockAsync(BlockHeader blockHeader, CancellationToken cancellationToken) { Logger.LogTrace("Entered ExecuteBlockAsync"); - var nonCancellable = nonCancellableTransactions.ToList(); - var cancellable = cancellableTransactions.ToList(); + + var nonCancellable = nonCancellableTransactions.ToList() + .Where(tx => !tx.MethodName.Contains('.')).ToList(); + + var cancellable = cancellableTransactions.ToList() + .Where(tx => !tx.MethodName.Contains('.')).ToList(); + var nonCancellableReturnSets = await _transactionExecutingService.ExecuteAsync( new TransactionExecutingDto { BlockHeader = blockHeader, Transactions = nonCancellable }, diff --git a/src/AElf.Kernel.TransactionPool/Application/TransactionValidationService.cs b/src/AElf.Kernel.TransactionPool/Application/TransactionValidationService.cs index 324cfb14d6..9d05ed5b19 100644 --- a/src/AElf.Kernel.TransactionPool/Application/TransactionValidationService.cs +++ b/src/AElf.Kernel.TransactionPool/Application/TransactionValidationService.cs @@ -49,6 +49,10 @@ public async Task ValidateTransactionWhileCollectingAsync(IChainContext ch public async Task ValidateTransactionWhileSyncingAsync(Transaction transaction) { + if (transaction.MethodName.Contains('.')) + { + return true; + } var validationTasks = _transactionValidationProviders.AsParallel() .Where(provider => provider.ValidateWhileSyncing).Select(async provider => { From 1ac04354c5e5e3b6aa70d084d8f3d6b4068f3756 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Tue, 12 Nov 2024 15:19:33 +0800 Subject: [PATCH 16/83] 1. Remove useless comments 2. Add an execution limit for inline transactions 3. Improve compatibility in inline method validation. --- ...DPoSContract_ProcessConsensusInformation.cs | 3 --- .../TokenContract_Helper.cs | 8 +++++++- .../Extensions/TransactionExtensions.cs | 4 ++++ .../PlainTransactionExecutingService.cs | 4 ++++ .../Dto/SingleTransactionExecutingDto.cs | 1 + .../ITransactionContext.cs | 1 + .../InlineWithTransactionIdCounter.cs | 18 ++++++++++++++++++ .../TransactionContext.cs | 1 + src/AElf.Runtime.CSharp/Executive.cs | 7 +++++++ src/AElf.Runtime.CSharp/TransactionConsts.cs | 6 ++++++ 10 files changed, 49 insertions(+), 4 deletions(-) create mode 100644 src/AElf.Kernel.SmartContract/InlineWithTransactionIdCounter.cs create mode 100644 src/AElf.Runtime.CSharp/TransactionConsts.cs diff --git a/contract/AElf.Contracts.Consensus.AEDPoS/AEDPoSContract_ProcessConsensusInformation.cs b/contract/AElf.Contracts.Consensus.AEDPoS/AEDPoSContract_ProcessConsensusInformation.cs index 0a01c8cf52..c51602a302 100644 --- a/contract/AElf.Contracts.Consensus.AEDPoS/AEDPoSContract_ProcessConsensusInformation.cs +++ b/contract/AElf.Contracts.Consensus.AEDPoS/AEDPoSContract_ProcessConsensusInformation.cs @@ -84,9 +84,6 @@ private void ProcessConsensusInformation(dynamic input, [CallerMemberName] strin // Clear cache. _processingBlockMinerPubkey = null; - - // TODO: Clear this if feature verified. - Context.SendInline(Context.Self, $".{nameof(DoNothing)}", new Empty()); } public override Empty DoNothing(Empty input) diff --git a/contract/AElf.Contracts.MultiToken/TokenContract_Helper.cs b/contract/AElf.Contracts.MultiToken/TokenContract_Helper.cs index 3a78c60cbe..f318c9fd27 100644 --- a/contract/AElf.Contracts.MultiToken/TokenContract_Helper.cs +++ b/contract/AElf.Contracts.MultiToken/TokenContract_Helper.cs @@ -215,10 +215,16 @@ private Address ExtractTokenContractAddress(ByteString bytes) private void AssertCrossChainTransaction(Transaction originalTransaction, Address validAddress, params string[] validMethodNames) { - var validateResult = validMethodNames.Contains(originalTransaction.MethodName) + var validateResult = validMethodNames.Contains(MaybeRecoverInlineTransactionFunctionName(originalTransaction.MethodName)) && originalTransaction.To == validAddress; Assert(validateResult, "Invalid transaction."); } + + private static string MaybeRecoverInlineTransactionFunctionName(string methodName) + { + var parts = methodName.Split('.'); + return parts.Length > 1 ? parts[^2] : methodName; + } private void RegisterTokenInfo(TokenInfo tokenInfo) { diff --git a/src/AElf.Kernel.Core/Extensions/TransactionExtensions.cs b/src/AElf.Kernel.Core/Extensions/TransactionExtensions.cs index 4c3e8e3242..502fc619e3 100644 --- a/src/AElf.Kernel.Core/Extensions/TransactionExtensions.cs +++ b/src/AElf.Kernel.Core/Extensions/TransactionExtensions.cs @@ -16,6 +16,10 @@ public static int Size(this Transaction transaction) public static bool VerifySignature(this Transaction transaction) { + if (transaction.MethodName.Contains('.')) + { + return true; + } if (!transaction.VerifyFields()) return false; diff --git a/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs b/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs index b4369eaeaf..23c58fb879 100644 --- a/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs +++ b/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs @@ -66,6 +66,7 @@ public async Task> ExecuteAsync(TransactionExecutingDto var singleTxExecutingDto = new SingleTransactionExecutingDto { Depth = 0, + InlineWithTransactionIdCounter = new InlineWithTransactionIdCounter(), ChainContext = groupChainContext, Transaction = transaction, CurrentBlockTime = transactionExecutingDto.BlockHeader.Time, @@ -241,6 +242,7 @@ private async Task ExecuteInlineTransactions(int depth, Timestamp currentBlockTi var needTxId = NeedTransactionId(inlineTx.MethodName); if (needTxId) { + txContext.InlineWithTransactionIdCounter.Increment(); if (!methodNameCount.TryAdd(inlineTx.MethodName, 0)) { methodNameCount[inlineTx.MethodName]++; @@ -266,6 +268,7 @@ private async Task ExecuteInlineTransactions(int depth, Timestamp currentBlockTi var singleTxExecutingDto = new SingleTransactionExecutingDto { Depth = depth + 1, + InlineWithTransactionIdCounter = txContext.InlineWithTransactionIdCounter, ChainContext = internalChainContext, Transaction = inlineTx, CurrentBlockTime = currentBlockTime, @@ -568,6 +571,7 @@ protected ITransactionContext CreateTransactionContext(SingleTransactionExecutin singleTxExecutingDto.ChainContext, singleTxExecutingDto.OriginTransactionId, origin, singleTxExecutingDto.Depth, singleTxExecutingDto.CurrentBlockTime); + txContext.InlineWithTransactionIdCounter = singleTxExecutingDto.InlineWithTransactionIdCounter; return txContext; } } \ No newline at end of file diff --git a/src/AElf.Kernel.SmartContract/Dto/SingleTransactionExecutingDto.cs b/src/AElf.Kernel.SmartContract/Dto/SingleTransactionExecutingDto.cs index 7dfe93020b..9c50702cfa 100644 --- a/src/AElf.Kernel.SmartContract/Dto/SingleTransactionExecutingDto.cs +++ b/src/AElf.Kernel.SmartContract/Dto/SingleTransactionExecutingDto.cs @@ -13,4 +13,5 @@ public class SingleTransactionExecutingDto public bool IsCancellable { get; set; } = true; public Hash OriginTransactionId { get; set; } + public InlineWithTransactionIdCounter InlineWithTransactionIdCounter { get; set; } } \ No newline at end of file diff --git a/src/AElf.Kernel.SmartContract/ITransactionContext.cs b/src/AElf.Kernel.SmartContract/ITransactionContext.cs index 0f1a3cecad..1d4ab59fbe 100644 --- a/src/AElf.Kernel.SmartContract/ITransactionContext.cs +++ b/src/AElf.Kernel.SmartContract/ITransactionContext.cs @@ -16,4 +16,5 @@ public interface ITransactionContext Transaction Transaction { get; set; } TransactionTrace Trace { get; set; } IStateCache StateCache { get; set; } + InlineWithTransactionIdCounter InlineWithTransactionIdCounter { get; set; } } \ No newline at end of file diff --git a/src/AElf.Kernel.SmartContract/InlineWithTransactionIdCounter.cs b/src/AElf.Kernel.SmartContract/InlineWithTransactionIdCounter.cs new file mode 100644 index 0000000000..1ae06c2504 --- /dev/null +++ b/src/AElf.Kernel.SmartContract/InlineWithTransactionIdCounter.cs @@ -0,0 +1,18 @@ +using System.Threading; + +namespace AElf.Kernel.SmartContract; + +public class InlineWithTransactionIdCounter +{ + private int _count = 0; + + public void Increment() + { + Interlocked.Increment(ref _count); + } + + public int GetCount() + { + return _count; + } +} \ No newline at end of file diff --git a/src/AElf.Kernel.SmartContract/TransactionContext.cs b/src/AElf.Kernel.SmartContract/TransactionContext.cs index aaf3fe79e6..2e76fcf5b1 100644 --- a/src/AElf.Kernel.SmartContract/TransactionContext.cs +++ b/src/AElf.Kernel.SmartContract/TransactionContext.cs @@ -16,4 +16,5 @@ public class TransactionContext : ITransactionContext public Transaction Transaction { get; set; } public TransactionTrace Trace { get; set; } public IStateCache StateCache { get; set; } + public InlineWithTransactionIdCounter InlineWithTransactionIdCounter { get; set; } } \ No newline at end of file diff --git a/src/AElf.Runtime.CSharp/Executive.cs b/src/AElf.Runtime.CSharp/Executive.cs index 6cb47187c6..d8a3acd692 100644 --- a/src/AElf.Runtime.CSharp/Executive.cs +++ b/src/AElf.Runtime.CSharp/Executive.cs @@ -63,6 +63,13 @@ public Task ApplyAsync(ITransactionContext transactionContext) CurrentTransactionContext.Trace.Error = "\n" + "ExceededMaxCallDepth"; return Task.CompletedTask; } + if (CurrentTransactionContext.InlineWithTransactionIdCounter != null + && CurrentTransactionContext.InlineWithTransactionIdCounter.GetCount() > TransactionConsts.InlineWithTransactionIdLimit) + { + CurrentTransactionContext.Trace.ExecutionStatus = ExecutionStatus.ExceededMaxCallDepth; + CurrentTransactionContext.Trace.Error = "\n" + "failed.ExceededMaxInlineWithTransactionIdCount"; + return Task.CompletedTask; + } Execute(); } diff --git a/src/AElf.Runtime.CSharp/TransactionConsts.cs b/src/AElf.Runtime.CSharp/TransactionConsts.cs new file mode 100644 index 0000000000..06e85b9d73 --- /dev/null +++ b/src/AElf.Runtime.CSharp/TransactionConsts.cs @@ -0,0 +1,6 @@ +namespace AElf.Runtime.CSharp; + +public class TransactionConsts +{ + public const int InlineWithTransactionIdLimit = 5; +} \ No newline at end of file From 0b3ab876942f5cbbaa7ea61e7d0e0c39f6b0c992 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Tue, 12 Nov 2024 17:13:10 +0800 Subject: [PATCH 17/83] Cancel inline event log --- .../PlainTransactionExecutingService.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs b/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs index 23c58fb879..a526f74082 100644 --- a/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs +++ b/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs @@ -494,14 +494,14 @@ private IEnumerable GetReturnSet(TransactionTrace trace, Tra Logger.LogWarning($"Inline tx id: {inlineTx.GetHash().ToHex()}\n{inlineTx}"); // TODO: Maybe we need to add a new log for inline tx with id created. - var log = new VirtualTransactionCreated - { - From = inlineTx.From, - To = inlineTx.To, - MethodName = inlineTx.MethodName, - Params = inlineTx.Params, - }; - returnSet.TransactionResult.Logs.Add(log.ToLogEvent(inlineTx.To)); + // var log = new VirtualTransactionCreated + // { + // From = inlineTx.From, + // To = inlineTx.To, + // MethodName = inlineTx.MethodName, + // Params = inlineTx.Params, + // }; + // returnSet.TransactionResult.Logs.Add(log.ToLogEvent(inlineTx.To)); } } else From 8626f56e6287febcb39b6c2e49b0a22adbfaa029 Mon Sep 17 00:00:00 2001 From: "jim.dong" Date: Tue, 12 Nov 2024 19:08:19 +0800 Subject: [PATCH 18/83] extend seed expiration time --- .../TokenContract_Actions.cs | 10 ++++++++++ protobuf/token_contract_impl.proto | 8 ++++++++ .../BVT/TokenApplicationTests.cs | 11 +++++++++++ .../MultiTokenContractTestBase.cs | 3 +++ 4 files changed, 32 insertions(+) diff --git a/contract/AElf.Contracts.MultiToken/TokenContract_Actions.cs b/contract/AElf.Contracts.MultiToken/TokenContract_Actions.cs index 6adcf01a2a..c1f3738024 100644 --- a/contract/AElf.Contracts.MultiToken/TokenContract_Actions.cs +++ b/contract/AElf.Contracts.MultiToken/TokenContract_Actions.cs @@ -691,6 +691,16 @@ public override Int32Value GetMaxBatchApproveCount(Empty input) }; } + public override Empty ExtendSeedExpirationTime(ExtendSeedExpirationTimeInput input) + { + var tokenInfo = GetTokenInfo(input.Symbol); + Assert(tokenInfo != null, "Seed NFT does not exist."); + Assert(tokenInfo.Owner == Context.Sender, "Sender is not Seed NFT owner."); + + tokenInfo.ExternalInfo.Value["__seed_exp_time"] = input.ExpirationTime; + return base.ExtendSeedExpirationTime(input); + } + private int GetMaxBatchApproveCount() { return State.MaxBatchApproveCount.Value == 0 diff --git a/protobuf/token_contract_impl.proto b/protobuf/token_contract_impl.proto index 5885914e80..7a6e76247f 100644 --- a/protobuf/token_contract_impl.proto +++ b/protobuf/token_contract_impl.proto @@ -182,6 +182,9 @@ service TokenContractImpl { rpc GetMaxBatchApproveCount (google.protobuf.Empty) returns (google.protobuf.Int32Value) { } + + rpc ExtendSeedExpirationTime (ExtendSeedExpirationTimeInput) returns (google.protobuf.Empty) { + } } message AdvanceResourceTokenInput { @@ -444,4 +447,9 @@ message ModifyTokenIssuerAndOwnerInput { message SetTokenIssuerAndOwnerModificationEnabledInput{ bool enabled = 1; +} + +message ExtendSeedExpirationTimeInput { + string symbol = 1; + int64 expiration_time = 2; } \ No newline at end of file diff --git a/test/AElf.Contracts.MultiToken.Tests/BVT/TokenApplicationTests.cs b/test/AElf.Contracts.MultiToken.Tests/BVT/TokenApplicationTests.cs index 201e56d6e6..24d06e3eec 100644 --- a/test/AElf.Contracts.MultiToken.Tests/BVT/TokenApplicationTests.cs +++ b/test/AElf.Contracts.MultiToken.Tests/BVT/TokenApplicationTests.cs @@ -1893,4 +1893,15 @@ public async Task TokenIssuerAndOwnerModification_Test() result.TransactionResult.Error.ShouldContain("Set token issuer and owner disabled."); } + + [Theory] + [InlineData("SEED-0", 1731927992000)] + public async Task ExtendSeedExpirationTime_Test(string symbol, long expirationTime) + { + ExtendSeedExpirationTimeInput input = new ExtendSeedExpirationTimeInput(); + input.Symbol = symbol; + input.ExpirationTime = expirationTime; + + await TokenContractStub.ExtendSeedExpirationTime.CallAsync(input); + } } \ No newline at end of file diff --git a/test/AElf.Contracts.MultiToken.Tests/MultiTokenContractTestBase.cs b/test/AElf.Contracts.MultiToken.Tests/MultiTokenContractTestBase.cs index 232a5f5b8b..62a7f23ec6 100644 --- a/test/AElf.Contracts.MultiToken.Tests/MultiTokenContractTestBase.cs +++ b/test/AElf.Contracts.MultiToken.Tests/MultiTokenContractTestBase.cs @@ -240,4 +240,7 @@ internal async Task> CreateMutiTokenWithExceptionAsync( await CreateSeedNftAsync(stub, createInput); return await stub.Create.SendWithExceptionAsync(createInput); } + + + } \ No newline at end of file From 54fb07d8b67e4caabf02fb8d9716eeb17756f6d4 Mon Sep 17 00:00:00 2001 From: "jim.dong" Date: Wed, 13 Nov 2024 22:46:08 +0800 Subject: [PATCH 19/83] extend SEED expiration time --- contract/AElf.Contracts.MultiToken/TokenContract_Actions.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/contract/AElf.Contracts.MultiToken/TokenContract_Actions.cs b/contract/AElf.Contracts.MultiToken/TokenContract_Actions.cs index c1f3738024..7c5b33b300 100644 --- a/contract/AElf.Contracts.MultiToken/TokenContract_Actions.cs +++ b/contract/AElf.Contracts.MultiToken/TokenContract_Actions.cs @@ -697,8 +697,10 @@ public override Empty ExtendSeedExpirationTime(ExtendSeedExpirationTimeInput inp Assert(tokenInfo != null, "Seed NFT does not exist."); Assert(tokenInfo.Owner == Context.Sender, "Sender is not Seed NFT owner."); - tokenInfo.ExternalInfo.Value["__seed_exp_time"] = input.ExpirationTime; - return base.ExtendSeedExpirationTime(input); + tokenInfo.ExternalInfo.Value[TokenContractConstants.SeedExpireTimeExternalInfoKey] = input.ExpirationTime.ToString(); + State.TokenInfos[input.Symbol] = tokenInfo; + base.ExtendSeedExpirationTime(input); + return new Empty(); } private int GetMaxBatchApproveCount() From 1e7c9875393c2774a8a43f808127546662648e2e Mon Sep 17 00:00:00 2001 From: "jim.dong" Date: Wed, 13 Nov 2024 23:17:57 +0800 Subject: [PATCH 20/83] transaction result status optimization, clear return the expired description --- protobuf/aelf/core.proto | 2 ++ .../Services/TransactionResultAppService.cs | 11 +++++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/protobuf/aelf/core.proto b/protobuf/aelf/core.proto index 4fe3a5bcf4..24fe381877 100644 --- a/protobuf/aelf/core.proto +++ b/protobuf/aelf/core.proto @@ -59,6 +59,8 @@ enum TransactionResultStatus { PENDING_VALIDATION = 5; // Transaction validation failed. NODE_VALIDATION_FAILED = 6; + // Transaction is expired and will never succeed + EXPIRED = 7; } message TransactionResult { diff --git a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs index 483dbb4366..ad47c41223 100644 --- a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs +++ b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs @@ -118,9 +118,16 @@ await _transactionResultProxyService.InvalidTransactionResultService.GetInvalidT return output; } } - - return output; + switch (output.BlockNumber - output.Transaction.RefBlockNumber) + { + case > KernelConstants.ReferenceBlockValidPeriod: + output.Status = TransactionResultStatus.Expired.ToString().ToUpper(); + output.Error = TransactionErrorResolver.TakeErrorMessage(TransactionResultStatus.Expired.ToString(), _webAppOptions.IsDebugMode); + return output; + default: + return output; + } } /// From 8ec60e333b190b43eaf14684b07412c47b0dd686 Mon Sep 17 00:00:00 2001 From: eanzhao Date: Thu, 14 Nov 2024 11:07:42 +0800 Subject: [PATCH 21/83] Fixed GetTransactionResultAsync: compare BestChainHeight with RefBlockNumber --- .../Services/TransactionResultAppService.cs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs index ad47c41223..1871e17a1c 100644 --- a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs +++ b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs @@ -118,16 +118,17 @@ await _transactionResultProxyService.InvalidTransactionResultService.GetInvalidT return output; } } - - switch (output.BlockNumber - output.Transaction.RefBlockNumber) + + var chain = await _blockchainService.GetChainAsync(); + if (chain.BestChainHeight - output.Transaction.RefBlockNumber > KernelConstants.ReferenceBlockValidPeriod) { - case > KernelConstants.ReferenceBlockValidPeriod: - output.Status = TransactionResultStatus.Expired.ToString().ToUpper(); - output.Error = TransactionErrorResolver.TakeErrorMessage(TransactionResultStatus.Expired.ToString(), _webAppOptions.IsDebugMode); - return output; - default: - return output; + output.Status = TransactionResultStatus.Expired.ToString().ToUpper(); + output.Error = TransactionErrorResolver.TakeErrorMessage(TransactionResultStatus.Expired.ToString(), + _webAppOptions.IsDebugMode); + return output; } + + return output; } /// From daaec051dbed7dae9eaadf947ff57d5fafd5581a Mon Sep 17 00:00:00 2001 From: "jim.dong" Date: Thu, 14 Nov 2024 14:58:51 +0800 Subject: [PATCH 22/83] optimize the result of transaction result --- .../Services/TransactionResultAppService.cs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs index 1871e17a1c..3eaae35f99 100644 --- a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs +++ b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs @@ -122,12 +122,11 @@ await _transactionResultProxyService.InvalidTransactionResultService.GetInvalidT var chain = await _blockchainService.GetChainAsync(); if (chain.BestChainHeight - output.Transaction.RefBlockNumber > KernelConstants.ReferenceBlockValidPeriod) { - output.Status = TransactionResultStatus.Expired.ToString().ToUpper(); - output.Error = TransactionErrorResolver.TakeErrorMessage(TransactionResultStatus.Expired.ToString(), - _webAppOptions.IsDebugMode); - return output; + output.Status = TransactionResultStatus.Expired.ToString().ToUpper(); + output.Error = TransactionErrorResolver.TakeErrorMessage(TransactionResultStatus.Expired.ToString(), + _webAppOptions.IsDebugMode); + return output; } - return output; } From 1ad4d469e89961253e7096d03a91c46f9101b02d Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Thu, 14 Nov 2024 19:00:23 +0800 Subject: [PATCH 23/83] support zk --- .../AElf.CSharp.CodeOps.csproj | 2 + .../Module/CallAndBranchCounts/Patcher.cs | 16 +- .../Module/ContractStructureValidator.cs | 2 + .../IExecutionObserverThresholdProvider.cs | 2 +- .../SmartContractConstants.cs | 2 +- .../AElf.Runtime.CSharp.csproj | 3 + .../AElf.Sdk.CSharp.Internal.csproj | 1 - .../CSharpSmartContractContextTests.cs | 10 - test/AElf.Types.Tests/BigIntegerTest.cs | 176 ++++++++++++++++++ 9 files changed, 200 insertions(+), 14 deletions(-) create mode 100644 test/AElf.Types.Tests/BigIntegerTest.cs diff --git a/src/AElf.CSharp.CodeOps/AElf.CSharp.CodeOps.csproj b/src/AElf.CSharp.CodeOps/AElf.CSharp.CodeOps.csproj index e4cd5517c8..d931ee9e76 100644 --- a/src/AElf.CSharp.CodeOps/AElf.CSharp.CodeOps.csproj +++ b/src/AElf.CSharp.CodeOps/AElf.CSharp.CodeOps.csproj @@ -10,6 +10,8 @@ + + diff --git a/src/AElf.CSharp.CodeOps/Patchers/Module/CallAndBranchCounts/Patcher.cs b/src/AElf.CSharp.CodeOps/Patchers/Module/CallAndBranchCounts/Patcher.cs index bdac2a7575..09b8581feb 100644 --- a/src/AElf.CSharp.CodeOps/Patchers/Module/CallAndBranchCounts/Patcher.cs +++ b/src/AElf.CSharp.CodeOps/Patchers/Module/CallAndBranchCounts/Patcher.cs @@ -17,7 +17,7 @@ public void Patch(ModuleDefinition module) return; // ReSharper disable once IdentifierTypo - var nmspace = module.Types.Single(m => m.BaseType is TypeDefinition).Namespace; + var nmspace = module.Types.Where(IsContractType).Single().Namespace; var proxyBuilder = new Patch(module, nmspace); @@ -28,6 +28,20 @@ public void Patch(ModuleDefinition module) module.Types.Add(proxyBuilder.ObserverType); } + private static bool IsContractType(TypeDefinition type) + { + if (type.FullName.StartsWith("AElf.Sdk.CSharp.CSharpSmartContract`1")) + return true; + if (type.BaseType is TypeDefinition baseType) + return IsContractType(baseType); + if(type.BaseType is GenericInstanceType baseType0) + return IsContractType(baseType0); + return false; + } + private static bool IsContractType(GenericInstanceType type) + { + return type.FullName.StartsWith("AElf.Sdk.CSharp.CSharpSmartContract`1"); + } } internal class MethodPatcher diff --git a/src/AElf.CSharp.CodeOps/Validators/Module/ContractStructureValidator.cs b/src/AElf.CSharp.CodeOps/Validators/Module/ContractStructureValidator.cs index 59f4209d5a..5fb83cd951 100644 --- a/src/AElf.CSharp.CodeOps/Validators/Module/ContractStructureValidator.cs +++ b/src/AElf.CSharp.CodeOps/Validators/Module/ContractStructureValidator.cs @@ -231,6 +231,8 @@ private bool IsBadStateField(FieldDefinition field) if (_allowedStateTypes.Contains(field.FieldType.FullName)) return false; + if(field.FieldType.Resolve().BaseType.FullName == typeof(StructuredState).FullName) + return false; // If not ContractReferenceState then it is not allowed return field.FieldType.Resolve().BaseType.FullName != typeof(ContractReferenceState).FullName; } diff --git a/src/AElf.Kernel.SmartContract/Application/IExecutionObserverThresholdProvider.cs b/src/AElf.Kernel.SmartContract/Application/IExecutionObserverThresholdProvider.cs index 22df31d5a3..1515ab0c20 100644 --- a/src/AElf.Kernel.SmartContract/Application/IExecutionObserverThresholdProvider.cs +++ b/src/AElf.Kernel.SmartContract/Application/IExecutionObserverThresholdProvider.cs @@ -33,7 +33,7 @@ public IExecutionObserverThreshold GetExecutionObserverThreshold(IBlockIndex blo var branchCountObserverThreshold = GetBlockExecutedData(blockIndex, BranchCountThresholdKey)?.Value ?? SmartContractConstants.ExecutionBranchThreshold; var callCountObserverThreshold = GetBlockExecutedData(blockIndex, CallCountThresholdKey)?.Value ?? - SmartContractConstants.ExecutionBranchThreshold; + SmartContractConstants.ExecutionCallThreshold; return new ExecutionObserverThreshold { ExecutionBranchThreshold = branchCountObserverThreshold, diff --git a/src/AElf.Kernel.SmartContract/SmartContractConstants.cs b/src/AElf.Kernel.SmartContract/SmartContractConstants.cs index 9a210289ce..0260dc8bbb 100644 --- a/src/AElf.Kernel.SmartContract/SmartContractConstants.cs +++ b/src/AElf.Kernel.SmartContract/SmartContractConstants.cs @@ -2,7 +2,7 @@ namespace AElf.Kernel.SmartContract; public class SmartContractConstants { - public const int ExecutionCallThreshold = 15000; + public const int ExecutionCallThreshold = 80000; public const int ExecutionBranchThreshold = 15000; diff --git a/src/AElf.Runtime.CSharp/AElf.Runtime.CSharp.csproj b/src/AElf.Runtime.CSharp/AElf.Runtime.CSharp.csproj index bf9914645e..122d0af0b5 100644 --- a/src/AElf.Runtime.CSharp/AElf.Runtime.CSharp.csproj +++ b/src/AElf.Runtime.CSharp/AElf.Runtime.CSharp.csproj @@ -22,6 +22,9 @@ + + + diff --git a/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj b/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj index 39b69c4352..ff42c2fa80 100644 --- a/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj +++ b/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj @@ -10,7 +10,6 @@ - all diff --git a/test/AElf.Sdk.CSharp.Tests/CSharpSmartContractContextTests.cs b/test/AElf.Sdk.CSharp.Tests/CSharpSmartContractContextTests.cs index 48dcf22768..bdac3de919 100644 --- a/test/AElf.Sdk.CSharp.Tests/CSharpSmartContractContextTests.cs +++ b/test/AElf.Sdk.CSharp.Tests/CSharpSmartContractContextTests.cs @@ -46,16 +46,6 @@ public void Verify_Ed25519Verify() ByteArrayHelper.HexStringToByteArray(message1), ByteArrayHelper.HexStringToByteArray(publicKey1))); - // var contractContext2 = new CSharpSmartContractContext(bridgeContext); - // var publicKey2 = "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c"; - // var message2 = "72"; - // var signature2 = "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00"; - // var ed25519VerifyResult2 = contractContext2.Ed25519Verify( - // ByteArrayHelper.HexStringToByteArray(signature2), - // ByteArrayHelper.HexStringToByteArray(message2), - // ByteArrayHelper.HexStringToByteArray(publicKey2)); - // ed25519VerifyResult2.ShouldBe(true); - } [Fact] diff --git a/test/AElf.Types.Tests/BigIntegerTest.cs b/test/AElf.Types.Tests/BigIntegerTest.cs new file mode 100644 index 0000000000..056fcca2a9 --- /dev/null +++ b/test/AElf.Types.Tests/BigIntegerTest.cs @@ -0,0 +1,176 @@ +using System; +using System.Numerics; +using Xunit; + +namespace AElf.Types.Tests; + +public class BigIntegerTest +{ + [Fact] + public void Zero_Should_Be_Zero() + { + var zero = BigIntValue.Zero; + Assert.Equal("0", zero.Value); + } + + [Fact] + public void One_Should_Be_One() + { + var one = BigIntValue.One; + Assert.Equal("1", one.Value); + } + + [Fact] + public void BigIntValue_FromBigEndianBytes_Should_Work() + { + var bytes = new byte[] { 0x01, 0x00 }; // 256 in big endian + var bigIntValue = BigIntValue.FromBigEndianBytes(bytes); + Assert.Equal("256", bigIntValue.Value); + } + + [Fact] + public void ToBigEndianBytes_Should_Work() + { + var bigIntValue = new BigIntValue { Value = "256" }; + var bytes = bigIntValue.ToBigEndianBytes(); + Assert.Equal(new byte[] { 0x01, 0x00 }, bytes); + } + + [Theory] + [InlineData("123", "123", 0)] + [InlineData("123", "456", -1)] + [InlineData("456", "123", 1)] + public void CompareTo_Should_Correctly_Compare(string a, string b, int expected) + { + var bigIntValueA = new BigIntValue { Value = a }; + var bigIntValueB = new BigIntValue { Value = b }; + + Assert.Equal(expected, bigIntValueA.CompareTo(bigIntValueB)); + } + + [Fact] + public void Implicit_Conversion_From_String_Should_Work() + { + BigIntValue bigIntValue = "123"; + Assert.Equal("123", bigIntValue.Value); + } + + [Fact] + public void Implicit_Conversion_From_Long_Should_Work() + { + BigIntValue bigIntValue = 456L; + Assert.Equal("456", bigIntValue.Value); + } + + [Fact] + public void Addition_Operator_Should_Work() + { + BigIntValue a = "123"; + BigIntValue b = "456"; + BigIntValue result = a + b; + Assert.Equal("579", result.Value); + } + + [Fact] + public void Subtraction_Operator_Should_Work() + { + BigIntValue a = "123"; + BigIntValue b = "23"; + BigIntValue result = a - b; + Assert.Equal("100", result.Value); + } + + [Fact] + public void Multiplication_Operator_Should_Work() + { + BigIntValue a = "10"; + BigIntValue b = "20"; + BigIntValue result = a * b; + Assert.Equal("200", result.Value); + } + + [Fact] + public void Modulus_Operator_Should_Work() + { + BigIntValue a = "10"; + BigIntValue b = "3"; + BigIntValue result = a % b; + Assert.Equal("1", result.Value); + } + + [Fact] + public void Equality_Operator_Should_Work() + { + BigIntValue a = "123"; + BigIntValue b = "123"; + Assert.True(a == b); + + BigIntValue c = "456"; + Assert.False(a == c); + } + + [Fact] + public void Inequality_Operator_Should_Work() + { + BigIntValue a = "123"; + BigIntValue b = "456"; + Assert.True(a != b); + + BigIntValue c = "123"; + Assert.False(a != c); + } + + [Fact] + public void LessThanOperator_Should_Work() + { + BigIntValue a = "123"; + BigIntValue b = "456"; + Assert.True(a < b); + Assert.False(b < a); + } + + [Fact] + public void GreaterThanOperator_Should_Work() + { + BigIntValue a = "456"; + BigIntValue b = "123"; + Assert.True(a > b); + Assert.False(b > a); + } + + [Fact] + public void LessThanOrEqualOperator_Should_Work() + { + BigIntValue a = "123"; + BigIntValue b = "123"; + BigIntValue c = "456"; + Assert.True(a <= b); + Assert.True(a <= c); + Assert.False(c <= a); + } + + [Fact] + public void GreaterThanOrEqualOperator_Should_Work() + { + BigIntValue a = "123"; + BigIntValue b = "123"; + BigIntValue c = "456"; + Assert.True(a >= b); + Assert.True(c >= a); + Assert.False(a >= c); + } + + [Theory] + [InlineData("0", 0)] + [InlineData("123456789", 123456789)] + [InlineData("-987654321", -987654321)] + [InlineData("1_000_000_000", 1000000000)] + [InlineData("-1_234_567", -1234567)] + public void ConvertStringToBigInteger_ValidStrings_Should_ParseCorrectly(string input, long expected) + { + BigIntValue bigIntValue = input; + BigInteger result = bigIntValue; // Implicit conversion to BigInteger + Assert.Equal(new BigInteger(expected), result); + } + +} \ No newline at end of file From 8c4234ab85be2b501741d3e1b72c356a683b729e Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Fri, 15 Nov 2024 08:54:41 +0800 Subject: [PATCH 24/83] Resolve unit test issue --- .../UnitTestPlainTransactionExecutingService.cs | 5 +++-- .../Service/PlainTransactionExecutingAsPluginService.cs | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/AElf.ContractTestKit.AEDPoSExtension/UnitTestPlainTransactionExecutingService.cs b/src/AElf.ContractTestKit.AEDPoSExtension/UnitTestPlainTransactionExecutingService.cs index 37f1b50c43..c3eabef06d 100644 --- a/src/AElf.ContractTestKit.AEDPoSExtension/UnitTestPlainTransactionExecutingService.cs +++ b/src/AElf.ContractTestKit.AEDPoSExtension/UnitTestPlainTransactionExecutingService.cs @@ -2,6 +2,7 @@ using System.Threading; using System.Threading.Tasks; using AElf.Kernel; +using AElf.Kernel.Blockchain.Application; using AElf.Kernel.FeatureDisable.Core; using AElf.Kernel.SmartContract; using AElf.Kernel.SmartContract.Application; @@ -13,8 +14,8 @@ public class UnitTestPlainTransactionExecutingService : PlainTransactionExecutin { public UnitTestPlainTransactionExecutingService(ISmartContractExecutiveService smartContractExecutiveService, IEnumerable postPlugins, IEnumerable prePlugins, - ITransactionContextFactory transactionContextFactory, IFeatureDisableService featureDisableService) : base( - smartContractExecutiveService, postPlugins, prePlugins, transactionContextFactory, featureDisableService) + ITransactionContextFactory transactionContextFactory, IFeatureDisableService featureDisableService,IBlockchainService blockchainService) : base( + smartContractExecutiveService, postPlugins, prePlugins, transactionContextFactory, featureDisableService,blockchainService) { } diff --git a/test/AElf.Kernel.SmartContract.ExecutionPluginForMethodFee.Tests/Service/PlainTransactionExecutingAsPluginService.cs b/test/AElf.Kernel.SmartContract.ExecutionPluginForMethodFee.Tests/Service/PlainTransactionExecutingAsPluginService.cs index f43cef0e42..cdda3f9e59 100644 --- a/test/AElf.Kernel.SmartContract.ExecutionPluginForMethodFee.Tests/Service/PlainTransactionExecutingAsPluginService.cs +++ b/test/AElf.Kernel.SmartContract.ExecutionPluginForMethodFee.Tests/Service/PlainTransactionExecutingAsPluginService.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using AElf.Kernel.Blockchain.Application; using AElf.Kernel.FeatureDisable.Core; using AElf.Kernel.SmartContract.Application; using AElf.Kernel.SmartContract.Domain; @@ -21,8 +22,8 @@ public class PlainTransactionExecutingAsPluginService : PlainTransactionExecutin public PlainTransactionExecutingAsPluginService (ISmartContractExecutiveService smartContractExecutiveService, IEnumerable postPlugins, IEnumerable prePlugins, - ITransactionContextFactory transactionContextFactory, IFeatureDisableService featureDisableService) : base( - smartContractExecutiveService, postPlugins, prePlugins, transactionContextFactory, featureDisableService) + ITransactionContextFactory transactionContextFactory, IFeatureDisableService featureDisableService, IBlockchainService blockchainService) : base( + smartContractExecutiveService, postPlugins, prePlugins, transactionContextFactory, featureDisableService,blockchainService) { _smartContractExecutiveService = smartContractExecutiveService; } From e1ccdb9b84ec2ce01bfbdca1839a92adb36b69bf Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Fri, 15 Nov 2024 10:55:16 +0800 Subject: [PATCH 25/83] Resolve Verification Failure Issue --- .../Extensions/TransactionExtensions.cs | 11 ++++++++++- .../Application/TransactionValidationService.cs | 3 ++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/AElf.Kernel.Core/Extensions/TransactionExtensions.cs b/src/AElf.Kernel.Core/Extensions/TransactionExtensions.cs index 502fc619e3..6a845b9df4 100644 --- a/src/AElf.Kernel.Core/Extensions/TransactionExtensions.cs +++ b/src/AElf.Kernel.Core/Extensions/TransactionExtensions.cs @@ -16,7 +16,7 @@ public static int Size(this Transaction transaction) public static bool VerifySignature(this Transaction transaction) { - if (transaction.MethodName.Contains('.')) + if (transaction.IsInlineWithTransactionId()) { return true; } @@ -31,7 +31,16 @@ public static bool VerifySignature(this Transaction transaction) public static bool VerifyExpiration(this Transaction transaction, long chainBranchBlockHeight) { + if (transaction.IsInlineWithTransactionId()) + { + return true; + } return transaction.RefBlockNumber <= chainBranchBlockHeight && transaction.GetExpiryBlockNumber() > chainBranchBlockHeight; } + + public static bool IsInlineWithTransactionId(this Transaction transaction) + { + return transaction.MethodName.Contains("."); + } } \ No newline at end of file diff --git a/src/AElf.Kernel.TransactionPool/Application/TransactionValidationService.cs b/src/AElf.Kernel.TransactionPool/Application/TransactionValidationService.cs index 9d05ed5b19..89c90ff36f 100644 --- a/src/AElf.Kernel.TransactionPool/Application/TransactionValidationService.cs +++ b/src/AElf.Kernel.TransactionPool/Application/TransactionValidationService.cs @@ -49,7 +49,8 @@ public async Task ValidateTransactionWhileCollectingAsync(IChainContext ch public async Task ValidateTransactionWhileSyncingAsync(Transaction transaction) { - if (transaction.MethodName.Contains('.')) + Logger.LogInformation("this is right version"); + if (transaction.IsInlineWithTransactionId()) { return true; } From 9df0b200aeece8750c5623ea9d18c821fe590dff Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Fri, 15 Nov 2024 21:45:16 +0800 Subject: [PATCH 26/83] Resolve the difficulty of creating inline transactions by eventlog during receiving --- protobuf/inline_transaction.proto | 15 +++++++++++++++ protobuf/virtual_transaction.proto | 2 +- .../AElf.Kernel.SmartContract.csproj | 3 +++ .../PlainTransactionExecutingService.cs | 16 ++++++---------- .../Application/TransactionValidationService.cs | 1 - 5 files changed, 25 insertions(+), 12 deletions(-) create mode 100644 protobuf/inline_transaction.proto diff --git a/protobuf/inline_transaction.proto b/protobuf/inline_transaction.proto new file mode 100644 index 0000000000..8aa96497fe --- /dev/null +++ b/protobuf/inline_transaction.proto @@ -0,0 +1,15 @@ +syntax = "proto3"; + +option csharp_namespace = "AElf.Types"; + + +import "aelf/core.proto"; +import "aelf/options.proto"; + +service InlineTransaction { +} + +message InlineTransactionCreated { + option (aelf.is_event) = true; + aelf.Transaction transaction = 1 [(aelf.is_indexed) = true]; +} diff --git a/protobuf/virtual_transaction.proto b/protobuf/virtual_transaction.proto index 8abb9db10c..914ef1e76f 100644 --- a/protobuf/virtual_transaction.proto +++ b/protobuf/virtual_transaction.proto @@ -17,4 +17,4 @@ message VirtualTransactionCreated { string method_name = 4 [(aelf.is_indexed) = true]; bytes params = 5; aelf.Address signatory = 6 [(aelf.is_indexed) = true]; -} \ No newline at end of file +} diff --git a/src/AElf.Kernel.SmartContract/AElf.Kernel.SmartContract.csproj b/src/AElf.Kernel.SmartContract/AElf.Kernel.SmartContract.csproj index ab2cf443cf..2358852342 100644 --- a/src/AElf.Kernel.SmartContract/AElf.Kernel.SmartContract.csproj +++ b/src/AElf.Kernel.SmartContract/AElf.Kernel.SmartContract.csproj @@ -22,5 +22,8 @@ Protobuf\Proto\virtual_transaction.proto + + Protobuf\Proto\inline_transaction.proto + \ No newline at end of file diff --git a/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs b/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs index a526f74082..3a3b2c0b00 100644 --- a/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs +++ b/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs @@ -472,7 +472,7 @@ private IEnumerable GetReturnSet(TransactionTrace trace, Tra returnSet = GetReturnSet(returnSet, transactionExecutingStateSets); returnSet.ReturnValue = trace.ReturnValue; - var inlineTxWithIdList = trace.InlineTransactions.Where(tx => NeedTransactionId(tx.MethodName)); + var inlineTxWithIdList = trace.GetAllTransactions().Where(tx => NeedTransactionId(tx.MethodName)); foreach (var inlineTx in inlineTxWithIdList) { var inlineTxId = inlineTx.GetHash(); @@ -493,15 +493,11 @@ private IEnumerable GetReturnSet(TransactionTrace trace, Tra returnSets.Add(inlineReturnSet); Logger.LogWarning($"Inline tx id: {inlineTx.GetHash().ToHex()}\n{inlineTx}"); - // TODO: Maybe we need to add a new log for inline tx with id created. - // var log = new VirtualTransactionCreated - // { - // From = inlineTx.From, - // To = inlineTx.To, - // MethodName = inlineTx.MethodName, - // Params = inlineTx.Params, - // }; - // returnSet.TransactionResult.Logs.Add(log.ToLogEvent(inlineTx.To)); + var log = new InlineTransactionCreated() + { + Transaction = inlineTx + }; + returnSet.TransactionResult.Logs.Add(log.ToLogEvent(inlineTx.To)); } } else diff --git a/src/AElf.Kernel.TransactionPool/Application/TransactionValidationService.cs b/src/AElf.Kernel.TransactionPool/Application/TransactionValidationService.cs index 89c90ff36f..10c4edc1b3 100644 --- a/src/AElf.Kernel.TransactionPool/Application/TransactionValidationService.cs +++ b/src/AElf.Kernel.TransactionPool/Application/TransactionValidationService.cs @@ -49,7 +49,6 @@ public async Task ValidateTransactionWhileCollectingAsync(IChainContext ch public async Task ValidateTransactionWhileSyncingAsync(Transaction transaction) { - Logger.LogInformation("this is right version"); if (transaction.IsInlineWithTransactionId()) { return true; From 5dd5ac88ca3034448d558f75830cc68fd01c5ccb Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Fri, 15 Nov 2024 21:56:54 +0800 Subject: [PATCH 27/83] Rename method name --- .../PlainTransactionExecutingService.cs | 2 +- .../Transaction/TransactionTrace.cs | 20 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs b/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs index 3a3b2c0b00..d3531087cd 100644 --- a/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs +++ b/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs @@ -472,7 +472,7 @@ private IEnumerable GetReturnSet(TransactionTrace trace, Tra returnSet = GetReturnSet(returnSet, transactionExecutingStateSets); returnSet.ReturnValue = trace.ReturnValue; - var inlineTxWithIdList = trace.GetAllTransactions().Where(tx => NeedTransactionId(tx.MethodName)); + var inlineTxWithIdList = trace.GetAllInlineTransactions().Where(tx => NeedTransactionId(tx.MethodName)); foreach (var inlineTx in inlineTxWithIdList) { var inlineTxId = inlineTx.GetHash(); diff --git a/src/AElf.Kernel.Types/Transaction/TransactionTrace.cs b/src/AElf.Kernel.Types/Transaction/TransactionTrace.cs index fbf78286a0..cd1f080432 100644 --- a/src/AElf.Kernel.Types/Transaction/TransactionTrace.cs +++ b/src/AElf.Kernel.Types/Transaction/TransactionTrace.cs @@ -89,4 +89,24 @@ public IEnumerable GetStateSets() foreach (var stateSet in stateSets) yield return stateSet; } } + + public List GetAllInlineTransactions() + { + var transactions = new List(); + var stack = new Stack(); + stack.Push(this); + + while (stack.Count > 0) + { + var currentTrace = stack.Pop(); + transactions.AddRange(currentTrace.InlineTransactions); + if (currentTrace.InlineTraces == null) continue; + foreach (var inlineTrace in currentTrace.InlineTraces) + { + stack.Push(inlineTrace); + } + } + + return transactions; + } } \ No newline at end of file From 6d433e59edaa4b0518af3c91ffbcc46bcb398799 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Mon, 18 Nov 2024 11:04:26 +0800 Subject: [PATCH 28/83] Add unit-test for zk supporting --- .../AElf.Sdk.CSharp.Tests.csproj | 2 + .../CSharpSmartContractContextTests.cs | 123 ++++++++++++++++++ 2 files changed, 125 insertions(+) diff --git a/test/AElf.Sdk.CSharp.Tests/AElf.Sdk.CSharp.Tests.csproj b/test/AElf.Sdk.CSharp.Tests/AElf.Sdk.CSharp.Tests.csproj index 91ff826eca..9a260f1451 100644 --- a/test/AElf.Sdk.CSharp.Tests/AElf.Sdk.CSharp.Tests.csproj +++ b/test/AElf.Sdk.CSharp.Tests/AElf.Sdk.CSharp.Tests.csproj @@ -4,12 +4,14 @@ false + all runtime; build; native; contentfiles; analyzers + diff --git a/test/AElf.Sdk.CSharp.Tests/CSharpSmartContractContextTests.cs b/test/AElf.Sdk.CSharp.Tests/CSharpSmartContractContextTests.cs index bdac3de919..19e57e247b 100644 --- a/test/AElf.Sdk.CSharp.Tests/CSharpSmartContractContextTests.cs +++ b/test/AElf.Sdk.CSharp.Tests/CSharpSmartContractContextTests.cs @@ -4,7 +4,9 @@ using AElf.Kernel.SmartContract; using AElf.Kernel.SmartContract.Application; using AElf.Types; +using Bn254.Net; using Google.Protobuf; +using Nethereum.Util; using Shouldly; using Xunit; using CustomContract = AElf.Runtime.CSharp.Tests.TestContract; @@ -85,4 +87,125 @@ public void Transaction_VerifySignature_Test() var result = bridgeContext.VerifySignature(transaction); result.ShouldBeTrue(); } + + [Fact] + public void keccak256_test() + { + var bridgeContext = GetRequiredService().Create(); + var origin = SampleAddress.AddressList[0]; + var contractContext = new CSharpSmartContractContext(bridgeContext); + byte[] message = System.Text.Encoding.UTF8.GetBytes("Test message"); + var fact = contractContext.Keccak256(message); + var expected = Sha3Keccack.Current.CalculateHash(message); + fact.ShouldBe(expected); + } + public static byte[] ToBytes32(BigIntValue value) + { + var bytes = value.ToBigEndianBytes(); + var newArray = new byte[32]; + for (int i = 0; i < bytes.Length; i++) + { + newArray[31 - i] = bytes[bytes.Length - 1 - i]; + } + + return newArray; + } + + [Fact] + public void Bn254G1Mul_Test() + { + var bridgeContext = GetRequiredService().Create(); + var contractContext = new CSharpSmartContractContext(bridgeContext); + + // Arrange + byte[] x1 = ToBytes32(new BigIntValue(0)); + byte[] y1 = ToBytes32(new BigIntValue(0)); + byte[] scalar = ToBytes32(new BigIntValue(0)); + + // use raw api to compute result + var (expectedXUInt256, expectedYUInt256) = Bn254.Net.Bn254.Mul( + UInt256.FromBigEndianBytes(x1), + UInt256.FromBigEndianBytes(y1), + UInt256.FromBigEndianBytes(scalar) + ); + var expectedX = expectedXUInt256.ToBigEndianBytes(); + var expectedY = expectedYUInt256.ToBigEndianBytes(); + + // Act + var (xResult, yResult) = contractContext.Bn254G1Mul(x1, y1, scalar); + + // Assert + xResult.ShouldBe(expectedX); + yResult.ShouldBe(expectedY); + } + + [Fact] + public void Bn254G1Add_Test() + { + var bridgeContext = GetRequiredService().Create(); + var contractContext = new CSharpSmartContractContext(bridgeContext); + + // Arrange + byte[] x1 = ToBytes32(new BigIntValue(0)); + byte[] y1 = ToBytes32(new BigIntValue(0)); + byte[] x2 = ToBytes32(new BigIntValue(0)); + byte[] y2 = ToBytes32(new BigIntValue(0)); + + // Use raw API to compute expected results + var (expectedX3UInt256, expectedY3UInt256) = Bn254.Net.Bn254.Add( + UInt256.FromBigEndianBytes(x1), + UInt256.FromBigEndianBytes(y1), + UInt256.FromBigEndianBytes(x2), + UInt256.FromBigEndianBytes(y2) + ); + var expectedX3 = expectedX3UInt256.ToBigEndianBytes(); + var expectedY3 = expectedY3UInt256.ToBigEndianBytes(); + + // Act + var (x3Result, y3Result) = contractContext.Bn254G1Add(x1, y1, x2, y2); + + // Assert + x3Result.ShouldBe(expectedX3); + y3Result.ShouldBe(expectedY3); + } + + + [Fact] + public void Bn254Pairing_Test() + { + var bridgeContext = GetRequiredService().Create(); + var contractContext = new CSharpSmartContractContext(bridgeContext); + + // Arrange + var input = new (byte[], byte[], byte[], byte[], byte[], byte[])[] + { + ( + ToBytes32(new BigIntValue(0)), + ToBytes32(new BigIntValue(0)), + ToBytes32(new BigIntValue(0)), + ToBytes32(new BigIntValue(0)), + ToBytes32(new BigIntValue(0)), + ToBytes32(new BigIntValue(0)) + ) + }; + + // Use raw API to compute expected results + bool expected = Bn254.Net.Bn254.Pairing(new (UInt256, UInt256, UInt256, UInt256, UInt256, UInt256)[] + { + ( + UInt256.FromBigEndianBytes(input[0].Item1), + UInt256.FromBigEndianBytes(input[0].Item2), + UInt256.FromBigEndianBytes(input[0].Item3), + UInt256.FromBigEndianBytes(input[0].Item4), + UInt256.FromBigEndianBytes(input[0].Item5), + UInt256.FromBigEndianBytes(input[0].Item6) + ) + }); + + // Act + bool result = contractContext.Bn254Pairing(input); + + // Assert + result.ShouldBe(expected); + } } \ No newline at end of file From c8769448760a304973cb04c6c274360598117a3c Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Mon, 18 Nov 2024 14:48:05 +0800 Subject: [PATCH 29/83] Clean up unused code and optimize the code --- .../AEDPoSContract_ProcessConsensusInformation.cs | 5 ----- protobuf/aedpos_contract.proto | 3 --- src/AElf.Runtime.CSharp/Executive.cs | 3 +-- 3 files changed, 1 insertion(+), 10 deletions(-) diff --git a/contract/AElf.Contracts.Consensus.AEDPoS/AEDPoSContract_ProcessConsensusInformation.cs b/contract/AElf.Contracts.Consensus.AEDPoS/AEDPoSContract_ProcessConsensusInformation.cs index c51602a302..b708306d99 100644 --- a/contract/AElf.Contracts.Consensus.AEDPoS/AEDPoSContract_ProcessConsensusInformation.cs +++ b/contract/AElf.Contracts.Consensus.AEDPoS/AEDPoSContract_ProcessConsensusInformation.cs @@ -86,11 +86,6 @@ private void ProcessConsensusInformation(dynamic input, [CallerMemberName] strin _processingBlockMinerPubkey = null; } - public override Empty DoNothing(Empty input) - { - return new Empty(); - } - /// /// Get latest updated signature. /// A signature is for generating a random hash. diff --git a/protobuf/aedpos_contract.proto b/protobuf/aedpos_contract.proto index 7519a5e82b..d06f5d5ccf 100644 --- a/protobuf/aedpos_contract.proto +++ b/protobuf/aedpos_contract.proto @@ -41,9 +41,6 @@ service AEDPoSContract { // Update consensus tiny block information. rpc UpdateTinyBlockInformation (TinyBlockInput) returns (google.protobuf.Empty) { } - - rpc DoNothing (google.protobuf.Empty) returns (google.protobuf.Empty) { - } // Set the maximum count of miners, by default, is unlimited. // If you want to control the count of miners, you need to set it through parliament. diff --git a/src/AElf.Runtime.CSharp/Executive.cs b/src/AElf.Runtime.CSharp/Executive.cs index d8a3acd692..48df0dd737 100644 --- a/src/AElf.Runtime.CSharp/Executive.cs +++ b/src/AElf.Runtime.CSharp/Executive.cs @@ -63,8 +63,7 @@ public Task ApplyAsync(ITransactionContext transactionContext) CurrentTransactionContext.Trace.Error = "\n" + "ExceededMaxCallDepth"; return Task.CompletedTask; } - if (CurrentTransactionContext.InlineWithTransactionIdCounter != null - && CurrentTransactionContext.InlineWithTransactionIdCounter.GetCount() > TransactionConsts.InlineWithTransactionIdLimit) + if (CurrentTransactionContext.InlineWithTransactionIdCounter?.GetCount() > TransactionConsts.InlineWithTransactionIdLimit) { CurrentTransactionContext.Trace.ExecutionStatus = ExecutionStatus.ExceededMaxCallDepth; CurrentTransactionContext.Trace.Error = "\n" + "failed.ExceededMaxInlineWithTransactionIdCount"; From 60b637d9aeb39ddebdd29a4527dfa7d77b08548d Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Mon, 18 Nov 2024 15:03:41 +0800 Subject: [PATCH 30/83] Update the sdk version --- .github/workflows/sonarqube.yaml | 2 +- global.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/sonarqube.yaml b/.github/workflows/sonarqube.yaml index dbfca652b6..b87ff0cf93 100644 --- a/.github/workflows/sonarqube.yaml +++ b/.github/workflows/sonarqube.yaml @@ -15,7 +15,7 @@ jobs: with: dotnet-version: '8.0' - name: Create temporary global.json - run: echo '{"sdk":{"version":"8.0.303"}}' > ./global.json + run: echo '{"sdk":{"version":"8.0.*"}}' > ./global.json - name: Set up JDK 17 uses: actions/setup-java@v1 with: diff --git a/global.json b/global.json index b76a0b882f..70976d298f 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "8.0.x" + "version": "8.0.*" } } \ No newline at end of file From d4162759d829fac4ef6398021ba44730d74f0e83 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Tue, 19 Nov 2024 11:14:21 +0800 Subject: [PATCH 31/83] Temporarily remove the unit test; it will be added back later --- azure-pipelines.yml | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 9cae4c73c7..5b34136665 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -21,28 +21,28 @@ jobs: n: 1 codecoverage: true - template: templates/build-template-linux.yml - parameters: - parts: 3 - n: 2 - codecoverage: false - - template: templates/build-template-linux.yml - parameters: - parts: 3 - n: 3 - codecoverage: false - - template: templates/build-template-macos.yml - parameters: - parts: 3 - n: 1 - codecoverage: true - - template: templates/build-template-macos.yml parameters: parts: 3 n: 2 codecoverage: true - - template: templates/build-template-macos.yml + - template: templates/build-template-linux.yml parameters: parts: 3 n: 3 codecoverage: true +# - template: templates/build-template-macos.yml +# parameters: +# parts: 3 +# n: 1 +# codecoverage: true +# - template: templates/build-template-macos.yml +# parameters: +# parts: 3 +# n: 2 +# codecoverage: true +# - template: templates/build-template-macos.yml +# parameters: +# parts: 3 +# n: 3 +# codecoverage: true \ No newline at end of file From 8299f355b0022207e65095878fc60ce54c2328a7 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Tue, 19 Nov 2024 11:54:43 +0800 Subject: [PATCH 32/83] Temporarily remove the unit test; it will be added back later --- azure-pipelines.yml | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 9cae4c73c7..5b34136665 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -21,28 +21,28 @@ jobs: n: 1 codecoverage: true - template: templates/build-template-linux.yml - parameters: - parts: 3 - n: 2 - codecoverage: false - - template: templates/build-template-linux.yml - parameters: - parts: 3 - n: 3 - codecoverage: false - - template: templates/build-template-macos.yml - parameters: - parts: 3 - n: 1 - codecoverage: true - - template: templates/build-template-macos.yml parameters: parts: 3 n: 2 codecoverage: true - - template: templates/build-template-macos.yml + - template: templates/build-template-linux.yml parameters: parts: 3 n: 3 codecoverage: true +# - template: templates/build-template-macos.yml +# parameters: +# parts: 3 +# n: 1 +# codecoverage: true +# - template: templates/build-template-macos.yml +# parameters: +# parts: 3 +# n: 2 +# codecoverage: true +# - template: templates/build-template-macos.yml +# parameters: +# parts: 3 +# n: 3 +# codecoverage: true \ No newline at end of file From 30672323d22095f6859e5194e980322a086c382a Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Tue, 19 Nov 2024 13:40:21 +0800 Subject: [PATCH 33/83] Modify config in azure-pipelines.yml --- azure-pipelines.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 5b34136665..92e907c956 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -24,12 +24,12 @@ jobs: parameters: parts: 3 n: 2 - codecoverage: true + codecoverage: false - template: templates/build-template-linux.yml parameters: parts: 3 n: 3 - codecoverage: true + codecoverage: false # - template: templates/build-template-macos.yml # parameters: # parts: 3 From 69ec7e806210ef082ce7a524d23a4e753b993e0b Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Tue, 19 Nov 2024 14:06:34 +0800 Subject: [PATCH 34/83] Modify config in azure-pipelines.yml --- azure-pipelines.yml | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 92e907c956..0ba0b56b20 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -30,16 +30,16 @@ jobs: parts: 3 n: 3 codecoverage: false -# - template: templates/build-template-macos.yml -# parameters: -# parts: 3 -# n: 1 -# codecoverage: true -# - template: templates/build-template-macos.yml -# parameters: -# parts: 3 -# n: 2 -# codecoverage: true + - template: templates/build-template-macos.yml + parameters: + parts: 3 + n: 1 + codecoverage: true + - template: templates/build-template-macos.yml + parameters: + parts: 3 + n: 2 + codecoverage: true # - template: templates/build-template-macos.yml # parameters: # parts: 3 From c045573a9727d1326599300a0ff1e570a9a86cee Mon Sep 17 00:00:00 2001 From: "jim.dong" Date: Tue, 19 Nov 2024 16:42:07 +0800 Subject: [PATCH 35/83] set a the Error message to the output to infer that the transaction will never succeed --- .../Services/TransactionResultAppService.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs index 3eaae35f99..9005109a67 100644 --- a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs +++ b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs @@ -122,10 +122,10 @@ await _transactionResultProxyService.InvalidTransactionResultService.GetInvalidT var chain = await _blockchainService.GetChainAsync(); if (chain.BestChainHeight - output.Transaction.RefBlockNumber > KernelConstants.ReferenceBlockValidPeriod) { - output.Status = TransactionResultStatus.Expired.ToString().ToUpper(); - output.Error = TransactionErrorResolver.TakeErrorMessage(TransactionResultStatus.Expired.ToString(), - _webAppOptions.IsDebugMode); - return output; + // set a the Error message to the output to infer that the transaction will never succeed. + var error = $"The transactions status is:{TransactionResultStatus.Expired.ToString()}, and it will never succeed."; + output.Error = TransactionErrorResolver.TakeErrorMessage(error, _webAppOptions.IsDebugMode); + return output; } return output; } From 18763eeb33b591a30a90086ea7078d35fdf21ba0 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Tue, 19 Nov 2024 16:43:57 +0800 Subject: [PATCH 36/83] Modify config in azure-pipelines.yml --- azure-pipelines.yml | 62 ++++++++++++++++++++++----------------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 5b34136665..638b5c27f1 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -1,20 +1,20 @@ # Azure Pipelines configuration file jobs: -# - template: templates/build-template-window.yml -# parameters: -# parts: 3 -# n: 1 -# codecoverage: true -# - template: templates/build-template-window.yml -# parameters: -# parts: 3 -# n: 2 -# codecoverage: false -# - template: templates/build-template-window.yml -# parameters: -# parts: 3 -# n: 3 -# codecoverage: false + # - template: templates/build-template-window.yml + # parameters: + # parts: 3 + # n: 1 + # codecoverage: true + # - template: templates/build-template-window.yml + # parameters: + # parts: 3 + # n: 2 + # codecoverage: false + # - template: templates/build-template-window.yml + # parameters: + # parts: 3 + # n: 3 + # codecoverage: false - template: templates/build-template-linux.yml parameters: parts: 3 @@ -24,25 +24,25 @@ jobs: parameters: parts: 3 n: 2 - codecoverage: true + codecoverage: false - template: templates/build-template-linux.yml parameters: parts: 3 n: 3 + codecoverage: false + - template: templates/build-template-macos.yml + parameters: + parts: 3 + n: 1 + codecoverage: true + - template: templates/build-template-macos.yml + parameters: + parts: 3 + n: 2 codecoverage: true -# - template: templates/build-template-macos.yml -# parameters: -# parts: 3 -# n: 1 -# codecoverage: true -# - template: templates/build-template-macos.yml -# parameters: -# parts: 3 -# n: 2 -# codecoverage: true -# - template: templates/build-template-macos.yml -# parameters: -# parts: 3 -# n: 3 -# codecoverage: true + # - template: templates/build-template-macos.yml + # parameters: + # parts: 3 + # n: 3 + # codecoverage: true \ No newline at end of file From 52efae93168b40d009c2fba342cb5ad2de0b5170 Mon Sep 17 00:00:00 2001 From: "jim.dong" Date: Tue, 19 Nov 2024 16:47:20 +0800 Subject: [PATCH 37/83] set a the Error message to the output to infer that the transaction will never succeed --- protobuf/aelf/core.proto | 2 -- 1 file changed, 2 deletions(-) diff --git a/protobuf/aelf/core.proto b/protobuf/aelf/core.proto index 24fe381877..4fe3a5bcf4 100644 --- a/protobuf/aelf/core.proto +++ b/protobuf/aelf/core.proto @@ -59,8 +59,6 @@ enum TransactionResultStatus { PENDING_VALIDATION = 5; // Transaction validation failed. NODE_VALIDATION_FAILED = 6; - // Transaction is expired and will never succeed - EXPIRED = 7; } message TransactionResult { From de45a0ff67193e8f1fec90a21774f6bca14812fa Mon Sep 17 00:00:00 2001 From: "jim.dong" Date: Tue, 19 Nov 2024 16:51:37 +0800 Subject: [PATCH 38/83] set a the Error message to the output to infer that the transaction will never succeed. --- .../Services/TransactionResultAppService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs index 9005109a67..3d466c5a2b 100644 --- a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs +++ b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs @@ -123,7 +123,7 @@ await _transactionResultProxyService.InvalidTransactionResultService.GetInvalidT if (chain.BestChainHeight - output.Transaction.RefBlockNumber > KernelConstants.ReferenceBlockValidPeriod) { // set a the Error message to the output to infer that the transaction will never succeed. - var error = $"The transactions status is:{TransactionResultStatus.Expired.ToString()}, and it will never succeed."; + var error = $"The transactions status is expired, and it will never succeed."; output.Error = TransactionErrorResolver.TakeErrorMessage(error, _webAppOptions.IsDebugMode); return output; } From 60cb378b0cc6711a759f1c581f60a317b371a131 Mon Sep 17 00:00:00 2001 From: "jim.dong" Date: Tue, 19 Nov 2024 17:12:28 +0800 Subject: [PATCH 39/83] If transaction satus is "NOT_EXIST", and the lag of the refblock is bigger that 512, this transaction will never bee succeed in the future --- .../Services/TransactionResultAppService.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs index 3d466c5a2b..c733722ced 100644 --- a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs +++ b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs @@ -120,7 +120,8 @@ await _transactionResultProxyService.InvalidTransactionResultService.GetInvalidT } var chain = await _blockchainService.GetChainAsync(); - if (chain.BestChainHeight - output.Transaction.RefBlockNumber > KernelConstants.ReferenceBlockValidPeriod) + if (chain.BestChainHeight - output.Transaction.RefBlockNumber > KernelConstants.ReferenceBlockValidPeriod + && transactionResult.Status == TransactionResultStatus.NotExisted) { // set a the Error message to the output to infer that the transaction will never succeed. var error = $"The transactions status is expired, and it will never succeed."; From 1b7c212e5d15fdbf1bac74da6b1cc2a99b3cf2a6 Mon Sep 17 00:00:00 2001 From: "jim.dong" Date: Tue, 19 Nov 2024 22:13:52 +0800 Subject: [PATCH 40/83] handle the Sonar build problem --- .github/workflows/sonarqube.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/sonarqube.yaml b/.github/workflows/sonarqube.yaml index dbfca652b6..b87ff0cf93 100644 --- a/.github/workflows/sonarqube.yaml +++ b/.github/workflows/sonarqube.yaml @@ -15,7 +15,7 @@ jobs: with: dotnet-version: '8.0' - name: Create temporary global.json - run: echo '{"sdk":{"version":"8.0.303"}}' > ./global.json + run: echo '{"sdk":{"version":"8.0.*"}}' > ./global.json - name: Set up JDK 17 uses: actions/setup-java@v1 with: From c53dbf790ac572c66f68a66de35019ee5bd72645 Mon Sep 17 00:00:00 2001 From: "jim.dong" Date: Tue, 19 Nov 2024 22:15:45 +0800 Subject: [PATCH 41/83] handle the Sonar build problem --- .github/workflows/sonarqube.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/sonarqube.yaml b/.github/workflows/sonarqube.yaml index dbfca652b6..b87ff0cf93 100644 --- a/.github/workflows/sonarqube.yaml +++ b/.github/workflows/sonarqube.yaml @@ -15,7 +15,7 @@ jobs: with: dotnet-version: '8.0' - name: Create temporary global.json - run: echo '{"sdk":{"version":"8.0.303"}}' > ./global.json + run: echo '{"sdk":{"version":"8.0.*"}}' > ./global.json - name: Set up JDK 17 uses: actions/setup-java@v1 with: From af79e90b6002df71dce64d4f33af8c1f3ff4e5c7 Mon Sep 17 00:00:00 2001 From: eanzhao Date: Wed, 20 Nov 2024 16:30:03 +0800 Subject: [PATCH 42/83] Fix tx expired error message. --- .../Services/TransactionResultAppService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs index c733722ced..4b6220c391 100644 --- a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs +++ b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs @@ -124,9 +124,9 @@ await _transactionResultProxyService.InvalidTransactionResultService.GetInvalidT && transactionResult.Status == TransactionResultStatus.NotExisted) { // set a the Error message to the output to infer that the transaction will never succeed. - var error = $"The transactions status is expired, and it will never succeed."; + var error = "The transaction is already expired, and it will never succeed."; output.Error = TransactionErrorResolver.TakeErrorMessage(error, _webAppOptions.IsDebugMode); - return output; + return output; } return output; } From 1404c3ecf0c46f1b07b3aebfacb3458d68bc84c4 Mon Sep 17 00:00:00 2001 From: eanzhao Date: Wed, 20 Nov 2024 16:41:01 +0800 Subject: [PATCH 43/83] Add new event: SeedExpirationTimeUpdated --- .../TokenContract_Actions.cs | 23 ++++++++++++++++--- protobuf/token_contract_impl.proto | 8 +++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/contract/AElf.Contracts.MultiToken/TokenContract_Actions.cs b/contract/AElf.Contracts.MultiToken/TokenContract_Actions.cs index 7c5b33b300..7c24cb4151 100644 --- a/contract/AElf.Contracts.MultiToken/TokenContract_Actions.cs +++ b/contract/AElf.Contracts.MultiToken/TokenContract_Actions.cs @@ -694,12 +694,29 @@ public override Int32Value GetMaxBatchApproveCount(Empty input) public override Empty ExtendSeedExpirationTime(ExtendSeedExpirationTimeInput input) { var tokenInfo = GetTokenInfo(input.Symbol); - Assert(tokenInfo != null, "Seed NFT does not exist."); + if (tokenInfo == null) + { + throw new AssertionException("Seed NFT does not exist."); + } + Assert(tokenInfo.Owner == Context.Sender, "Sender is not Seed NFT owner."); + var oldExpireTimeLong = 0L; + if (tokenInfo.ExternalInfo.Value.TryGetValue(TokenContractConstants.SeedExpireTimeExternalInfoKey, + out var oldExpireTime)) + { + long.TryParse(oldExpireTime, out oldExpireTimeLong); + } - tokenInfo.ExternalInfo.Value[TokenContractConstants.SeedExpireTimeExternalInfoKey] = input.ExpirationTime.ToString(); + tokenInfo.ExternalInfo.Value[TokenContractConstants.SeedExpireTimeExternalInfoKey] = + input.ExpirationTime.ToString(); State.TokenInfos[input.Symbol] = tokenInfo; - base.ExtendSeedExpirationTime(input); + Context.Fire(new SeedExpirationTimeUpdated + { + ChainId = tokenInfo.IssueChainId, + Symbol = input.Symbol, + OldExpirationTime = oldExpireTimeLong, + NewExpirationTime = input.ExpirationTime + }); return new Empty(); } diff --git a/protobuf/token_contract_impl.proto b/protobuf/token_contract_impl.proto index 7a6e76247f..3ae6ffa2c5 100644 --- a/protobuf/token_contract_impl.proto +++ b/protobuf/token_contract_impl.proto @@ -452,4 +452,12 @@ message SetTokenIssuerAndOwnerModificationEnabledInput{ message ExtendSeedExpirationTimeInput { string symbol = 1; int64 expiration_time = 2; +} + +message SeedExpirationTimeUpdated { + option (aelf.is_event) = true; + int32 chain_id = 1; + string symbol = 2; + int64 old_expiration_time = 3; + int64 new_expiration_time = 4; } \ No newline at end of file From d1a71ef2740669d2660d06318fe3e6fa41cfc6f2 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Sat, 23 Nov 2024 17:05:30 +0800 Subject: [PATCH 44/83] CallCount revert to 15000 --- src/AElf.Kernel.SmartContract/SmartContractConstants.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/AElf.Kernel.SmartContract/SmartContractConstants.cs b/src/AElf.Kernel.SmartContract/SmartContractConstants.cs index 0260dc8bbb..9a210289ce 100644 --- a/src/AElf.Kernel.SmartContract/SmartContractConstants.cs +++ b/src/AElf.Kernel.SmartContract/SmartContractConstants.cs @@ -2,7 +2,7 @@ namespace AElf.Kernel.SmartContract; public class SmartContractConstants { - public const int ExecutionCallThreshold = 80000; + public const int ExecutionCallThreshold = 15000; public const int ExecutionBranchThreshold = 15000; From e617a6958d3fd3d3f5a2d990cdca538e60de3553 Mon Sep 17 00:00:00 2001 From: "jim.dong" Date: Mon, 25 Nov 2024 16:38:40 +0800 Subject: [PATCH 45/83] The Status is obsolete. Use StatusV2 instead --- protobuf/aelf/core.proto | 2 ++ .../Dto/TransactionResultDto.cs | 5 +++++ .../Services/TransactionResultAppService.cs | 8 ++++++++ 3 files changed, 15 insertions(+) diff --git a/protobuf/aelf/core.proto b/protobuf/aelf/core.proto index 4fe3a5bcf4..d2812d46f7 100644 --- a/protobuf/aelf/core.proto +++ b/protobuf/aelf/core.proto @@ -59,6 +59,8 @@ enum TransactionResultStatus { PENDING_VALIDATION = 5; // Transaction validation failed. NODE_VALIDATION_FAILED = 6; + // Transaction is expired + EXPIRED = 7; } message TransactionResult { diff --git a/src/AElf.WebApp.Application.Chain/Dto/TransactionResultDto.cs b/src/AElf.WebApp.Application.Chain/Dto/TransactionResultDto.cs index e76f92a941..115643789b 100644 --- a/src/AElf.WebApp.Application.Chain/Dto/TransactionResultDto.cs +++ b/src/AElf.WebApp.Application.Chain/Dto/TransactionResultDto.cs @@ -1,10 +1,15 @@ +using System; + namespace AElf.WebApp.Application.Chain.Dto; public class TransactionResultDto { public string TransactionId { get; set; } + [Obsolete("The Status is obsolete. Use StatusV2 instead.")] public string Status { get; set; } + + public string StatusV2 { get; set; } public LogEventDto[] Logs { get; set; } diff --git a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs index 483dbb4366..ba1fa6299f 100644 --- a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs +++ b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs @@ -118,6 +118,14 @@ await _transactionResultProxyService.InvalidTransactionResultService.GetInvalidT return output; } } + + var chain = await _blockchainService.GetChainAsync(); + if (chain.BestChainHeight - output.Transaction.RefBlockNumber > KernelConstants.ReferenceBlockValidPeriod + && transactionResult.Status == TransactionResultStatus.NotExisted) + { + output.StatusV2 = TransactionResultStatus.Expired; + return output; + } return output; From d1658fd1674c1c8d242b1499b83149a1b1d54488 Mon Sep 17 00:00:00 2001 From: "jim.dong" Date: Mon, 25 Nov 2024 16:39:52 +0800 Subject: [PATCH 46/83] The Status is obsolete. Use StatusV2 instead --- .../Services/TransactionResultAppService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs index ba1fa6299f..1566c7b954 100644 --- a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs +++ b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs @@ -123,7 +123,7 @@ await _transactionResultProxyService.InvalidTransactionResultService.GetInvalidT if (chain.BestChainHeight - output.Transaction.RefBlockNumber > KernelConstants.ReferenceBlockValidPeriod && transactionResult.Status == TransactionResultStatus.NotExisted) { - output.StatusV2 = TransactionResultStatus.Expired; + output.StatusV2 = TransactionResultStatus.Expired.ToString().ToUpper(); return output; } From 0f4b2c44cfe20e9860f2cc6e21e47346967c1c84 Mon Sep 17 00:00:00 2001 From: "jim.dong" Date: Mon, 25 Nov 2024 16:49:09 +0800 Subject: [PATCH 47/83] The Status is obsolete in this version. Use StatusV2 instead --- .../BlockChainAppServiceTest.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs b/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs index 67e9db0b83..f6baca6ad2 100644 --- a/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs +++ b/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs @@ -681,6 +681,7 @@ public async Task Get_TransactionResult_Success_Test() response.TransactionId.ShouldBe(transactionHex); response.Status.ShouldBe(TransactionResultStatus.Mined.ToString().ToUpper()); + response.StatusV2.ShouldBe(TransactionResultStatus.Expired.ToString().ToUpper()); response.TransactionSize.ShouldBe(transaction.CalculateSize()); response.BlockNumber.ShouldBe(block.Height); response.BlockHash.ShouldBe(block.GetHash().ToHex()); From b3a138c9be7f6cf331dcc5b70dfd43288b54f1e5 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Tue, 26 Nov 2024 14:37:59 +0800 Subject: [PATCH 48/83] Add unit-test for cross-aa --- protobuf/test_virtual_address_contract.proto | 6 + .../BVT/ElectionTests.cs | 127 ++++++++++++++++++ .../Action.cs | 21 +++ 3 files changed, 154 insertions(+) diff --git a/protobuf/test_virtual_address_contract.proto b/protobuf/test_virtual_address_contract.proto index cdfb14fa05..992ad86fbf 100644 --- a/protobuf/test_virtual_address_contract.proto +++ b/protobuf/test_virtual_address_contract.proto @@ -14,6 +14,7 @@ service VirtualAddressContract { option (aelf.base) = "acs1.proto"; rpc VirtualAddressVote(VirtualAddressVoteInput) returns (google.protobuf.Empty); + rpc VirtualAddressVoteWithInline(VirtualAddressVoteWithCountInput) returns (google.protobuf.Empty); rpc VirtualAddressWithdraw(aelf.Hash) returns (google.protobuf.Empty); rpc VirtualAddressChangeVotingOption(VirtualAddressChangeVotingOptionInput) returns (google.protobuf.Empty); rpc VirtualAddressClaimProfit(VirtualAddressClaimProfitInput) returns (google.protobuf.Empty); @@ -32,6 +33,11 @@ message VirtualAddressVoteInput { aelf.Hash token = 4; } +message VirtualAddressVoteWithCountInput { + VirtualAddressVoteInput vote_input = 1; // Existing input type + int32 count = 2; // Additional count input +} + message VirtualAddressChangeVotingOptionInput { bool is_reset = 1; aelf.Hash vote_id = 2; diff --git a/test/AElf.Contracts.Election.Tests/BVT/ElectionTests.cs b/test/AElf.Contracts.Election.Tests/BVT/ElectionTests.cs index 2ba363f220..b143874a08 100644 --- a/test/AElf.Contracts.Election.Tests/BVT/ElectionTests.cs +++ b/test/AElf.Contracts.Election.Tests/BVT/ElectionTests.cs @@ -1984,6 +1984,133 @@ await VirtualAddressContractStub.VirtualAddressVote.SendAsync(new VirtualAddress return result.ActiveVotingRecords.First().VoteId; } + // [Fact] + // public async Task VirtualAddress_Vote_WithInlineTxIdAndCountTest() + // { + // var amount = 100; + // const int lockTime = 100 * 60 * 60 * 24; + // var candidatesKeyPairs = await ElectionContract_AnnounceElection_Test(); + // var candidateKeyPair = candidatesKeyPairs[0]; + // + // var address = await VirtualAddressContractStub.GetVirtualAddress.CallAsync(new Empty()); + // var initBalance = 100000; + // + // await TokenContractStub.Transfer.SendAsync(new TransferInput + // { + // Amount = initBalance, + // Symbol = "ELF", + // To = address, + // Memo = "test" + // }); + // + // CheckBalance(address, "ELF", initBalance); + // CheckBalance(address, "SHARE", 0); + // CheckBalance(address, "VOTE", 0); + // + // var virtualAddressVoteInput = new VirtualAddressVoteInput + // { + // PubKey = candidateKeyPair.PublicKey.ToHex(), + // Amount = amount, + // EndTimestamp = TimestampHelper.GetUtcNow().AddSeconds(lockTime), + // Token = HashHelper.ComputeFrom("token A") + // }; + // + // var resultawait = await VirtualAddressContractStub.VirtualAddressVoteWithInline.SendAsync(new VirtualAddressVoteWithCountInput + // { + // VoteInput = virtualAddressVoteInput, + // Count = 6 + // }); + // return null; + // } + // + [Fact] + public async Task VirtualAddress_Vote_WithInlineTxIdTest() + { + var amount = 100; + const int lockTime = 100 * 60 * 60 * 24; + var candidatesKeyPairs = await ElectionContract_AnnounceElection_Test(); + var candidateKeyPair = candidatesKeyPairs[0]; + + var address = await VirtualAddressContractStub.GetVirtualAddress.CallAsync(new Empty()); + var initBalance = 100000; + + await TokenContractStub.Transfer.SendAsync(new TransferInput + { + Amount = initBalance, + Symbol = "ELF", + To = address, + Memo = "test" + }); + + CheckBalance(address, "ELF", initBalance); + CheckBalance(address, "SHARE", 0); + CheckBalance(address, "VOTE", 0); + + var virtualAddressVoteInput = new VirtualAddressVoteInput + { + PubKey = candidateKeyPair.PublicKey.ToHex(), + Amount = amount, + EndTimestamp = TimestampHelper.GetUtcNow().AddSeconds(lockTime), + Token = HashHelper.ComputeFrom("token A") + }; + + await VirtualAddressContractStub.VirtualAddressVoteWithInline.SendAsync(new VirtualAddressVoteWithCountInput + { + VoteInput = virtualAddressVoteInput, + Count = 1 + }); + + var result = await ElectionContractStub.GetElectorVote.CallAsync(new StringValue + { + Value = address.ToBase58() + }); + result.ActiveVotedVotesAmount.ShouldBe(amount); + result = await ElectionContractStub.GetElectorVoteWithRecords.CallAsync(new StringValue + { + Value = address.ToBase58() + }); + result.ActiveVotedVotesAmount.ShouldBe(amount); + result = await ElectionContractStub.GetElectorVoteWithAllRecords.CallAsync(new StringValue + { + Value = address.ToBase58() + }); + result.AllVotedVotesAmount.ShouldBe(amount); + + CheckBalance(address, "ELF", initBalance - amount); + CheckBalance(address, "SHARE", amount); + CheckBalance(address, "VOTE", amount); + + await VirtualAddressContractStub.VirtualAddressVote.SendAsync(new VirtualAddressVoteInput + { + PubKey = candidateKeyPair.PublicKey.ToHex(), + Amount = amount, + EndTimestamp = TimestampHelper.GetUtcNow().AddSeconds(lockTime), + Token = HashHelper.ComputeFrom("token A") + }); + + result = await ElectionContractStub.GetElectorVote.CallAsync(new StringValue + { + Value = address.ToBase58() + }); + result.ActiveVotedVotesAmount.ShouldBe(amount + amount); + result = await ElectionContractStub.GetElectorVoteWithRecords.CallAsync(new StringValue + { + Value = address.ToBase58() + }); + result.ActiveVotedVotesAmount.ShouldBe(amount + amount); + result = await ElectionContractStub.GetElectorVoteWithAllRecords.CallAsync(new StringValue + { + Value = address.ToBase58() + }); + result.AllVotedVotesAmount.ShouldBe(amount + amount); + + CheckBalance(address, "ELF", initBalance - amount - amount); + CheckBalance(address, "SHARE", amount + amount); + CheckBalance(address, "VOTE", amount + amount); + + return result.ActiveVotingRecords.First().VoteId; + } + [Fact] public async Task VirtualAddress_Withdraw_Test() { diff --git a/test/AElf.Contracts.TestContract.VirtualAddress/Action.cs b/test/AElf.Contracts.TestContract.VirtualAddress/Action.cs index 295830ea1c..bc8edd7a81 100644 --- a/test/AElf.Contracts.TestContract.VirtualAddress/Action.cs +++ b/test/AElf.Contracts.TestContract.VirtualAddress/Action.cs @@ -9,6 +9,27 @@ namespace AElf.Contracts.TestContract.VirtualAddress; public partial class Action : VirtualAddressContractContainer.VirtualAddressContractBase { + + public override Empty VirtualAddressVoteWithInline(VirtualAddressVoteWithCountInput input) + { + if (input.Count == null) return new Empty(); + Initialize(); + + for (int i = 0; i < input.Count; i++) + { + Context.SendVirtualInline(HashHelper.ComputeFrom("test"), State.ElectionContract.Value, ".Vote", new VoteMinerInput + { + CandidatePubkey = input.VoteInput.PubKey, + Amount = input.VoteInput.Amount, + EndTimestamp = input.VoteInput.EndTimestamp, + Token = input.VoteInput.Token + }.ToByteString()); + } + + + return new Empty(); + } + public override Empty VirtualAddressVote(VirtualAddressVoteInput input) { Initialize(); From b498ff540be7c0ee53f13f05f4fadb6578cc9203 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Tue, 26 Nov 2024 17:10:11 +0800 Subject: [PATCH 49/83] Add unit test --- .../Extensions/TransactionExtensionsTests.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/test/AElf.Kernel.Core.Tests/Extensions/TransactionExtensionsTests.cs b/test/AElf.Kernel.Core.Tests/Extensions/TransactionExtensionsTests.cs index daa6331365..2fe628cb1f 100644 --- a/test/AElf.Kernel.Core.Tests/Extensions/TransactionExtensionsTests.cs +++ b/test/AElf.Kernel.Core.Tests/Extensions/TransactionExtensionsTests.cs @@ -46,4 +46,14 @@ public void VerifyExpiration_Test() transaction.VerifyExpiration(100).ShouldBeTrue(); transaction.VerifyExpiration(612).ShouldBeFalse(); } + + [Fact] + public void IsInlineWithTransactionId_Test() + { + var transaction = _kernelTestHelper.GenerateTransaction(100); + transaction.MethodName = ".vote"; + transaction.IsInlineWithTransactionId().ShouldBeTrue(); + transaction.MethodName = "vote"; + transaction.IsInlineWithTransactionId().ShouldBeFalse(); + } } \ No newline at end of file From c84faaae4002a37ad0317fbbabcf769a6932ba15 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Tue, 26 Nov 2024 17:17:33 +0800 Subject: [PATCH 50/83] Remove unused unit test --- .../BVT/ElectionTests.cs | 39 ------------------- 1 file changed, 39 deletions(-) diff --git a/test/AElf.Contracts.Election.Tests/BVT/ElectionTests.cs b/test/AElf.Contracts.Election.Tests/BVT/ElectionTests.cs index b143874a08..d6e44f057f 100644 --- a/test/AElf.Contracts.Election.Tests/BVT/ElectionTests.cs +++ b/test/AElf.Contracts.Election.Tests/BVT/ElectionTests.cs @@ -1984,45 +1984,6 @@ await VirtualAddressContractStub.VirtualAddressVote.SendAsync(new VirtualAddress return result.ActiveVotingRecords.First().VoteId; } - // [Fact] - // public async Task VirtualAddress_Vote_WithInlineTxIdAndCountTest() - // { - // var amount = 100; - // const int lockTime = 100 * 60 * 60 * 24; - // var candidatesKeyPairs = await ElectionContract_AnnounceElection_Test(); - // var candidateKeyPair = candidatesKeyPairs[0]; - // - // var address = await VirtualAddressContractStub.GetVirtualAddress.CallAsync(new Empty()); - // var initBalance = 100000; - // - // await TokenContractStub.Transfer.SendAsync(new TransferInput - // { - // Amount = initBalance, - // Symbol = "ELF", - // To = address, - // Memo = "test" - // }); - // - // CheckBalance(address, "ELF", initBalance); - // CheckBalance(address, "SHARE", 0); - // CheckBalance(address, "VOTE", 0); - // - // var virtualAddressVoteInput = new VirtualAddressVoteInput - // { - // PubKey = candidateKeyPair.PublicKey.ToHex(), - // Amount = amount, - // EndTimestamp = TimestampHelper.GetUtcNow().AddSeconds(lockTime), - // Token = HashHelper.ComputeFrom("token A") - // }; - // - // var resultawait = await VirtualAddressContractStub.VirtualAddressVoteWithInline.SendAsync(new VirtualAddressVoteWithCountInput - // { - // VoteInput = virtualAddressVoteInput, - // Count = 6 - // }); - // return null; - // } - // [Fact] public async Task VirtualAddress_Vote_WithInlineTxIdTest() { From cec89b7af347f8e145dab5d1648dd8bd34bb884f Mon Sep 17 00:00:00 2001 From: "jim.dong" Date: Tue, 26 Nov 2024 17:19:08 +0800 Subject: [PATCH 51/83] unit test done --- .../Services/TransactionResultAppService.cs | 60 +++++++++++++++++++ test/AElf.OS.TestBase/OSTestHelper.cs | 9 +++ .../BlockChainAppServiceTest.cs | 21 +++++++ 3 files changed, 90 insertions(+) diff --git a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs index 1566c7b954..4a58a172f2 100644 --- a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs +++ b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs @@ -24,6 +24,8 @@ namespace AElf.WebApp.Application.Chain; public interface ITransactionResultAppService { Task GetTransactionResultAsync(string transactionId); + + Task GetTransactionResultAsyncV2(string transactionId); Task> GetTransactionResultsAsync(string blockHash, int offset = 0, int limit = 10); @@ -106,6 +108,64 @@ public async Task GetTransactionResultAsync(string transac return output; } + if (_transactionOptions.StoreInvalidTransactionResultEnabled) + { + var failedTransactionResult = + await _transactionResultProxyService.InvalidTransactionResultService.GetInvalidTransactionResultAsync( + transactionIdHash); + if (failedTransactionResult != null) + { + output.Status = failedTransactionResult.Status.ToString().ToUpper(); + output.Error = failedTransactionResult.Error; + return output; + } + } + + return output; + + } + /// + /// Get the current status of a transaction + /// + /// transaction id + /// + public async Task GetTransactionResultAsyncV2(string transactionId) + { + Hash transactionIdHash; + try + { + transactionIdHash = Hash.LoadFromHex(transactionId); + } + catch + { + throw new UserFriendlyException(Error.Message[Error.InvalidTransactionId], + Error.InvalidTransactionId.ToString()); + } + + var transactionResult = await GetTransactionResultAsync(transactionIdHash); + var output = _objectMapper.GetMapper() + .Map(transactionResult, + opt => opt.Items[TransactionProfile.ErrorTrace] = _webAppOptions.IsDebugMode); + + var transaction = await _transactionManager.GetTransactionAsync(transactionResult.TransactionId); + output.Transaction = _objectMapper.Map(transaction); + output.TransactionSize = transaction?.CalculateSize() ?? 0; + + if (transactionResult.Status != TransactionResultStatus.NotExisted) + { + await FormatTransactionParamsAsync(output.Transaction, transaction.Params); + return output; + } + + var validationStatus = _transactionResultStatusCacheProvider.GetTransactionResultStatus(transactionIdHash); + if (validationStatus != null) + { + output.Status = validationStatus.TransactionResultStatus.ToString().ToUpper(); + output.Error = + TransactionErrorResolver.TakeErrorMessage(validationStatus.Error, _webAppOptions.IsDebugMode); + return output; + } + if (_transactionOptions.StoreInvalidTransactionResultEnabled) { var failedTransactionResult = diff --git a/test/AElf.OS.TestBase/OSTestHelper.cs b/test/AElf.OS.TestBase/OSTestHelper.cs index cbef7de0eb..ca64c5e90c 100644 --- a/test/AElf.OS.TestBase/OSTestHelper.cs +++ b/test/AElf.OS.TestBase/OSTestHelper.cs @@ -163,6 +163,15 @@ await _smartContractAddressService.GetAddressByContractNameAsync(await GetChainC return transaction; } + + + public async Task Mined520Blocks() + { + for (var i = 0; i < 520; i++) + { + await MinedOneBlock(); + } + } public async Task<(List, List)> PrepareTokenForParallel(int count, long tokenAmount = 10) { diff --git a/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs b/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs index f6baca6ad2..1ddffe93c4 100644 --- a/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs +++ b/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs @@ -686,6 +686,27 @@ public async Task Get_TransactionResult_Success_Test() response.BlockNumber.ShouldBe(block.Height); response.BlockHash.ShouldBe(block.GetHash().ToHex()); } + + [Fact] + public async Task Get_TransactionResultV2_Success_Test() + { + + // 1.build transaction to be expired + var transaction = await _osTestHelper.GenerateTransferTransaction(); + + // 2.push chain height to be ref_block_number + 512 + await _osTestHelper.Mined520Blocks(); + var transactionHex = transaction.GetHash().ToHex(); + + // 3.broadcast expired transaction + await _osTestHelper.BroadcastTransactions(new List { transaction }); + + // 4.get transaction status + var response = await GetResponseAsObjectAsync( + $"/api/blockChain/transactionResult?transactionId={transactionHex}"); + response.TransactionId.ShouldBe(TransactionResultStatus.Expired.ToString()); + + } [Fact] public async Task Get_Failed_TransactionResult_Success_Test() From 2e1522e295cf68f11be943cdda1481b178717c0c Mon Sep 17 00:00:00 2001 From: "jim.dong" Date: Tue, 26 Nov 2024 17:50:57 +0800 Subject: [PATCH 52/83] unit test done --- .../Services/TransactionResultAppService.cs | 6 +++--- .../BlockChainAppServiceTest.cs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs index 4a58a172f2..fad830cd7d 100644 --- a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs +++ b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs @@ -25,7 +25,7 @@ public interface ITransactionResultAppService { Task GetTransactionResultAsync(string transactionId); - Task GetTransactionResultAsyncV2(string transactionId); + Task GetTransactionResultV2Async(string transactionId); Task> GetTransactionResultsAsync(string blockHash, int offset = 0, int limit = 10); @@ -125,11 +125,11 @@ await _transactionResultProxyService.InvalidTransactionResultService.GetInvalidT } /// - /// Get the current status of a transaction + /// Get the current status of a transaction, available since V1.12.0 /// /// transaction id /// - public async Task GetTransactionResultAsyncV2(string transactionId) + public async Task GetTransactionResultV2Async(string transactionId) { Hash transactionIdHash; try diff --git a/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs b/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs index 1ddffe93c4..e3f2ba9d81 100644 --- a/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs +++ b/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs @@ -703,7 +703,7 @@ public async Task Get_TransactionResultV2_Success_Test() // 4.get transaction status var response = await GetResponseAsObjectAsync( - $"/api/blockChain/transactionResult?transactionId={transactionHex}"); + $"/api/blockChain/transactionResultV2?transactionId={transactionHex}"); response.TransactionId.ShouldBe(TransactionResultStatus.Expired.ToString()); } From 67ea4aa695982d7da13f2603128db3ea3c11abf6 Mon Sep 17 00:00:00 2001 From: eanzhao Date: Wed, 27 Nov 2024 10:58:06 +0800 Subject: [PATCH 53/83] Tune Get_TransactionResultV2_Expired_Testf and fixed tx.statusv2 issues. --- .../Services/TransactionResultAppService.cs | 8 ++--- test/AElf.OS.TestBase/OSTestHelper.cs | 9 ------ .../BlockChainAppServiceTest.cs | 32 +++++++++++++------ 3 files changed, 26 insertions(+), 23 deletions(-) diff --git a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs index fad830cd7d..29c4542ad2 100644 --- a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs +++ b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs @@ -146,6 +146,7 @@ public async Task GetTransactionResultV2Async(string trans var output = _objectMapper.GetMapper() .Map(transactionResult, opt => opt.Items[TransactionProfile.ErrorTrace] = _webAppOptions.IsDebugMode); + output.StatusV2 = output.Status; var transaction = await _transactionManager.GetTransactionAsync(transactionResult.TransactionId); output.Transaction = _objectMapper.Map(transaction); @@ -160,7 +161,7 @@ public async Task GetTransactionResultV2Async(string trans var validationStatus = _transactionResultStatusCacheProvider.GetTransactionResultStatus(transactionIdHash); if (validationStatus != null) { - output.Status = validationStatus.TransactionResultStatus.ToString().ToUpper(); + output.StatusV2 = validationStatus.TransactionResultStatus.ToString().ToUpper(); output.Error = TransactionErrorResolver.TakeErrorMessage(validationStatus.Error, _webAppOptions.IsDebugMode); return output; @@ -173,14 +174,14 @@ await _transactionResultProxyService.InvalidTransactionResultService.GetInvalidT transactionIdHash); if (failedTransactionResult != null) { - output.Status = failedTransactionResult.Status.ToString().ToUpper(); + output.StatusV2 = failedTransactionResult.Status.ToString().ToUpper(); output.Error = failedTransactionResult.Error; return output; } } var chain = await _blockchainService.GetChainAsync(); - if (chain.BestChainHeight - output.Transaction.RefBlockNumber > KernelConstants.ReferenceBlockValidPeriod + if (chain.BestChainHeight - output.Transaction?.RefBlockNumber > KernelConstants.ReferenceBlockValidPeriod && transactionResult.Status == TransactionResultStatus.NotExisted) { output.StatusV2 = TransactionResultStatus.Expired.ToString().ToUpper(); @@ -188,7 +189,6 @@ await _transactionResultProxyService.InvalidTransactionResultService.GetInvalidT } return output; - } /// diff --git a/test/AElf.OS.TestBase/OSTestHelper.cs b/test/AElf.OS.TestBase/OSTestHelper.cs index ca64c5e90c..cbef7de0eb 100644 --- a/test/AElf.OS.TestBase/OSTestHelper.cs +++ b/test/AElf.OS.TestBase/OSTestHelper.cs @@ -163,15 +163,6 @@ await _smartContractAddressService.GetAddressByContractNameAsync(await GetChainC return transaction; } - - - public async Task Mined520Blocks() - { - for (var i = 0; i < 520; i++) - { - await MinedOneBlock(); - } - } public async Task<(List, List)> PrepareTokenForParallel(int count, long tokenAmount = 10) { diff --git a/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs b/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs index e3f2ba9d81..85bb6021f2 100644 --- a/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs +++ b/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs @@ -681,31 +681,43 @@ public async Task Get_TransactionResult_Success_Test() response.TransactionId.ShouldBe(transactionHex); response.Status.ShouldBe(TransactionResultStatus.Mined.ToString().ToUpper()); - response.StatusV2.ShouldBe(TransactionResultStatus.Expired.ToString().ToUpper()); response.TransactionSize.ShouldBe(transaction.CalculateSize()); response.BlockNumber.ShouldBe(block.Height); response.BlockHash.ShouldBe(block.GetHash().ToHex()); } [Fact] - public async Task Get_TransactionResultV2_Success_Test() + public async Task Get_TransactionResultV2_Expired_Test() { - - // 1.build transaction to be expired + // Generate a transaction var transaction = await _osTestHelper.GenerateTransferTransaction(); - // 2.push chain height to be ref_block_number + 512 - await _osTestHelper.Mined520Blocks(); + // Push chain height to be ref_block_number + at least 512 + await MineSomeBlocks(520); var transactionHex = transaction.GetHash().ToHex(); - // 3.broadcast expired transaction + // Broadcast expired transaction await _osTestHelper.BroadcastTransactions(new List { transaction }); - // 4.get transaction status + // Try to package this transaction + await _osTestHelper.MinedOneBlock(); + + // Check transaction status var response = await GetResponseAsObjectAsync( $"/api/blockChain/transactionResultV2?transactionId={transactionHex}"); - response.TransactionId.ShouldBe(TransactionResultStatus.Expired.ToString()); - + // response.StatusV2.ShouldBe(TransactionResultStatus.Expired.ToString()); + } + + private async Task MineSomeBlocks(int blockNumber) + { + var heightBefore = (await _osTestHelper.GetChainContextAsync()).BlockHeight; + for (var i = 0; i < blockNumber; i++) + { + await _osTestHelper.MinedOneBlock(); + } + + var heightAfter = (await _osTestHelper.GetChainContextAsync()).BlockHeight; + heightAfter.ShouldBe(heightBefore + blockNumber); } [Fact] From 39398fab899836a98bb60ca23e262978886f63d8 Mon Sep 17 00:00:00 2001 From: eanzhao Date: Wed, 27 Nov 2024 11:25:22 +0800 Subject: [PATCH 54/83] Will return new status if pending txs already expired. --- .../Services/TransactionResultAppService.cs | 16 ++++++++-------- .../BlockChainAppServiceTest.cs | 5 +---- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs index 29c4542ad2..2889473dad 100644 --- a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs +++ b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs @@ -152,6 +152,14 @@ public async Task GetTransactionResultV2Async(string trans output.Transaction = _objectMapper.Map(transaction); output.TransactionSize = transaction?.CalculateSize() ?? 0; + var chain = await _blockchainService.GetChainAsync(); + if (transactionResult.Status == TransactionResultStatus.Pending && + chain.BestChainHeight - output.Transaction?.RefBlockNumber > KernelConstants.ReferenceBlockValidPeriod) + { + output.StatusV2 = TransactionResultStatus.Expired.ToString().ToUpper(); + return output; + } + if (transactionResult.Status != TransactionResultStatus.NotExisted) { await FormatTransactionParamsAsync(output.Transaction, transaction.Params); @@ -179,14 +187,6 @@ await _transactionResultProxyService.InvalidTransactionResultService.GetInvalidT return output; } } - - var chain = await _blockchainService.GetChainAsync(); - if (chain.BestChainHeight - output.Transaction?.RefBlockNumber > KernelConstants.ReferenceBlockValidPeriod - && transactionResult.Status == TransactionResultStatus.NotExisted) - { - output.StatusV2 = TransactionResultStatus.Expired.ToString().ToUpper(); - return output; - } return output; } diff --git a/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs b/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs index 85bb6021f2..c4fc96777d 100644 --- a/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs +++ b/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs @@ -698,14 +698,11 @@ public async Task Get_TransactionResultV2_Expired_Test() // Broadcast expired transaction await _osTestHelper.BroadcastTransactions(new List { transaction }); - - // Try to package this transaction - await _osTestHelper.MinedOneBlock(); // Check transaction status var response = await GetResponseAsObjectAsync( $"/api/blockChain/transactionResultV2?transactionId={transactionHex}"); - // response.StatusV2.ShouldBe(TransactionResultStatus.Expired.ToString()); + response.StatusV2.ShouldBe(TransactionResultStatus.Expired.ToString().ToUpper()); } private async Task MineSomeBlocks(int blockNumber) From c4a291ca962c1ced6a00f6432073c6485c726c5e Mon Sep 17 00:00:00 2001 From: "jim.dong" Date: Wed, 4 Dec 2024 11:48:34 +0800 Subject: [PATCH 55/83] TransactionResult optimization, add a new method GetTransactionResultV2Async --- .../Services/TransactionResultAppService.cs | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs index 8bdc750025..01d4272b64 100644 --- a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs +++ b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs @@ -120,16 +120,6 @@ await _transactionResultProxyService.InvalidTransactionResultService.GetInvalidT return output; } } - - var chain = await _blockchainService.GetChainAsync(); - if (chain.BestChainHeight - output.Transaction.RefBlockNumber > KernelConstants.ReferenceBlockValidPeriod - && transactionResult.Status == TransactionResultStatus.NotExisted) - { - // set a the Error message to the output to infer that the transaction will never succeed. - var error = "The transaction is already expired, and it will never succeed."; - output.Error = TransactionErrorResolver.TakeErrorMessage(error, _webAppOptions.IsDebugMode); - return output; - } return output; } /// From a74faf0a64e5558a7f959fcae5bf8e365327a99a Mon Sep 17 00:00:00 2001 From: "jim.dong" Date: Thu, 5 Dec 2024 14:30:03 +0800 Subject: [PATCH 56/83] Remove inline transaction modification because of the early publishment of Extend seed expiration time --- .../AElf.Contracts.MultiToken/TokenContract_Helper.cs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/contract/AElf.Contracts.MultiToken/TokenContract_Helper.cs b/contract/AElf.Contracts.MultiToken/TokenContract_Helper.cs index f318c9fd27..3a78c60cbe 100644 --- a/contract/AElf.Contracts.MultiToken/TokenContract_Helper.cs +++ b/contract/AElf.Contracts.MultiToken/TokenContract_Helper.cs @@ -215,16 +215,10 @@ private Address ExtractTokenContractAddress(ByteString bytes) private void AssertCrossChainTransaction(Transaction originalTransaction, Address validAddress, params string[] validMethodNames) { - var validateResult = validMethodNames.Contains(MaybeRecoverInlineTransactionFunctionName(originalTransaction.MethodName)) + var validateResult = validMethodNames.Contains(originalTransaction.MethodName) && originalTransaction.To == validAddress; Assert(validateResult, "Invalid transaction."); } - - private static string MaybeRecoverInlineTransactionFunctionName(string methodName) - { - var parts = methodName.Split('.'); - return parts.Length > 1 ? parts[^2] : methodName; - } private void RegisterTokenInfo(TokenInfo tokenInfo) { From 2a62de270ea20d72e9d968c5b84ca2033c37901e Mon Sep 17 00:00:00 2001 From: "jim.dong" Date: Sat, 7 Dec 2024 15:27:00 +0800 Subject: [PATCH 57/83] update StatusV2 to StatusWithBVP --- .../Dto/TransactionResultDto.cs | 4 ++-- .../Services/TransactionResultAppService.cs | 8 ++++---- .../BlockChainAppServiceTest.cs | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/AElf.WebApp.Application.Chain/Dto/TransactionResultDto.cs b/src/AElf.WebApp.Application.Chain/Dto/TransactionResultDto.cs index 115643789b..49459d3dc5 100644 --- a/src/AElf.WebApp.Application.Chain/Dto/TransactionResultDto.cs +++ b/src/AElf.WebApp.Application.Chain/Dto/TransactionResultDto.cs @@ -6,10 +6,10 @@ public class TransactionResultDto { public string TransactionId { get; set; } - [Obsolete("The Status is obsolete. Use StatusV2 instead.")] + [Obsolete("The Status is obsolete. Use StatusWithBVP instead.")] public string Status { get; set; } - public string StatusV2 { get; set; } + public string StatusWithBVP { get; set; } public LogEventDto[] Logs { get; set; } diff --git a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs index 01d4272b64..1faccef3bb 100644 --- a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs +++ b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs @@ -144,7 +144,7 @@ public async Task GetTransactionResultV2Async(string trans var output = _objectMapper.GetMapper() .Map(transactionResult, opt => opt.Items[TransactionProfile.ErrorTrace] = _webAppOptions.IsDebugMode); - output.StatusV2 = output.Status; + output.StatusWithBVP = output.Status; var transaction = await _transactionManager.GetTransactionAsync(transactionResult.TransactionId); output.Transaction = _objectMapper.Map(transaction); @@ -154,7 +154,7 @@ public async Task GetTransactionResultV2Async(string trans if (transactionResult.Status == TransactionResultStatus.Pending && chain.BestChainHeight - output.Transaction?.RefBlockNumber > KernelConstants.ReferenceBlockValidPeriod) { - output.StatusV2 = TransactionResultStatus.Expired.ToString().ToUpper(); + output.StatusWithBVP = TransactionResultStatus.Expired.ToString().ToUpper(); return output; } @@ -167,7 +167,7 @@ public async Task GetTransactionResultV2Async(string trans var validationStatus = _transactionResultStatusCacheProvider.GetTransactionResultStatus(transactionIdHash); if (validationStatus != null) { - output.StatusV2 = validationStatus.TransactionResultStatus.ToString().ToUpper(); + output.StatusWithBVP = validationStatus.TransactionResultStatus.ToString().ToUpper(); output.Error = TransactionErrorResolver.TakeErrorMessage(validationStatus.Error, _webAppOptions.IsDebugMode); return output; @@ -180,7 +180,7 @@ await _transactionResultProxyService.InvalidTransactionResultService.GetInvalidT transactionIdHash); if (failedTransactionResult != null) { - output.StatusV2 = failedTransactionResult.Status.ToString().ToUpper(); + output.StatusWithBVP = failedTransactionResult.Status.ToString().ToUpper(); output.Error = failedTransactionResult.Error; return output; } diff --git a/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs b/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs index c4fc96777d..926798cbe1 100644 --- a/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs +++ b/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs @@ -702,7 +702,7 @@ public async Task Get_TransactionResultV2_Expired_Test() // Check transaction status var response = await GetResponseAsObjectAsync( $"/api/blockChain/transactionResultV2?transactionId={transactionHex}"); - response.StatusV2.ShouldBe(TransactionResultStatus.Expired.ToString().ToUpper()); + response.StatusWithBVP.ShouldBe(TransactionResultStatus.Expired.ToString().ToUpper()); } private async Task MineSomeBlocks(int blockNumber) From d38683fde34978e369ead18c33630360e2421707 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Thu, 12 Dec 2024 14:47:15 +0800 Subject: [PATCH 58/83] Remove publish config in main and side project --- .../AElf.Blockchains.MainChain.csproj | 2 -- .../AElf.Blockchains.SideChain.csproj | 2 -- 2 files changed, 4 deletions(-) diff --git a/src/AElf.Blockchains.MainChain/AElf.Blockchains.MainChain.csproj b/src/AElf.Blockchains.MainChain/AElf.Blockchains.MainChain.csproj index 7097bb2748..c99ca2bf21 100644 --- a/src/AElf.Blockchains.MainChain/AElf.Blockchains.MainChain.csproj +++ b/src/AElf.Blockchains.MainChain/AElf.Blockchains.MainChain.csproj @@ -5,8 +5,6 @@ 0436 Main module for a mainchain node. - Release - true diff --git a/src/AElf.Blockchains.SideChain/AElf.Blockchains.SideChain.csproj b/src/AElf.Blockchains.SideChain/AElf.Blockchains.SideChain.csproj index 063a9d5ebf..9364aac96b 100644 --- a/src/AElf.Blockchains.SideChain/AElf.Blockchains.SideChain.csproj +++ b/src/AElf.Blockchains.SideChain/AElf.Blockchains.SideChain.csproj @@ -3,8 +3,6 @@ net8.0 Main module for a sidechain node. - Release - true 1701;1702 From 29143a2417faf033328f3cc1b76966b9e73df13e Mon Sep 17 00:00:00 2001 From: "jim.dong" Date: Sat, 14 Dec 2024 15:09:09 +0800 Subject: [PATCH 59/83] token contract add inline transaction modification --- .../AElf.Contracts.MultiToken/TokenContract_Helper.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/contract/AElf.Contracts.MultiToken/TokenContract_Helper.cs b/contract/AElf.Contracts.MultiToken/TokenContract_Helper.cs index 3a78c60cbe..f318c9fd27 100644 --- a/contract/AElf.Contracts.MultiToken/TokenContract_Helper.cs +++ b/contract/AElf.Contracts.MultiToken/TokenContract_Helper.cs @@ -215,10 +215,16 @@ private Address ExtractTokenContractAddress(ByteString bytes) private void AssertCrossChainTransaction(Transaction originalTransaction, Address validAddress, params string[] validMethodNames) { - var validateResult = validMethodNames.Contains(originalTransaction.MethodName) + var validateResult = validMethodNames.Contains(MaybeRecoverInlineTransactionFunctionName(originalTransaction.MethodName)) && originalTransaction.To == validAddress; Assert(validateResult, "Invalid transaction."); } + + private static string MaybeRecoverInlineTransactionFunctionName(string methodName) + { + var parts = methodName.Split('.'); + return parts.Length > 1 ? parts[^2] : methodName; + } private void RegisterTokenInfo(TokenInfo tokenInfo) { From 6008ea59dcaf9711e1f154478c34850d77f75cb4 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Tue, 17 Dec 2024 11:47:11 +0800 Subject: [PATCH 60/83] Revert code --- .../Module/CallAndBranchCounts/Patcher.cs | 16 +--------------- 1 file changed, 1 insertion(+), 15 deletions(-) diff --git a/src/AElf.CSharp.CodeOps/Patchers/Module/CallAndBranchCounts/Patcher.cs b/src/AElf.CSharp.CodeOps/Patchers/Module/CallAndBranchCounts/Patcher.cs index 09b8581feb..bdac2a7575 100644 --- a/src/AElf.CSharp.CodeOps/Patchers/Module/CallAndBranchCounts/Patcher.cs +++ b/src/AElf.CSharp.CodeOps/Patchers/Module/CallAndBranchCounts/Patcher.cs @@ -17,7 +17,7 @@ public void Patch(ModuleDefinition module) return; // ReSharper disable once IdentifierTypo - var nmspace = module.Types.Where(IsContractType).Single().Namespace; + var nmspace = module.Types.Single(m => m.BaseType is TypeDefinition).Namespace; var proxyBuilder = new Patch(module, nmspace); @@ -28,20 +28,6 @@ public void Patch(ModuleDefinition module) module.Types.Add(proxyBuilder.ObserverType); } - private static bool IsContractType(TypeDefinition type) - { - if (type.FullName.StartsWith("AElf.Sdk.CSharp.CSharpSmartContract`1")) - return true; - if (type.BaseType is TypeDefinition baseType) - return IsContractType(baseType); - if(type.BaseType is GenericInstanceType baseType0) - return IsContractType(baseType0); - return false; - } - private static bool IsContractType(GenericInstanceType type) - { - return type.FullName.StartsWith("AElf.Sdk.CSharp.CSharpSmartContract`1"); - } } internal class MethodPatcher From 77ed70a6aeada6d12433715849ea542663900972 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Wed, 18 Dec 2024 10:57:56 +0800 Subject: [PATCH 61/83] try to skip issue that node can not produce --- src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs b/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs index 6c42b3605c..d4762479c6 100644 --- a/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs +++ b/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs @@ -44,6 +44,7 @@ public Task HandleEventAsync(ConsensusRequestMiningEventData eventData) var chain = await _blockchainService.GetChainAsync(); if (eventData.PreviousBlockHash != chain.BestChainHash) { + await TriggerConsensusEventAsync(chain.BestChainHash, chain.BestChainHeight); Logger.LogDebug("Mining canceled because best chain already updated"); return; } From 334079102e2912a6129a3acf9306484060db2563 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Wed, 18 Dec 2024 14:12:34 +0800 Subject: [PATCH 62/83] Remove TriggerConsensusEventAsync --- src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs b/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs index d4762479c6..6c42b3605c 100644 --- a/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs +++ b/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs @@ -44,7 +44,6 @@ public Task HandleEventAsync(ConsensusRequestMiningEventData eventData) var chain = await _blockchainService.GetChainAsync(); if (eventData.PreviousBlockHash != chain.BestChainHash) { - await TriggerConsensusEventAsync(chain.BestChainHash, chain.BestChainHeight); Logger.LogDebug("Mining canceled because best chain already updated"); return; } From a584079519275183de74588eb20efde57cf7d674 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Wed, 18 Dec 2024 15:53:03 +0800 Subject: [PATCH 63/83] Add TriggerConsensusEventAsync for image --- src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs b/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs index 6c42b3605c..d4762479c6 100644 --- a/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs +++ b/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs @@ -44,6 +44,7 @@ public Task HandleEventAsync(ConsensusRequestMiningEventData eventData) var chain = await _blockchainService.GetChainAsync(); if (eventData.PreviousBlockHash != chain.BestChainHash) { + await TriggerConsensusEventAsync(chain.BestChainHash, chain.BestChainHeight); Logger.LogDebug("Mining canceled because best chain already updated"); return; } From 6bf28b9d2f0f1919a5f9422c5bd635ba9a633832 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Wed, 18 Dec 2024 16:53:47 +0800 Subject: [PATCH 64/83] remove TriggerConsensusEventAsync --- src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs b/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs index d4762479c6..6c42b3605c 100644 --- a/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs +++ b/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs @@ -44,7 +44,6 @@ public Task HandleEventAsync(ConsensusRequestMiningEventData eventData) var chain = await _blockchainService.GetChainAsync(); if (eventData.PreviousBlockHash != chain.BestChainHash) { - await TriggerConsensusEventAsync(chain.BestChainHash, chain.BestChainHeight); Logger.LogDebug("Mining canceled because best chain already updated"); return; } From 745b32666a73ae522bff9f94d017fff789be25ba Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Thu, 19 Dec 2024 05:11:10 +0800 Subject: [PATCH 65/83] add TriggerConsensusEventAsync --- src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs b/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs index 6c42b3605c..e39230885c 100644 --- a/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs +++ b/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs @@ -44,7 +44,8 @@ public Task HandleEventAsync(ConsensusRequestMiningEventData eventData) var chain = await _blockchainService.GetChainAsync(); if (eventData.PreviousBlockHash != chain.BestChainHash) { - Logger.LogDebug("Mining canceled because best chain already updated"); + await TriggerConsensusEventAsync(chain.BestChainHash, chain.BestChainHeight); + Logger.LogDebug("Mining canceled because best chain already updated 1"); return; } From 3222d1cba33e332f2d93df034c8690015e19fa7d Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Thu, 19 Dec 2024 07:12:39 +0800 Subject: [PATCH 66/83] Add log --- src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs b/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs index e39230885c..11c8937392 100644 --- a/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs +++ b/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs @@ -44,6 +44,7 @@ public Task HandleEventAsync(ConsensusRequestMiningEventData eventData) var chain = await _blockchainService.GetChainAsync(); if (eventData.PreviousBlockHash != chain.BestChainHash) { + Logger.LogDebug($"PreviousBlockHash:{eventData.PreviousBlockHash},BestChainHash:{chain.BestChainHash}"); await TriggerConsensusEventAsync(chain.BestChainHash, chain.BestChainHeight); Logger.LogDebug("Mining canceled because best chain already updated 1"); return; From c522ab92827a125f76f116e08dedd9722d330ec1 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Thu, 19 Dec 2024 08:24:23 +0800 Subject: [PATCH 67/83] Add log --- src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs b/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs index 11c8937392..6df35205e5 100644 --- a/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs +++ b/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs @@ -44,7 +44,7 @@ public Task HandleEventAsync(ConsensusRequestMiningEventData eventData) var chain = await _blockchainService.GetChainAsync(); if (eventData.PreviousBlockHash != chain.BestChainHash) { - Logger.LogDebug($"PreviousBlockHash:{eventData.PreviousBlockHash},BestChainHash:{chain.BestChainHash}"); + Logger.LogDebug($"PreviousBlockHash:{eventData.PreviousBlockHash},BestChainHash:{chain.BestChainHash},BestChainHeight:{chain.BestChainHeight},preHeight:{eventData.PreviousBlockHeight}"); await TriggerConsensusEventAsync(chain.BestChainHash, chain.BestChainHeight); Logger.LogDebug("Mining canceled because best chain already updated 1"); return; From 692c6b2a3072438c1bd0557b11a616378a44ec00 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Thu, 19 Dec 2024 09:49:16 +0800 Subject: [PATCH 68/83] 1. Remove log and resolve issue --- .../IrreversibleBlockHeightUnacceptableLogEventProcessor.cs | 6 +++++- src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs | 4 +--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/src/AElf.Kernel.Consensus.AEDPoS/Application/IrreversibleBlockHeightUnacceptableLogEventProcessor.cs b/src/AElf.Kernel.Consensus.AEDPoS/Application/IrreversibleBlockHeightUnacceptableLogEventProcessor.cs index 5ca2448229..4b5e3cab43 100644 --- a/src/AElf.Kernel.Consensus.AEDPoS/Application/IrreversibleBlockHeightUnacceptableLogEventProcessor.cs +++ b/src/AElf.Kernel.Consensus.AEDPoS/Application/IrreversibleBlockHeightUnacceptableLogEventProcessor.cs @@ -53,12 +53,16 @@ protected override async Task ProcessLogEventAsync(Block block, LogEvent logEven if (distanceToLib.DistanceToIrreversibleBlockHeight > 0) { + var chain = await _blockchainService.GetChainAsync(); Logger.LogDebug($"Distance to lib height: {distanceToLib.DistanceToIrreversibleBlockHeight}"); + if ( block.Height - chain.LastIrreversibleBlockHeight < distanceToLib.DistanceToIrreversibleBlockHeight/2) + { + return; + } Logger.LogDebug("Will rollback to lib height."); _taskQueueManager.Enqueue( async () => { - var chain = await _blockchainService.GetChainAsync(); await _blockchainService.ResetChainToLibAsync(chain); }, KernelConstants.UpdateChainQueueName); } diff --git a/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs b/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs index 6df35205e5..6c42b3605c 100644 --- a/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs +++ b/src/AElf.Kernel/ConsensusRequestMiningEventHandler.cs @@ -44,9 +44,7 @@ public Task HandleEventAsync(ConsensusRequestMiningEventData eventData) var chain = await _blockchainService.GetChainAsync(); if (eventData.PreviousBlockHash != chain.BestChainHash) { - Logger.LogDebug($"PreviousBlockHash:{eventData.PreviousBlockHash},BestChainHash:{chain.BestChainHash},BestChainHeight:{chain.BestChainHeight},preHeight:{eventData.PreviousBlockHeight}"); - await TriggerConsensusEventAsync(chain.BestChainHash, chain.BestChainHeight); - Logger.LogDebug("Mining canceled because best chain already updated 1"); + Logger.LogDebug("Mining canceled because best chain already updated"); return; } From b8fb0d8aea94c9a6102c1623319c6a79f85d7be5 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Fri, 20 Dec 2024 11:32:14 +0800 Subject: [PATCH 69/83] Remove unused code --- .../Validators/Whitelist/IWhitelistProvider.cs | 1 + .../IrreversibleBlockHeightUnacceptableLogEventProcessor.cs | 6 +----- src/AElf.Types/Types/BigIntValue.cs | 1 - .../MultiTokenContractTestBase.cs | 3 --- 4 files changed, 2 insertions(+), 9 deletions(-) diff --git a/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs b/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs index 1d50b2d12d..1c7a30fa38 100644 --- a/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs +++ b/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs @@ -49,6 +49,7 @@ private void WhitelistAssemblies(Whitelist whitelist) .Assembly(typeof(IMethod).Assembly, Trust.Full) // AElf.CSharp.Core .Assembly(typeof(SecretSharingHelper).Assembly, Trust.Partial) // AElf.Cryptography .Assembly(typeof(ISmartContractBridgeContext).Assembly, Trust.Full) // AElf.Kernel.SmartContract.Shared + .Assembly(typeof(Groth16.Net.Verifier).Assembly, Trust.Full) // AElf.Cryptography.ECDSA ; } diff --git a/src/AElf.Kernel.Consensus.AEDPoS/Application/IrreversibleBlockHeightUnacceptableLogEventProcessor.cs b/src/AElf.Kernel.Consensus.AEDPoS/Application/IrreversibleBlockHeightUnacceptableLogEventProcessor.cs index 4b5e3cab43..5ca2448229 100644 --- a/src/AElf.Kernel.Consensus.AEDPoS/Application/IrreversibleBlockHeightUnacceptableLogEventProcessor.cs +++ b/src/AElf.Kernel.Consensus.AEDPoS/Application/IrreversibleBlockHeightUnacceptableLogEventProcessor.cs @@ -53,16 +53,12 @@ protected override async Task ProcessLogEventAsync(Block block, LogEvent logEven if (distanceToLib.DistanceToIrreversibleBlockHeight > 0) { - var chain = await _blockchainService.GetChainAsync(); Logger.LogDebug($"Distance to lib height: {distanceToLib.DistanceToIrreversibleBlockHeight}"); - if ( block.Height - chain.LastIrreversibleBlockHeight < distanceToLib.DistanceToIrreversibleBlockHeight/2) - { - return; - } Logger.LogDebug("Will rollback to lib height."); _taskQueueManager.Enqueue( async () => { + var chain = await _blockchainService.GetChainAsync(); await _blockchainService.ResetChainToLibAsync(chain); }, KernelConstants.UpdateChainQueueName); } diff --git a/src/AElf.Types/Types/BigIntValue.cs b/src/AElf.Types/Types/BigIntValue.cs index f65c8897a3..bd8c446065 100644 --- a/src/AElf.Types/Types/BigIntValue.cs +++ b/src/AElf.Types/Types/BigIntValue.cs @@ -207,6 +207,5 @@ private static bool LessThan(in BigIntValue a, in BigIntValue b) } #endregion - } } \ No newline at end of file diff --git a/test/AElf.Contracts.MultiToken.Tests/MultiTokenContractTestBase.cs b/test/AElf.Contracts.MultiToken.Tests/MultiTokenContractTestBase.cs index 62a7f23ec6..232a5f5b8b 100644 --- a/test/AElf.Contracts.MultiToken.Tests/MultiTokenContractTestBase.cs +++ b/test/AElf.Contracts.MultiToken.Tests/MultiTokenContractTestBase.cs @@ -240,7 +240,4 @@ internal async Task> CreateMutiTokenWithExceptionAsync( await CreateSeedNftAsync(stub, createInput); return await stub.Create.SendWithExceptionAsync(createInput); } - - - } \ No newline at end of file From 586a98aa5246aa8806d2300ff467ad596ea21a45 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Mon, 23 Dec 2024 19:35:55 +0800 Subject: [PATCH 70/83] Remove cross-aa code --- .../TokenContract_Helper.cs | 8 +- protobuf/test_virtual_address_contract.proto | 6 -- ...nitTestPlainTransactionExecutingService.cs | 5 +- .../Extensions/TransactionExtensions.cs | 13 --- .../AElf.Kernel.SmartContract.csproj | 3 - .../PlainTransactionExecutingService.cs | 102 +----------------- .../Dto/SingleTransactionExecutingDto.cs | 1 - .../ITransactionContext.cs | 1 - .../InlineWithTransactionIdCounter.cs | 18 ---- .../TransactionContext.cs | 1 - .../Application/BlockExecutingService.cs | 34 ++---- .../TransactionValidationService.cs | 4 - .../Transaction/TransactionTrace.cs | 20 ---- src/AElf.Runtime.CSharp/Executive.cs | 6 -- src/AElf.Runtime.CSharp/TransactionConsts.cs | 6 -- .../Services/TransactionResultAppService.cs | 2 +- .../BVT/ElectionTests.cs | 88 --------------- .../Action.cs | 21 ---- .../Extensions/TransactionExtensionsTests.cs | 10 -- ...lainTransactionExecutingAsPluginService.cs | 4 +- 20 files changed, 21 insertions(+), 332 deletions(-) delete mode 100644 src/AElf.Kernel.SmartContract/InlineWithTransactionIdCounter.cs delete mode 100644 src/AElf.Runtime.CSharp/TransactionConsts.cs diff --git a/contract/AElf.Contracts.MultiToken/TokenContract_Helper.cs b/contract/AElf.Contracts.MultiToken/TokenContract_Helper.cs index f318c9fd27..3a78c60cbe 100644 --- a/contract/AElf.Contracts.MultiToken/TokenContract_Helper.cs +++ b/contract/AElf.Contracts.MultiToken/TokenContract_Helper.cs @@ -215,16 +215,10 @@ private Address ExtractTokenContractAddress(ByteString bytes) private void AssertCrossChainTransaction(Transaction originalTransaction, Address validAddress, params string[] validMethodNames) { - var validateResult = validMethodNames.Contains(MaybeRecoverInlineTransactionFunctionName(originalTransaction.MethodName)) + var validateResult = validMethodNames.Contains(originalTransaction.MethodName) && originalTransaction.To == validAddress; Assert(validateResult, "Invalid transaction."); } - - private static string MaybeRecoverInlineTransactionFunctionName(string methodName) - { - var parts = methodName.Split('.'); - return parts.Length > 1 ? parts[^2] : methodName; - } private void RegisterTokenInfo(TokenInfo tokenInfo) { diff --git a/protobuf/test_virtual_address_contract.proto b/protobuf/test_virtual_address_contract.proto index 992ad86fbf..cdfb14fa05 100644 --- a/protobuf/test_virtual_address_contract.proto +++ b/protobuf/test_virtual_address_contract.proto @@ -14,7 +14,6 @@ service VirtualAddressContract { option (aelf.base) = "acs1.proto"; rpc VirtualAddressVote(VirtualAddressVoteInput) returns (google.protobuf.Empty); - rpc VirtualAddressVoteWithInline(VirtualAddressVoteWithCountInput) returns (google.protobuf.Empty); rpc VirtualAddressWithdraw(aelf.Hash) returns (google.protobuf.Empty); rpc VirtualAddressChangeVotingOption(VirtualAddressChangeVotingOptionInput) returns (google.protobuf.Empty); rpc VirtualAddressClaimProfit(VirtualAddressClaimProfitInput) returns (google.protobuf.Empty); @@ -33,11 +32,6 @@ message VirtualAddressVoteInput { aelf.Hash token = 4; } -message VirtualAddressVoteWithCountInput { - VirtualAddressVoteInput vote_input = 1; // Existing input type - int32 count = 2; // Additional count input -} - message VirtualAddressChangeVotingOptionInput { bool is_reset = 1; aelf.Hash vote_id = 2; diff --git a/src/AElf.ContractTestKit.AEDPoSExtension/UnitTestPlainTransactionExecutingService.cs b/src/AElf.ContractTestKit.AEDPoSExtension/UnitTestPlainTransactionExecutingService.cs index c3eabef06d..37f1b50c43 100644 --- a/src/AElf.ContractTestKit.AEDPoSExtension/UnitTestPlainTransactionExecutingService.cs +++ b/src/AElf.ContractTestKit.AEDPoSExtension/UnitTestPlainTransactionExecutingService.cs @@ -2,7 +2,6 @@ using System.Threading; using System.Threading.Tasks; using AElf.Kernel; -using AElf.Kernel.Blockchain.Application; using AElf.Kernel.FeatureDisable.Core; using AElf.Kernel.SmartContract; using AElf.Kernel.SmartContract.Application; @@ -14,8 +13,8 @@ public class UnitTestPlainTransactionExecutingService : PlainTransactionExecutin { public UnitTestPlainTransactionExecutingService(ISmartContractExecutiveService smartContractExecutiveService, IEnumerable postPlugins, IEnumerable prePlugins, - ITransactionContextFactory transactionContextFactory, IFeatureDisableService featureDisableService,IBlockchainService blockchainService) : base( - smartContractExecutiveService, postPlugins, prePlugins, transactionContextFactory, featureDisableService,blockchainService) + ITransactionContextFactory transactionContextFactory, IFeatureDisableService featureDisableService) : base( + smartContractExecutiveService, postPlugins, prePlugins, transactionContextFactory, featureDisableService) { } diff --git a/src/AElf.Kernel.Core/Extensions/TransactionExtensions.cs b/src/AElf.Kernel.Core/Extensions/TransactionExtensions.cs index 6a845b9df4..4c3e8e3242 100644 --- a/src/AElf.Kernel.Core/Extensions/TransactionExtensions.cs +++ b/src/AElf.Kernel.Core/Extensions/TransactionExtensions.cs @@ -16,10 +16,6 @@ public static int Size(this Transaction transaction) public static bool VerifySignature(this Transaction transaction) { - if (transaction.IsInlineWithTransactionId()) - { - return true; - } if (!transaction.VerifyFields()) return false; @@ -31,16 +27,7 @@ public static bool VerifySignature(this Transaction transaction) public static bool VerifyExpiration(this Transaction transaction, long chainBranchBlockHeight) { - if (transaction.IsInlineWithTransactionId()) - { - return true; - } return transaction.RefBlockNumber <= chainBranchBlockHeight && transaction.GetExpiryBlockNumber() > chainBranchBlockHeight; } - - public static bool IsInlineWithTransactionId(this Transaction transaction) - { - return transaction.MethodName.Contains("."); - } } \ No newline at end of file diff --git a/src/AElf.Kernel.SmartContract/AElf.Kernel.SmartContract.csproj b/src/AElf.Kernel.SmartContract/AElf.Kernel.SmartContract.csproj index 2358852342..ab2cf443cf 100644 --- a/src/AElf.Kernel.SmartContract/AElf.Kernel.SmartContract.csproj +++ b/src/AElf.Kernel.SmartContract/AElf.Kernel.SmartContract.csproj @@ -22,8 +22,5 @@ Protobuf\Proto\virtual_transaction.proto - - Protobuf\Proto\inline_transaction.proto - \ No newline at end of file diff --git a/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs b/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs index d3531087cd..79b09034f9 100644 --- a/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs +++ b/src/AElf.Kernel.SmartContract/Application/PlainTransactionExecutingService.cs @@ -3,8 +3,6 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; -using AElf.CSharp.Core.Extension; -using AElf.Kernel.Blockchain.Application; using AElf.Kernel.FeatureDisable.Core; using AElf.Kernel.SmartContract.Domain; using AElf.Kernel.SmartContract.Infrastructure; @@ -25,17 +23,14 @@ public class PlainTransactionExecutingService : IPlainTransactionExecutingServic private readonly ISmartContractExecutiveService _smartContractExecutiveService; private readonly ITransactionContextFactory _transactionContextFactory; private readonly IFeatureDisableService _featureDisableService; - private readonly IBlockchainService _blockchainService; public PlainTransactionExecutingService(ISmartContractExecutiveService smartContractExecutiveService, IEnumerable postPlugins, IEnumerable prePlugins, - ITransactionContextFactory transactionContextFactory, IFeatureDisableService featureDisableService, - IBlockchainService blockchainService) + ITransactionContextFactory transactionContextFactory, IFeatureDisableService featureDisableService) { _smartContractExecutiveService = smartContractExecutiveService; _transactionContextFactory = transactionContextFactory; _featureDisableService = featureDisableService; - _blockchainService = blockchainService; _prePlugins = GetUniquePlugins(prePlugins); _postPlugins = GetUniquePlugins(postPlugins); Logger = NullLogger.Instance; @@ -66,7 +61,6 @@ public async Task> ExecuteAsync(TransactionExecutingDto var singleTxExecutingDto = new SingleTransactionExecutingDto { Depth = 0, - InlineWithTransactionIdCounter = new InlineWithTransactionIdCounter(), ChainContext = groupChainContext, Transaction = transaction, CurrentBlockTime = transactionExecutingDto.BlockHeader.Time, @@ -77,7 +71,7 @@ public async Task> ExecuteAsync(TransactionExecutingDto var transactionExecutionTask = Task.Run(() => ExecuteOneAsync(singleTxExecutingDto, cancellationToken), cancellationToken); - trace = await transactionExecutionTask; + trace = await transactionExecutionTask.WithCancellation(cancellationToken); } catch (OperationCanceledException) { @@ -96,7 +90,7 @@ public async Task> ExecuteAsync(TransactionExecutingDto var result = GetTransactionResult(trace, transactionExecutingDto.BlockHeader.Height); var returnSet = GetReturnSet(trace, result); - returnSets.AddRange(returnSet); + returnSets.Add(returnSet); } return returnSets; @@ -181,22 +175,14 @@ protected virtual async Task ExecuteOneAsync( #endregion - var methodName = txContext.Transaction.MethodName; - var originMethodName = MaybeRecoverInlineTransactionFunctionName(methodName); - txContext.Transaction.MethodName = originMethodName; - await executive.ApplyAsync(txContext); if (txContext.Trace.IsSuccessful()) - { - // Maybe layered method name. - txContext.Transaction.MethodName = methodName; await ExecuteInlineTransactions(singleTxExecutingDto.Depth, singleTxExecutingDto.CurrentBlockTime, txContext, internalStateCache, internalChainContext, singleTxExecutingDto.OriginTransactionId, cancellationToken); - } #region PostTransaction @@ -235,40 +221,11 @@ private async Task ExecuteInlineTransactions(int depth, Timestamp currentBlockTi { var trace = txContext.Trace; internalStateCache.Update(txContext.Trace.GetStateSets()); - - var methodNameCount = new Dictionary(); foreach (var inlineTx in txContext.Trace.InlineTransactions) { - var needTxId = NeedTransactionId(inlineTx.MethodName); - if (needTxId) - { - txContext.InlineWithTransactionIdCounter.Increment(); - if (!methodNameCount.TryAdd(inlineTx.MethodName, 0)) - { - methodNameCount[inlineTx.MethodName]++; - inlineTx.MethodName = - GenerateLayeredMethodNameForInlineTransaction( - txContext.Transaction, - inlineTx.MethodName, - methodNameCount[inlineTx.MethodName] - ); - } - else - { - inlineTx.MethodName = GenerateLayeredMethodNameForInlineTransaction( - txContext.Transaction, - inlineTx.MethodName, - 0 - ); - } - - await _blockchainService.AddTransactionsAsync([inlineTx]); - } - var singleTxExecutingDto = new SingleTransactionExecutingDto { Depth = depth + 1, - InlineWithTransactionIdCounter = txContext.InlineWithTransactionIdCounter, ChainContext = internalChainContext, Transaction = inlineTx, CurrentBlockTime = currentBlockTime, @@ -289,25 +246,6 @@ private async Task ExecuteInlineTransactions(int depth, Timestamp currentBlockTi } } - private static string GenerateLayeredMethodNameForInlineTransaction(Transaction parentTx, string inlineFunctionName, - int index) - { - var parentTxMethodName = parentTx.MethodName; - inlineFunctionName = inlineFunctionName.StartsWith('.') ? inlineFunctionName[1..] : inlineFunctionName; - return $"{parentTx.GetHash().ToHex()}.{parentTxMethodName}.{inlineFunctionName}.{index}"; - } - - private static string MaybeRecoverInlineTransactionFunctionName(string methodName) - { - var parts = methodName.Split('.'); - return parts.Length > 1 ? parts[^2] : methodName; - } - - private static bool NeedTransactionId(string methodName) - { - return methodName.Contains('.'); - } - private async Task ExecutePluginOnPreTransactionStageAsync(IExecutive executive, ITransactionContext txContext, Timestamp currentBlockTime, @@ -455,7 +393,7 @@ private TransactionResult GetTransactionResult(TransactionTrace trace, long bloc return txResult; } - private IEnumerable GetReturnSet(TransactionTrace trace, TransactionResult result) + private ExecutionReturnSet GetReturnSet(TransactionTrace trace, TransactionResult result) { var returnSet = new ExecutionReturnSet { @@ -464,41 +402,12 @@ private IEnumerable GetReturnSet(TransactionTrace trace, Tra Bloom = result.Bloom, TransactionResult = result }; - var returnSets = new List { returnSet }; if (trace.IsSuccessful()) { var transactionExecutingStateSets = trace.GetStateSets(); returnSet = GetReturnSet(returnSet, transactionExecutingStateSets); returnSet.ReturnValue = trace.ReturnValue; - - var inlineTxWithIdList = trace.GetAllInlineTransactions().Where(tx => NeedTransactionId(tx.MethodName)); - foreach (var inlineTx in inlineTxWithIdList) - { - var inlineTxId = inlineTx.GetHash(); - var inlineReturnSet = new ExecutionReturnSet - { - TransactionId = inlineTxId, - Status = TransactionResultStatus.Mined, - TransactionResult = new TransactionResult - { - TransactionId = inlineTxId, - BlockNumber = result.BlockNumber, - Status = TransactionResultStatus.Mined - } - }; - - // No need to execute GetReturnSet method, because changes are already set to `returnSet`. - - returnSets.Add(inlineReturnSet); - - Logger.LogWarning($"Inline tx id: {inlineTx.GetHash().ToHex()}\n{inlineTx}"); - var log = new InlineTransactionCreated() - { - Transaction = inlineTx - }; - returnSet.TransactionResult.Logs.Add(log.ToLogEvent(inlineTx.To)); - } } else { @@ -517,7 +426,7 @@ private IEnumerable GetReturnSet(TransactionTrace trace, Tra var reads = trace.GetFlattenedReads(); foreach (var read in reads) returnSet.StateAccesses[read.Key] = read.Value; - return returnSets; + return returnSet; } private ExecutionReturnSet GetReturnSet(ExecutionReturnSet returnSet, @@ -567,7 +476,6 @@ protected ITransactionContext CreateTransactionContext(SingleTransactionExecutin singleTxExecutingDto.ChainContext, singleTxExecutingDto.OriginTransactionId, origin, singleTxExecutingDto.Depth, singleTxExecutingDto.CurrentBlockTime); - txContext.InlineWithTransactionIdCounter = singleTxExecutingDto.InlineWithTransactionIdCounter; return txContext; } } \ No newline at end of file diff --git a/src/AElf.Kernel.SmartContract/Dto/SingleTransactionExecutingDto.cs b/src/AElf.Kernel.SmartContract/Dto/SingleTransactionExecutingDto.cs index 9c50702cfa..7dfe93020b 100644 --- a/src/AElf.Kernel.SmartContract/Dto/SingleTransactionExecutingDto.cs +++ b/src/AElf.Kernel.SmartContract/Dto/SingleTransactionExecutingDto.cs @@ -13,5 +13,4 @@ public class SingleTransactionExecutingDto public bool IsCancellable { get; set; } = true; public Hash OriginTransactionId { get; set; } - public InlineWithTransactionIdCounter InlineWithTransactionIdCounter { get; set; } } \ No newline at end of file diff --git a/src/AElf.Kernel.SmartContract/ITransactionContext.cs b/src/AElf.Kernel.SmartContract/ITransactionContext.cs index 1d4ab59fbe..0f1a3cecad 100644 --- a/src/AElf.Kernel.SmartContract/ITransactionContext.cs +++ b/src/AElf.Kernel.SmartContract/ITransactionContext.cs @@ -16,5 +16,4 @@ public interface ITransactionContext Transaction Transaction { get; set; } TransactionTrace Trace { get; set; } IStateCache StateCache { get; set; } - InlineWithTransactionIdCounter InlineWithTransactionIdCounter { get; set; } } \ No newline at end of file diff --git a/src/AElf.Kernel.SmartContract/InlineWithTransactionIdCounter.cs b/src/AElf.Kernel.SmartContract/InlineWithTransactionIdCounter.cs deleted file mode 100644 index 1ae06c2504..0000000000 --- a/src/AElf.Kernel.SmartContract/InlineWithTransactionIdCounter.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System.Threading; - -namespace AElf.Kernel.SmartContract; - -public class InlineWithTransactionIdCounter -{ - private int _count = 0; - - public void Increment() - { - Interlocked.Increment(ref _count); - } - - public int GetCount() - { - return _count; - } -} \ No newline at end of file diff --git a/src/AElf.Kernel.SmartContract/TransactionContext.cs b/src/AElf.Kernel.SmartContract/TransactionContext.cs index 2e76fcf5b1..aaf3fe79e6 100644 --- a/src/AElf.Kernel.SmartContract/TransactionContext.cs +++ b/src/AElf.Kernel.SmartContract/TransactionContext.cs @@ -16,5 +16,4 @@ public class TransactionContext : ITransactionContext public Transaction Transaction { get; set; } public TransactionTrace Trace { get; set; } public IStateCache StateCache { get; set; } - public InlineWithTransactionIdCounter InlineWithTransactionIdCounter { get; set; } } \ No newline at end of file diff --git a/src/AElf.Kernel.SmartContractExecution/Application/BlockExecutingService.cs b/src/AElf.Kernel.SmartContractExecution/Application/BlockExecutingService.cs index e7538a59b0..6dcfca3178 100644 --- a/src/AElf.Kernel.SmartContractExecution/Application/BlockExecutingService.cs +++ b/src/AElf.Kernel.SmartContractExecution/Application/BlockExecutingService.cs @@ -55,13 +55,8 @@ public async Task ExecuteBlockAsync(BlockHeader blockHeader, CancellationToken cancellationToken) { Logger.LogTrace("Entered ExecuteBlockAsync"); - - var nonCancellable = nonCancellableTransactions.ToList() - .Where(tx => !tx.MethodName.Contains('.')).ToList(); - - var cancellable = cancellableTransactions.ToList() - .Where(tx => !tx.MethodName.Contains('.')).ToList(); - + var nonCancellable = nonCancellableTransactions.ToList(); + var cancellable = cancellableTransactions.ToList(); var nonCancellableReturnSets = await _transactionExecutingService.ExecuteAsync( new TransactionExecutingDto { BlockHeader = blockHeader, Transactions = nonCancellable }, @@ -73,16 +68,15 @@ await _transactionExecutingService.ExecuteAsync( if (!cancellationToken.IsCancellationRequested && cancellable.Count > 0) { - var txExecutingDto = new TransactionExecutingDto - { - BlockHeader = blockHeader, - Transactions = cancellable, - PartialBlockStateSet = returnSetCollection.ToBlockStateSet() - }; cancellableReturnSets = await _transactionExecutingService.ExecuteAsync( - txExecutingDto, cancellationToken); + new TransactionExecutingDto + { + BlockHeader = blockHeader, + Transactions = cancellable, + PartialBlockStateSet = returnSetCollection.ToBlockStateSet() + }, + cancellationToken); returnSetCollection.AddRange(cancellableReturnSets); - cancellable = txExecutingDto.Transactions.ToList(); Logger.LogTrace("Executed cancellable txs"); } @@ -125,15 +119,7 @@ private Task FillBlockAfterExecutionAsync(BlockHeader header, var allExecutedTransactionIds = transactions.Select(x => x.GetHash()).ToList(); var orderedReturnSets = executionReturnSetCollection.GetExecutionReturnSetList() - .OrderBy(d => allExecutedTransactionIds.IndexOf(d.TransactionId) >= 0 ? allExecutedTransactionIds.IndexOf(d.TransactionId) : int.MaxValue) - .ThenBy(d => d.TransactionId) - .ToList(); - - var inlineTxIds = orderedReturnSets - .Where(returnSet => !allExecutedTransactionIds.Contains(returnSet.TransactionId)) - .Select(returnSet => returnSet.TransactionId) - .ToList(); - allExecutedTransactionIds.AddRange(inlineTxIds); + .OrderBy(d => allExecutedTransactionIds.IndexOf(d.TransactionId)).ToList(); var block = new Block { diff --git a/src/AElf.Kernel.TransactionPool/Application/TransactionValidationService.cs b/src/AElf.Kernel.TransactionPool/Application/TransactionValidationService.cs index 10c4edc1b3..324cfb14d6 100644 --- a/src/AElf.Kernel.TransactionPool/Application/TransactionValidationService.cs +++ b/src/AElf.Kernel.TransactionPool/Application/TransactionValidationService.cs @@ -49,10 +49,6 @@ public async Task ValidateTransactionWhileCollectingAsync(IChainContext ch public async Task ValidateTransactionWhileSyncingAsync(Transaction transaction) { - if (transaction.IsInlineWithTransactionId()) - { - return true; - } var validationTasks = _transactionValidationProviders.AsParallel() .Where(provider => provider.ValidateWhileSyncing).Select(async provider => { diff --git a/src/AElf.Kernel.Types/Transaction/TransactionTrace.cs b/src/AElf.Kernel.Types/Transaction/TransactionTrace.cs index cd1f080432..fbf78286a0 100644 --- a/src/AElf.Kernel.Types/Transaction/TransactionTrace.cs +++ b/src/AElf.Kernel.Types/Transaction/TransactionTrace.cs @@ -89,24 +89,4 @@ public IEnumerable GetStateSets() foreach (var stateSet in stateSets) yield return stateSet; } } - - public List GetAllInlineTransactions() - { - var transactions = new List(); - var stack = new Stack(); - stack.Push(this); - - while (stack.Count > 0) - { - var currentTrace = stack.Pop(); - transactions.AddRange(currentTrace.InlineTransactions); - if (currentTrace.InlineTraces == null) continue; - foreach (var inlineTrace in currentTrace.InlineTraces) - { - stack.Push(inlineTrace); - } - } - - return transactions; - } } \ No newline at end of file diff --git a/src/AElf.Runtime.CSharp/Executive.cs b/src/AElf.Runtime.CSharp/Executive.cs index 48df0dd737..6cb47187c6 100644 --- a/src/AElf.Runtime.CSharp/Executive.cs +++ b/src/AElf.Runtime.CSharp/Executive.cs @@ -63,12 +63,6 @@ public Task ApplyAsync(ITransactionContext transactionContext) CurrentTransactionContext.Trace.Error = "\n" + "ExceededMaxCallDepth"; return Task.CompletedTask; } - if (CurrentTransactionContext.InlineWithTransactionIdCounter?.GetCount() > TransactionConsts.InlineWithTransactionIdLimit) - { - CurrentTransactionContext.Trace.ExecutionStatus = ExecutionStatus.ExceededMaxCallDepth; - CurrentTransactionContext.Trace.Error = "\n" + "failed.ExceededMaxInlineWithTransactionIdCount"; - return Task.CompletedTask; - } Execute(); } diff --git a/src/AElf.Runtime.CSharp/TransactionConsts.cs b/src/AElf.Runtime.CSharp/TransactionConsts.cs deleted file mode 100644 index 06e85b9d73..0000000000 --- a/src/AElf.Runtime.CSharp/TransactionConsts.cs +++ /dev/null @@ -1,6 +0,0 @@ -namespace AElf.Runtime.CSharp; - -public class TransactionConsts -{ - public const int InlineWithTransactionIdLimit = 5; -} \ No newline at end of file diff --git a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs index 1faccef3bb..1923b9f989 100644 --- a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs +++ b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs @@ -24,7 +24,7 @@ namespace AElf.WebApp.Application.Chain; public interface ITransactionResultAppService { Task GetTransactionResultAsync(string transactionId); - + Task GetTransactionResultV2Async(string transactionId); Task> GetTransactionResultsAsync(string blockHash, int offset = 0, diff --git a/test/AElf.Contracts.Election.Tests/BVT/ElectionTests.cs b/test/AElf.Contracts.Election.Tests/BVT/ElectionTests.cs index d6e44f057f..2ba363f220 100644 --- a/test/AElf.Contracts.Election.Tests/BVT/ElectionTests.cs +++ b/test/AElf.Contracts.Election.Tests/BVT/ElectionTests.cs @@ -1984,94 +1984,6 @@ await VirtualAddressContractStub.VirtualAddressVote.SendAsync(new VirtualAddress return result.ActiveVotingRecords.First().VoteId; } - [Fact] - public async Task VirtualAddress_Vote_WithInlineTxIdTest() - { - var amount = 100; - const int lockTime = 100 * 60 * 60 * 24; - var candidatesKeyPairs = await ElectionContract_AnnounceElection_Test(); - var candidateKeyPair = candidatesKeyPairs[0]; - - var address = await VirtualAddressContractStub.GetVirtualAddress.CallAsync(new Empty()); - var initBalance = 100000; - - await TokenContractStub.Transfer.SendAsync(new TransferInput - { - Amount = initBalance, - Symbol = "ELF", - To = address, - Memo = "test" - }); - - CheckBalance(address, "ELF", initBalance); - CheckBalance(address, "SHARE", 0); - CheckBalance(address, "VOTE", 0); - - var virtualAddressVoteInput = new VirtualAddressVoteInput - { - PubKey = candidateKeyPair.PublicKey.ToHex(), - Amount = amount, - EndTimestamp = TimestampHelper.GetUtcNow().AddSeconds(lockTime), - Token = HashHelper.ComputeFrom("token A") - }; - - await VirtualAddressContractStub.VirtualAddressVoteWithInline.SendAsync(new VirtualAddressVoteWithCountInput - { - VoteInput = virtualAddressVoteInput, - Count = 1 - }); - - var result = await ElectionContractStub.GetElectorVote.CallAsync(new StringValue - { - Value = address.ToBase58() - }); - result.ActiveVotedVotesAmount.ShouldBe(amount); - result = await ElectionContractStub.GetElectorVoteWithRecords.CallAsync(new StringValue - { - Value = address.ToBase58() - }); - result.ActiveVotedVotesAmount.ShouldBe(amount); - result = await ElectionContractStub.GetElectorVoteWithAllRecords.CallAsync(new StringValue - { - Value = address.ToBase58() - }); - result.AllVotedVotesAmount.ShouldBe(amount); - - CheckBalance(address, "ELF", initBalance - amount); - CheckBalance(address, "SHARE", amount); - CheckBalance(address, "VOTE", amount); - - await VirtualAddressContractStub.VirtualAddressVote.SendAsync(new VirtualAddressVoteInput - { - PubKey = candidateKeyPair.PublicKey.ToHex(), - Amount = amount, - EndTimestamp = TimestampHelper.GetUtcNow().AddSeconds(lockTime), - Token = HashHelper.ComputeFrom("token A") - }); - - result = await ElectionContractStub.GetElectorVote.CallAsync(new StringValue - { - Value = address.ToBase58() - }); - result.ActiveVotedVotesAmount.ShouldBe(amount + amount); - result = await ElectionContractStub.GetElectorVoteWithRecords.CallAsync(new StringValue - { - Value = address.ToBase58() - }); - result.ActiveVotedVotesAmount.ShouldBe(amount + amount); - result = await ElectionContractStub.GetElectorVoteWithAllRecords.CallAsync(new StringValue - { - Value = address.ToBase58() - }); - result.AllVotedVotesAmount.ShouldBe(amount + amount); - - CheckBalance(address, "ELF", initBalance - amount - amount); - CheckBalance(address, "SHARE", amount + amount); - CheckBalance(address, "VOTE", amount + amount); - - return result.ActiveVotingRecords.First().VoteId; - } - [Fact] public async Task VirtualAddress_Withdraw_Test() { diff --git a/test/AElf.Contracts.TestContract.VirtualAddress/Action.cs b/test/AElf.Contracts.TestContract.VirtualAddress/Action.cs index bc8edd7a81..295830ea1c 100644 --- a/test/AElf.Contracts.TestContract.VirtualAddress/Action.cs +++ b/test/AElf.Contracts.TestContract.VirtualAddress/Action.cs @@ -9,27 +9,6 @@ namespace AElf.Contracts.TestContract.VirtualAddress; public partial class Action : VirtualAddressContractContainer.VirtualAddressContractBase { - - public override Empty VirtualAddressVoteWithInline(VirtualAddressVoteWithCountInput input) - { - if (input.Count == null) return new Empty(); - Initialize(); - - for (int i = 0; i < input.Count; i++) - { - Context.SendVirtualInline(HashHelper.ComputeFrom("test"), State.ElectionContract.Value, ".Vote", new VoteMinerInput - { - CandidatePubkey = input.VoteInput.PubKey, - Amount = input.VoteInput.Amount, - EndTimestamp = input.VoteInput.EndTimestamp, - Token = input.VoteInput.Token - }.ToByteString()); - } - - - return new Empty(); - } - public override Empty VirtualAddressVote(VirtualAddressVoteInput input) { Initialize(); diff --git a/test/AElf.Kernel.Core.Tests/Extensions/TransactionExtensionsTests.cs b/test/AElf.Kernel.Core.Tests/Extensions/TransactionExtensionsTests.cs index 2fe628cb1f..daa6331365 100644 --- a/test/AElf.Kernel.Core.Tests/Extensions/TransactionExtensionsTests.cs +++ b/test/AElf.Kernel.Core.Tests/Extensions/TransactionExtensionsTests.cs @@ -46,14 +46,4 @@ public void VerifyExpiration_Test() transaction.VerifyExpiration(100).ShouldBeTrue(); transaction.VerifyExpiration(612).ShouldBeFalse(); } - - [Fact] - public void IsInlineWithTransactionId_Test() - { - var transaction = _kernelTestHelper.GenerateTransaction(100); - transaction.MethodName = ".vote"; - transaction.IsInlineWithTransactionId().ShouldBeTrue(); - transaction.MethodName = "vote"; - transaction.IsInlineWithTransactionId().ShouldBeFalse(); - } } \ No newline at end of file diff --git a/test/AElf.Kernel.SmartContract.ExecutionPluginForMethodFee.Tests/Service/PlainTransactionExecutingAsPluginService.cs b/test/AElf.Kernel.SmartContract.ExecutionPluginForMethodFee.Tests/Service/PlainTransactionExecutingAsPluginService.cs index cdda3f9e59..51d07eafe4 100644 --- a/test/AElf.Kernel.SmartContract.ExecutionPluginForMethodFee.Tests/Service/PlainTransactionExecutingAsPluginService.cs +++ b/test/AElf.Kernel.SmartContract.ExecutionPluginForMethodFee.Tests/Service/PlainTransactionExecutingAsPluginService.cs @@ -22,8 +22,8 @@ public class PlainTransactionExecutingAsPluginService : PlainTransactionExecutin public PlainTransactionExecutingAsPluginService (ISmartContractExecutiveService smartContractExecutiveService, IEnumerable postPlugins, IEnumerable prePlugins, - ITransactionContextFactory transactionContextFactory, IFeatureDisableService featureDisableService, IBlockchainService blockchainService) : base( - smartContractExecutiveService, postPlugins, prePlugins, transactionContextFactory, featureDisableService,blockchainService) + ITransactionContextFactory transactionContextFactory, IFeatureDisableService featureDisableService) : base( + smartContractExecutiveService, postPlugins, prePlugins, transactionContextFactory, featureDisableService) { _smartContractExecutiveService = smartContractExecutiveService; } From ff58f36cc1db3771bc42a507214c05d18b7e8830 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Tue, 24 Dec 2024 16:12:45 +0800 Subject: [PATCH 71/83] Adjust the implementation of zk function --- .../Whitelist/IWhitelistProvider.cs | 8 ++- .../AElf.Cryptography.csproj | 9 ++++ .../SecretSharing/SecretSharingHelper.cs | 48 +++++++++++++++++ .../AElf.Runtime.CSharp.csproj | 6 +-- .../CSharpSmartContractContext.cs | 54 +++++++++---------- 5 files changed, 94 insertions(+), 31 deletions(-) diff --git a/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs b/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs index 1c7a30fa38..4d525eac88 100644 --- a/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs +++ b/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs @@ -200,6 +200,12 @@ private void WhitelistAElfTypes(Whitelist whitelist) // Selectively allowed types and members .Namespace("AElf.Cryptography.SecretSharing", Permission.Denied, type => type .Type(typeof(SecretSharingHelper), Permission.Denied, member => member - .Member(nameof(SecretSharingHelper.DecodeSecret), Permission.Allowed))); + .Member(nameof(SecretSharingHelper.DecodeSecret), Permission.Allowed) + .Member(nameof(SecretSharingHelper.Ed25519Verify), Permission.Allowed) + .Member(nameof(SecretSharingHelper.Keccak256), Permission.Allowed) + .Member(nameof(SecretSharingHelper.Bn254G1Mul), Permission.Allowed) + .Member(nameof(SecretSharingHelper.Bn254Pairing), Permission.Allowed) + + )); } } \ No newline at end of file diff --git a/src/AElf.Cryptography/AElf.Cryptography.csproj b/src/AElf.Cryptography/AElf.Cryptography.csproj index 1f5c07064d..d652a84e0c 100644 --- a/src/AElf.Cryptography/AElf.Cryptography.csproj +++ b/src/AElf.Cryptography/AElf.Cryptography.csproj @@ -10,6 +10,15 @@ + + all + + + all + + + all + diff --git a/src/AElf.Cryptography/SecretSharing/SecretSharingHelper.cs b/src/AElf.Cryptography/SecretSharing/SecretSharingHelper.cs index 919db05d9b..fb7d79a58e 100644 --- a/src/AElf.Cryptography/SecretSharing/SecretSharingHelper.cs +++ b/src/AElf.Cryptography/SecretSharing/SecretSharingHelper.cs @@ -2,6 +2,8 @@ using System.Collections.Generic; using System.Linq; using System.Numerics; +using Bn254.Net; +using Nethereum.Util; namespace AElf.Cryptography.SecretSharing { @@ -11,6 +13,52 @@ namespace AElf.Cryptography.SecretSharing /// public static class SecretSharingHelper { + public static bool Ed25519Verify(byte[] signature, byte[] message, byte[] publicKey) + { + try + { + var instance = new Rebex.Security.Cryptography.Ed25519(); + instance.FromPublicKey(publicKey); + return instance.VerifyMessage(message, signature); + } + catch (Exception e) + { + return false; + } + } + + public static byte[] Keccak256(byte[] message) + { + return Sha3Keccack.Current.CalculateHash(message); + } + + public static (byte[] x, byte[] y) Bn254G1Mul(byte[] x1, byte[] y1, byte[] s) + { + var (xUInt256, yUInt256) = Bn254.Net.Bn254.Mul(UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), + UInt256.FromBigEndianBytes(s)); + return (xUInt256.ToBigEndianBytes(), yUInt256.ToBigEndianBytes()); + } + + public static (byte[] x3, byte[] y3) Bn254G1Mul(byte[] x1, byte[] y1, byte[] x2, byte[] y2) + { + var (x3UInt256, y3UInt256) = Bn254.Net.Bn254.Add(UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), + UInt256.FromBigEndianBytes(x2), UInt256.FromBigEndianBytes(y2)); + return (x3UInt256.ToBigEndianBytes(), y3UInt256.ToBigEndianBytes()); + } + + public static bool Bn254Pairing((byte[], byte[], byte[], byte[], byte[], byte[])[] input) + { + var elements = new (UInt256, UInt256, UInt256, UInt256, UInt256, UInt256)[input.Length]; + for (var i = 0; i < input.Length; i++) + { + var (x1, y1, x2, y2, x3, y3) = input[i]; + elements[i] = (UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), + UInt256.FromBigEndianBytes(x2), UInt256.FromBigEndianBytes(y2), + UInt256.FromBigEndianBytes(x3), UInt256.FromBigEndianBytes(y3)); + } + + return Bn254.Net.Bn254.Pairing(elements); + } public static List EncodeSecret(byte[] secretMessage, int threshold, int totalParts) { // Polynomial construction. diff --git a/src/AElf.Runtime.CSharp/AElf.Runtime.CSharp.csproj b/src/AElf.Runtime.CSharp/AElf.Runtime.CSharp.csproj index 122d0af0b5..b9c1d1df61 100644 --- a/src/AElf.Runtime.CSharp/AElf.Runtime.CSharp.csproj +++ b/src/AElf.Runtime.CSharp/AElf.Runtime.CSharp.csproj @@ -22,9 +22,9 @@ - - - + + + diff --git a/src/AElf.Sdk.CSharp/CSharpSmartContractContext.cs b/src/AElf.Sdk.CSharp/CSharpSmartContractContext.cs index 146c0ba31c..caf5cbde5e 100644 --- a/src/AElf.Sdk.CSharp/CSharpSmartContractContext.cs +++ b/src/AElf.Sdk.CSharp/CSharpSmartContractContext.cs @@ -14,14 +14,14 @@ namespace AElf.Sdk.CSharp; /// base class for smart contracts (Context property). It provides access to properties and methods useful for /// implementing the logic in smart contracts. /// -public class CSharpSmartContractContext : ISmartContractBridgeContext, IBuiltIns +public class CSharpSmartContractContext : ISmartContractBridgeContext { - private IBuiltIns BuiltInsImplementation { get; } + // private IBuiltIns BuiltInsImplementation { get; } public CSharpSmartContractContext(ISmartContractBridgeContext smartContractBridgeContextImplementation) { SmartContractBridgeContextImplementation = smartContractBridgeContextImplementation; - BuiltInsImplementation = new InternalBuiltIns(); + // BuiltInsImplementation = new InternalBuiltIns(); } public ISmartContractBridgeContext SmartContractBridgeContextImplementation { get; } @@ -402,28 +402,28 @@ public bool ECVrfVerify(byte[] pubKey, byte[] alpha, byte[] pi, out byte[] beta) return SmartContractBridgeContextImplementation.ECVrfVerify(pubKey, alpha, pi, out beta); } - public bool Ed25519Verify(byte[] signature, byte[] message, byte[] publicKey) - { - return BuiltInsImplementation.Ed25519Verify(signature, message, publicKey); - } - - public byte[] Keccak256(byte[] message) - { - return BuiltInsImplementation.Keccak256(message); - } - - public (byte[] x, byte[] y) Bn254G1Mul(byte[] x1, byte[] y1, byte[] s) - { - return BuiltInsImplementation.Bn254G1Mul(x1, y1, s); - } - - public (byte[] x3, byte[] y3) Bn254G1Add(byte[] x1, byte[] y1, byte[] x2, byte[] y2) - { - return BuiltInsImplementation.Bn254G1Add(x1, y1, x2, y2); - } - - public bool Bn254Pairing((byte[], byte[], byte[], byte[], byte[], byte[])[] input) - { - return BuiltInsImplementation.Bn254Pairing(input); - } + // public bool Ed25519Verify(byte[] signature, byte[] message, byte[] publicKey) + // { + // return BuiltInsImplementation.Ed25519Verify(signature, message, publicKey); + // } + // + // public byte[] Keccak256(byte[] message) + // { + // return BuiltInsImplementation.Keccak256(message); + // } + // + // public (byte[] x, byte[] y) Bn254G1Mul(byte[] x1, byte[] y1, byte[] s) + // { + // return BuiltInsImplementation.Bn254G1Mul(x1, y1, s); + // } + // + // public (byte[] x3, byte[] y3) Bn254G1Add(byte[] x1, byte[] y1, byte[] x2, byte[] y2) + // { + // return BuiltInsImplementation.Bn254G1Add(x1, y1, x2, y2); + // } + // + // public bool Bn254Pairing((byte[], byte[], byte[], byte[], byte[], byte[])[] input) + // { + // return BuiltInsImplementation.Bn254Pairing(input); + // } } \ No newline at end of file From 4d02f2733fc4cd1f10198637c3bd9ca021c93440 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Wed, 25 Dec 2024 14:13:17 +0800 Subject: [PATCH 72/83] Adjust implementation of ZK function --- .../Whitelist/IWhitelistProvider.cs | 6 +- .../PureFunction/PureFunctionHelper.cs | 57 +++++++++++++++++++ .../SecretSharing/SecretSharingHelper.cs | 48 ---------------- 3 files changed, 58 insertions(+), 53 deletions(-) create mode 100644 src/AElf.Cryptography/PureFunction/PureFunctionHelper.cs diff --git a/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs b/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs index 4d525eac88..3b9dc807b9 100644 --- a/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs +++ b/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs @@ -48,6 +48,7 @@ private void WhitelistAssemblies(Whitelist whitelist) .Assembly(typeof(Address).Assembly, Trust.Full) // AElf.Types .Assembly(typeof(IMethod).Assembly, Trust.Full) // AElf.CSharp.Core .Assembly(typeof(SecretSharingHelper).Assembly, Trust.Partial) // AElf.Cryptography + .Assembly(typeof(PureFunctionHelper).Assembly, Trust.Full) // AElf.Cryptography .Assembly(typeof(ISmartContractBridgeContext).Assembly, Trust.Full) // AElf.Kernel.SmartContract.Shared .Assembly(typeof(Groth16.Net.Verifier).Assembly, Trust.Full) // AElf.Cryptography.ECDSA ; @@ -201,11 +202,6 @@ private void WhitelistAElfTypes(Whitelist whitelist) .Namespace("AElf.Cryptography.SecretSharing", Permission.Denied, type => type .Type(typeof(SecretSharingHelper), Permission.Denied, member => member .Member(nameof(SecretSharingHelper.DecodeSecret), Permission.Allowed) - .Member(nameof(SecretSharingHelper.Ed25519Verify), Permission.Allowed) - .Member(nameof(SecretSharingHelper.Keccak256), Permission.Allowed) - .Member(nameof(SecretSharingHelper.Bn254G1Mul), Permission.Allowed) - .Member(nameof(SecretSharingHelper.Bn254Pairing), Permission.Allowed) - )); } } \ No newline at end of file diff --git a/src/AElf.Cryptography/PureFunction/PureFunctionHelper.cs b/src/AElf.Cryptography/PureFunction/PureFunctionHelper.cs new file mode 100644 index 0000000000..01cc9e51c1 --- /dev/null +++ b/src/AElf.Cryptography/PureFunction/PureFunctionHelper.cs @@ -0,0 +1,57 @@ +using System; +using Bn254.Net; +using Nethereum.Util; +using Rebex.Security.Cryptography; + +namespace AElf.Cryptography.SecretSharing +{ + public static class PureFunctionHelper + { + public static bool Ed25519Verify(byte[] signature, byte[] message, byte[] publicKey) + { + try + { + var instance = new Ed25519(); + instance.FromPublicKey(publicKey); + return instance.VerifyMessage(message, signature); + } + catch (Exception e) + { + return false; + } + } + + public static byte[] Keccak256(byte[] message) + { + return Sha3Keccack.Current.CalculateHash(message); + } + + public static (byte[] x, byte[] y) Bn254G1Mul(byte[] x1, byte[] y1, byte[] s) + { + var (xUInt256, yUInt256) = Bn254.Net.Bn254.Mul(UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), + UInt256.FromBigEndianBytes(s)); + return (xUInt256.ToBigEndianBytes(), yUInt256.ToBigEndianBytes()); + } + + public static (byte[] x3, byte[] y3) Bn254G1Mul(byte[] x1, byte[] y1, byte[] x2, byte[] y2) + { + var (x3UInt256, y3UInt256) = Bn254.Net.Bn254.Add(UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), + UInt256.FromBigEndianBytes(x2), UInt256.FromBigEndianBytes(y2)); + return (x3UInt256.ToBigEndianBytes(), y3UInt256.ToBigEndianBytes()); + } + + public static bool Bn254Pairing((byte[], byte[], byte[], byte[], byte[], byte[])[] input) + { + var elements = new (UInt256, UInt256, UInt256, UInt256, UInt256, UInt256)[input.Length]; + for (var i = 0; i < input.Length; i++) + { + var (x1, y1, x2, y2, x3, y3) = input[i]; + elements[i] = (UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), + UInt256.FromBigEndianBytes(x2), UInt256.FromBigEndianBytes(y2), + UInt256.FromBigEndianBytes(x3), UInt256.FromBigEndianBytes(y3)); + } + + return Bn254.Net.Bn254.Pairing(elements); + } + } +} \ No newline at end of file diff --git a/src/AElf.Cryptography/SecretSharing/SecretSharingHelper.cs b/src/AElf.Cryptography/SecretSharing/SecretSharingHelper.cs index fb7d79a58e..919db05d9b 100644 --- a/src/AElf.Cryptography/SecretSharing/SecretSharingHelper.cs +++ b/src/AElf.Cryptography/SecretSharing/SecretSharingHelper.cs @@ -2,8 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Numerics; -using Bn254.Net; -using Nethereum.Util; namespace AElf.Cryptography.SecretSharing { @@ -13,52 +11,6 @@ namespace AElf.Cryptography.SecretSharing /// public static class SecretSharingHelper { - public static bool Ed25519Verify(byte[] signature, byte[] message, byte[] publicKey) - { - try - { - var instance = new Rebex.Security.Cryptography.Ed25519(); - instance.FromPublicKey(publicKey); - return instance.VerifyMessage(message, signature); - } - catch (Exception e) - { - return false; - } - } - - public static byte[] Keccak256(byte[] message) - { - return Sha3Keccack.Current.CalculateHash(message); - } - - public static (byte[] x, byte[] y) Bn254G1Mul(byte[] x1, byte[] y1, byte[] s) - { - var (xUInt256, yUInt256) = Bn254.Net.Bn254.Mul(UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), - UInt256.FromBigEndianBytes(s)); - return (xUInt256.ToBigEndianBytes(), yUInt256.ToBigEndianBytes()); - } - - public static (byte[] x3, byte[] y3) Bn254G1Mul(byte[] x1, byte[] y1, byte[] x2, byte[] y2) - { - var (x3UInt256, y3UInt256) = Bn254.Net.Bn254.Add(UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), - UInt256.FromBigEndianBytes(x2), UInt256.FromBigEndianBytes(y2)); - return (x3UInt256.ToBigEndianBytes(), y3UInt256.ToBigEndianBytes()); - } - - public static bool Bn254Pairing((byte[], byte[], byte[], byte[], byte[], byte[])[] input) - { - var elements = new (UInt256, UInt256, UInt256, UInt256, UInt256, UInt256)[input.Length]; - for (var i = 0; i < input.Length; i++) - { - var (x1, y1, x2, y2, x3, y3) = input[i]; - elements[i] = (UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), - UInt256.FromBigEndianBytes(x2), UInt256.FromBigEndianBytes(y2), - UInt256.FromBigEndianBytes(x3), UInt256.FromBigEndianBytes(y3)); - } - - return Bn254.Net.Bn254.Pairing(elements); - } public static List EncodeSecret(byte[] secretMessage, int threshold, int totalParts) { // Polynomial construction. From 230fcebc7426a9bcb81039a301d76b6b85ae7f11 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Thu, 26 Dec 2024 16:11:14 +0800 Subject: [PATCH 73/83] Adjust impletation of zk function --- .../Whitelist/IWhitelistProvider.cs | 22 ++++++- src/AElf.Cryptography/Bn254/Bn254Helper.cs | 37 ++++++++++++ src/AElf.Cryptography/EdDSA/EdDsaHelper.cs | 22 +++++++ src/AElf.Cryptography/Keccak/KeccakHelper.cs | 12 ++++ .../PureFunction/PureFunctionHelper.cs | 57 ------------------- 5 files changed, 91 insertions(+), 59 deletions(-) create mode 100644 src/AElf.Cryptography/Bn254/Bn254Helper.cs create mode 100644 src/AElf.Cryptography/EdDSA/EdDsaHelper.cs create mode 100644 src/AElf.Cryptography/Keccak/KeccakHelper.cs delete mode 100644 src/AElf.Cryptography/PureFunction/PureFunctionHelper.cs diff --git a/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs b/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs index 3b9dc807b9..e1112740ef 100644 --- a/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs +++ b/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs @@ -5,6 +5,9 @@ using System.Runtime.CompilerServices; using System.Text; using System.Text.RegularExpressions; +using AElf.Cryptography.Bn254; +using AElf.Cryptography.EdDSA; +using AElf.Cryptography.Keccak; using AElf.Cryptography.SecretSharing; using AElf.CSharp.Core; using AElf.Kernel.SmartContract; @@ -48,7 +51,6 @@ private void WhitelistAssemblies(Whitelist whitelist) .Assembly(typeof(Address).Assembly, Trust.Full) // AElf.Types .Assembly(typeof(IMethod).Assembly, Trust.Full) // AElf.CSharp.Core .Assembly(typeof(SecretSharingHelper).Assembly, Trust.Partial) // AElf.Cryptography - .Assembly(typeof(PureFunctionHelper).Assembly, Trust.Full) // AElf.Cryptography .Assembly(typeof(ISmartContractBridgeContext).Assembly, Trust.Full) // AElf.Kernel.SmartContract.Shared .Assembly(typeof(Groth16.Net.Verifier).Assembly, Trust.Full) // AElf.Cryptography.ECDSA ; @@ -202,6 +204,22 @@ private void WhitelistAElfTypes(Whitelist whitelist) .Namespace("AElf.Cryptography.SecretSharing", Permission.Denied, type => type .Type(typeof(SecretSharingHelper), Permission.Denied, member => member .Member(nameof(SecretSharingHelper.DecodeSecret), Permission.Allowed) - )); + )) + .Namespace("AElf.Cryptography.Bn254", Permission.Denied, type => type + .Type(typeof(Bn254Helper), Permission.Denied, member => member + .Member(nameof(Bn254Helper.Bn254Pairing), Permission.Allowed) + .Member(nameof(Bn254Helper.Bn254G1Add), Permission.Allowed) + .Member(nameof(Bn254Helper.Bn254G1Mul), Permission.Allowed) + )) + .Namespace("AElf.Cryptography.EdDSA", Permission.Denied, type => type + .Type(typeof(EdDsaHelper), Permission.Denied, member => member + .Member(nameof(EdDsaHelper.Ed25519Verify), Permission.Allowed) + )) + .Namespace("AElf.Cryptography.Keccak", Permission.Denied, type => type + .Type(typeof(KeccakHelper), Permission.Denied, member => member + .Member(nameof(KeccakHelper.Keccak256), Permission.Allowed) + )) + ; + } } \ No newline at end of file diff --git a/src/AElf.Cryptography/Bn254/Bn254Helper.cs b/src/AElf.Cryptography/Bn254/Bn254Helper.cs new file mode 100644 index 0000000000..08f0297b3f --- /dev/null +++ b/src/AElf.Cryptography/Bn254/Bn254Helper.cs @@ -0,0 +1,37 @@ +using Bn254.Net; + +namespace AElf.Cryptography.Bn254 +{ + public class Bn254Helper + { + public (byte[] x, byte[] y) Bn254G1Mul(byte[] x1, byte[] y1, byte[] s) + { + var (xUInt256, yUInt256) = global::Bn254.Net.Bn254.Mul(UInt256.FromBigEndianBytes(x1), + UInt256.FromBigEndianBytes(y1), + UInt256.FromBigEndianBytes(s)); + return (xUInt256.ToBigEndianBytes(), yUInt256.ToBigEndianBytes()); + } + + public (byte[] x3, byte[] y3) Bn254G1Add(byte[] x1, byte[] y1, byte[] x2, byte[] y2) + { + var (x3UInt256, y3UInt256) = global::Bn254.Net.Bn254.Add(UInt256.FromBigEndianBytes(x1), + UInt256.FromBigEndianBytes(y1), + UInt256.FromBigEndianBytes(x2), UInt256.FromBigEndianBytes(y2)); + return (x3UInt256.ToBigEndianBytes(), y3UInt256.ToBigEndianBytes()); + } + + public bool Bn254Pairing((byte[], byte[], byte[], byte[], byte[], byte[])[] input) + { + var elements = new (UInt256, UInt256, UInt256, UInt256, UInt256, UInt256)[input.Length]; + for (var i = 0; i < input.Length; i++) + { + var (x1, y1, x2, y2, x3, y3) = input[i]; + elements[i] = (UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), + UInt256.FromBigEndianBytes(x2), UInt256.FromBigEndianBytes(y2), + UInt256.FromBigEndianBytes(x3), UInt256.FromBigEndianBytes(y3)); + } + + return global::Bn254.Net.Bn254.Pairing(elements); + } + } +} \ No newline at end of file diff --git a/src/AElf.Cryptography/EdDSA/EdDsaHelper.cs b/src/AElf.Cryptography/EdDSA/EdDsaHelper.cs new file mode 100644 index 0000000000..02046e8a02 --- /dev/null +++ b/src/AElf.Cryptography/EdDSA/EdDsaHelper.cs @@ -0,0 +1,22 @@ +using System; +using Rebex.Security.Cryptography; + +namespace AElf.Cryptography.EdDSA +{ + public static class EdDsaHelper + { + public static bool Ed25519Verify(byte[] signature, byte[] message, byte[] publicKey) + { + try + { + var instance = new Ed25519(); + instance.FromPublicKey(publicKey); + return instance.VerifyMessage(message, signature); + } + catch (Exception e) + { + return false; + } + } + } +} \ No newline at end of file diff --git a/src/AElf.Cryptography/Keccak/KeccakHelper.cs b/src/AElf.Cryptography/Keccak/KeccakHelper.cs new file mode 100644 index 0000000000..dbb182f29c --- /dev/null +++ b/src/AElf.Cryptography/Keccak/KeccakHelper.cs @@ -0,0 +1,12 @@ +using Nethereum.Util; + +namespace AElf.Cryptography.Keccak +{ + public static class KeccakHelper + { + public static byte[] Keccak256(byte[] message) + { + return Sha3Keccack.Current.CalculateHash(message); + } + } +} \ No newline at end of file diff --git a/src/AElf.Cryptography/PureFunction/PureFunctionHelper.cs b/src/AElf.Cryptography/PureFunction/PureFunctionHelper.cs deleted file mode 100644 index 01cc9e51c1..0000000000 --- a/src/AElf.Cryptography/PureFunction/PureFunctionHelper.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System; -using Bn254.Net; -using Nethereum.Util; -using Rebex.Security.Cryptography; - -namespace AElf.Cryptography.SecretSharing -{ - public static class PureFunctionHelper - { - public static bool Ed25519Verify(byte[] signature, byte[] message, byte[] publicKey) - { - try - { - var instance = new Ed25519(); - instance.FromPublicKey(publicKey); - return instance.VerifyMessage(message, signature); - } - catch (Exception e) - { - return false; - } - } - - public static byte[] Keccak256(byte[] message) - { - return Sha3Keccack.Current.CalculateHash(message); - } - - public static (byte[] x, byte[] y) Bn254G1Mul(byte[] x1, byte[] y1, byte[] s) - { - var (xUInt256, yUInt256) = Bn254.Net.Bn254.Mul(UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), - UInt256.FromBigEndianBytes(s)); - return (xUInt256.ToBigEndianBytes(), yUInt256.ToBigEndianBytes()); - } - - public static (byte[] x3, byte[] y3) Bn254G1Mul(byte[] x1, byte[] y1, byte[] x2, byte[] y2) - { - var (x3UInt256, y3UInt256) = Bn254.Net.Bn254.Add(UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), - UInt256.FromBigEndianBytes(x2), UInt256.FromBigEndianBytes(y2)); - return (x3UInt256.ToBigEndianBytes(), y3UInt256.ToBigEndianBytes()); - } - - public static bool Bn254Pairing((byte[], byte[], byte[], byte[], byte[], byte[])[] input) - { - var elements = new (UInt256, UInt256, UInt256, UInt256, UInt256, UInt256)[input.Length]; - for (var i = 0; i < input.Length; i++) - { - var (x1, y1, x2, y2, x3, y3) = input[i]; - elements[i] = (UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), - UInt256.FromBigEndianBytes(x2), UInt256.FromBigEndianBytes(y2), - UInt256.FromBigEndianBytes(x3), UInt256.FromBigEndianBytes(y3)); - } - - return Bn254.Net.Bn254.Pairing(elements); - } - } -} \ No newline at end of file From c1247616c649dd4f3168f9a19745ae1e307e7604 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Fri, 27 Dec 2024 11:08:29 +0800 Subject: [PATCH 74/83] Adjust to static method --- src/AElf.Cryptography/Bn254/Bn254Helper.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/AElf.Cryptography/Bn254/Bn254Helper.cs b/src/AElf.Cryptography/Bn254/Bn254Helper.cs index 08f0297b3f..318a82b355 100644 --- a/src/AElf.Cryptography/Bn254/Bn254Helper.cs +++ b/src/AElf.Cryptography/Bn254/Bn254Helper.cs @@ -2,9 +2,9 @@ namespace AElf.Cryptography.Bn254 { - public class Bn254Helper + public static class Bn254Helper { - public (byte[] x, byte[] y) Bn254G1Mul(byte[] x1, byte[] y1, byte[] s) + public static (byte[] x, byte[] y) Bn254G1Mul(byte[] x1, byte[] y1, byte[] s) { var (xUInt256, yUInt256) = global::Bn254.Net.Bn254.Mul(UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), @@ -12,7 +12,7 @@ public class Bn254Helper return (xUInt256.ToBigEndianBytes(), yUInt256.ToBigEndianBytes()); } - public (byte[] x3, byte[] y3) Bn254G1Add(byte[] x1, byte[] y1, byte[] x2, byte[] y2) + public static (byte[] x3, byte[] y3) Bn254G1Add(byte[] x1, byte[] y1, byte[] x2, byte[] y2) { var (x3UInt256, y3UInt256) = global::Bn254.Net.Bn254.Add(UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), @@ -20,7 +20,7 @@ public class Bn254Helper return (x3UInt256.ToBigEndianBytes(), y3UInt256.ToBigEndianBytes()); } - public bool Bn254Pairing((byte[], byte[], byte[], byte[], byte[], byte[])[] input) + public static bool Bn254Pairing((byte[], byte[], byte[], byte[], byte[], byte[])[] input) { var elements = new (UInt256, UInt256, UInt256, UInt256, UInt256, UInt256)[input.Length]; for (var i = 0; i < input.Length; i++) From a2ef9a6590de563884a3db9376551a7900c64883 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Fri, 27 Dec 2024 13:10:53 +0800 Subject: [PATCH 75/83] Add WhitelistCryptographyHelpers whitelist method --- .../Whitelist/IWhitelistProvider.cs | 44 ++++++++++++------- 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs b/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs index e1112740ef..69bef5c723 100644 --- a/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs +++ b/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs @@ -171,6 +171,31 @@ private void WhitelistOthers(Whitelist whitelist) ) ; } + + private void WhitelistCryptographyHelpers(Whitelist whitelist) + { + whitelist + // Selectively allowed types and members + .Namespace("AElf.Cryptography.SecretSharing", Permission.Denied, type => type + .Type(typeof(SecretSharingHelper), Permission.Denied, member => member + .Member(nameof(SecretSharingHelper.DecodeSecret), Permission.Allowed) + )) + .Namespace("AElf.Cryptography.Bn254", Permission.Denied, type => type + .Type(typeof(Bn254Helper), Permission.Denied, member => member + .Member(nameof(Bn254Helper.Bn254Pairing), Permission.Allowed) + .Member(nameof(Bn254Helper.Bn254G1Add), Permission.Allowed) + .Member(nameof(Bn254Helper.Bn254G1Mul), Permission.Allowed) + )) + .Namespace("AElf.Cryptography.EdDSA", Permission.Denied, type => type + .Type(typeof(EdDsaHelper), Permission.Denied, member => member + .Member(nameof(EdDsaHelper.Ed25519Verify), Permission.Allowed) + )) + .Namespace("AElf.Cryptography.Keccak", Permission.Denied, type => type + .Type(typeof(KeccakHelper), Permission.Denied, member => member + .Member(nameof(KeccakHelper.Keccak256), Permission.Allowed) + )) + ; + } private Whitelist CreateWhitelist() { @@ -180,6 +205,7 @@ private Whitelist CreateWhitelist() WhitelistReflectionTypes(whitelist); WhitelistLinqAndCollections(whitelist); WhitelistOthers(whitelist); + WhitelistCryptographyHelpers(whitelist); return whitelist; } } @@ -204,22 +230,6 @@ private void WhitelistAElfTypes(Whitelist whitelist) .Namespace("AElf.Cryptography.SecretSharing", Permission.Denied, type => type .Type(typeof(SecretSharingHelper), Permission.Denied, member => member .Member(nameof(SecretSharingHelper.DecodeSecret), Permission.Allowed) - )) - .Namespace("AElf.Cryptography.Bn254", Permission.Denied, type => type - .Type(typeof(Bn254Helper), Permission.Denied, member => member - .Member(nameof(Bn254Helper.Bn254Pairing), Permission.Allowed) - .Member(nameof(Bn254Helper.Bn254G1Add), Permission.Allowed) - .Member(nameof(Bn254Helper.Bn254G1Mul), Permission.Allowed) - )) - .Namespace("AElf.Cryptography.EdDSA", Permission.Denied, type => type - .Type(typeof(EdDsaHelper), Permission.Denied, member => member - .Member(nameof(EdDsaHelper.Ed25519Verify), Permission.Allowed) - )) - .Namespace("AElf.Cryptography.Keccak", Permission.Denied, type => type - .Type(typeof(KeccakHelper), Permission.Denied, member => member - .Member(nameof(KeccakHelper.Keccak256), Permission.Allowed) - )) - ; - + )); } } \ No newline at end of file From c75210482e6b38e0cf0fe84f4fef12d8089f9bb2 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Sun, 29 Dec 2024 21:26:17 +0800 Subject: [PATCH 76/83] Adjust zk code --- AElf.All.sln | 14 - .../Patchers/Module/SafeMath/Patcher.cs | 1 - .../Whitelist/IWhitelistProvider.cs | 7 +- src/AElf.Cryptography/Bn254/Bn254Helper.cs | 7 +- .../AElf.Sdk.CSharp.Internal.csproj | 28 -- src/AElf.Sdk.CSharp.Internal/AssemblyInfo.cs | 3 - .../InternalBuiltIns.cs | 61 ---- .../AElf.Sdk.CSharp.Spec.csproj | 11 - src/AElf.Sdk.CSharp.Spec/IBuiltIns.cs | 10 - src/AElf.Sdk.CSharp/AElf.Sdk.CSharp.csproj | 1 - .../CSharpSmartContractAbstract.cs | 5 +- .../CSharpSmartContractContext.cs | 2 - .../ContractsPreparation.cs | 1 - .../Action.cs | 3 +- .../CSharpSmartContractContextTests.cs | 308 +++++++++--------- 15 files changed, 162 insertions(+), 300 deletions(-) delete mode 100644 src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj delete mode 100644 src/AElf.Sdk.CSharp.Internal/AssemblyInfo.cs delete mode 100644 src/AElf.Sdk.CSharp.Internal/InternalBuiltIns.cs delete mode 100644 src/AElf.Sdk.CSharp.Spec/AElf.Sdk.CSharp.Spec.csproj delete mode 100644 src/AElf.Sdk.CSharp.Spec/IBuiltIns.cs diff --git a/AElf.All.sln b/AElf.All.sln index 782e186970..34ad27a9ac 100644 --- a/AElf.All.sln +++ b/AElf.All.sln @@ -385,10 +385,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AElf.Kernel.FeatureDisable. EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AElf.Kernel.FeatureDisable.Core", "src\AElf.Kernel.FeatureDisable.Core\AElf.Kernel.FeatureDisable.Core.csproj", "{659A7C7A-44C9-424E-B4F6-D1D3656F7AD4}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AElf.Sdk.CSharp.Spec", "src\AElf.Sdk.CSharp.Spec\AElf.Sdk.CSharp.Spec.csproj", "{45A77C41-142E-4296-A14A-D53067EC8B75}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AElf.Sdk.CSharp.Internal", "src\AElf.Sdk.CSharp.Internal\AElf.Sdk.CSharp.Internal.csproj", "{A77380A7-E425-45A3-BF3F-F865DA4F3F4E}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -1111,14 +1107,6 @@ Global {659A7C7A-44C9-424E-B4F6-D1D3656F7AD4}.Debug|Any CPU.Build.0 = Debug|Any CPU {659A7C7A-44C9-424E-B4F6-D1D3656F7AD4}.Release|Any CPU.ActiveCfg = Release|Any CPU {659A7C7A-44C9-424E-B4F6-D1D3656F7AD4}.Release|Any CPU.Build.0 = Release|Any CPU - {45A77C41-142E-4296-A14A-D53067EC8B75}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {45A77C41-142E-4296-A14A-D53067EC8B75}.Debug|Any CPU.Build.0 = Debug|Any CPU - {45A77C41-142E-4296-A14A-D53067EC8B75}.Release|Any CPU.ActiveCfg = Release|Any CPU - {45A77C41-142E-4296-A14A-D53067EC8B75}.Release|Any CPU.Build.0 = Release|Any CPU - {A77380A7-E425-45A3-BF3F-F865DA4F3F4E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A77380A7-E425-45A3-BF3F-F865DA4F3F4E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A77380A7-E425-45A3-BF3F-F865DA4F3F4E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A77380A7-E425-45A3-BF3F-F865DA4F3F4E}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -1313,7 +1301,5 @@ Global {A4ACE6D2-4CF8-4B52-93C9-BB8BEC0C098E} = {90B310B4-C2DB-419E-B5EE-97FA096B62CC} {8C0D86A4-D1A7-4B61-AC44-755F5AC75D67} = {4E54480A-D155-43ED-9736-1A5BE7957211} {659A7C7A-44C9-424E-B4F6-D1D3656F7AD4} = {90B310B4-C2DB-419E-B5EE-97FA096B62CC} - {45A77C41-142E-4296-A14A-D53067EC8B75} = {798BAA50-825B-4DD9-83E2-77A9EE6EBE09} - {A77380A7-E425-45A3-BF3F-F865DA4F3F4E} = {798BAA50-825B-4DD9-83E2-77A9EE6EBE09} EndGlobalSection EndGlobal diff --git a/src/AElf.CSharp.CodeOps/Patchers/Module/SafeMath/Patcher.cs b/src/AElf.CSharp.CodeOps/Patchers/Module/SafeMath/Patcher.cs index 2bc2e46232..2d8ec1ebe6 100644 --- a/src/AElf.CSharp.CodeOps/Patchers/Module/SafeMath/Patcher.cs +++ b/src/AElf.CSharp.CodeOps/Patchers/Module/SafeMath/Patcher.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; -using AElf.Sdk.CSharp; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Cecil.Rocks; diff --git a/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs b/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs index 69bef5c723..41e3ba704d 100644 --- a/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs +++ b/src/AElf.CSharp.CodeOps/Validators/Whitelist/IWhitelistProvider.cs @@ -176,10 +176,6 @@ private void WhitelistCryptographyHelpers(Whitelist whitelist) { whitelist // Selectively allowed types and members - .Namespace("AElf.Cryptography.SecretSharing", Permission.Denied, type => type - .Type(typeof(SecretSharingHelper), Permission.Denied, member => member - .Member(nameof(SecretSharingHelper.DecodeSecret), Permission.Allowed) - )) .Namespace("AElf.Cryptography.Bn254", Permission.Denied, type => type .Type(typeof(Bn254Helper), Permission.Denied, member => member .Member(nameof(Bn254Helper.Bn254Pairing), Permission.Allowed) @@ -229,7 +225,6 @@ private void WhitelistAElfTypes(Whitelist whitelist) // Selectively allowed types and members .Namespace("AElf.Cryptography.SecretSharing", Permission.Denied, type => type .Type(typeof(SecretSharingHelper), Permission.Denied, member => member - .Member(nameof(SecretSharingHelper.DecodeSecret), Permission.Allowed) - )); + .Member(nameof(SecretSharingHelper.DecodeSecret), Permission.Allowed))); } } \ No newline at end of file diff --git a/src/AElf.Cryptography/Bn254/Bn254Helper.cs b/src/AElf.Cryptography/Bn254/Bn254Helper.cs index 318a82b355..0cf74fc3bc 100644 --- a/src/AElf.Cryptography/Bn254/Bn254Helper.cs +++ b/src/AElf.Cryptography/Bn254/Bn254Helper.cs @@ -1,4 +1,5 @@ using Bn254.Net; +using NetBn254 = Bn254.Net; namespace AElf.Cryptography.Bn254 { @@ -6,7 +7,7 @@ public static class Bn254Helper { public static (byte[] x, byte[] y) Bn254G1Mul(byte[] x1, byte[] y1, byte[] s) { - var (xUInt256, yUInt256) = global::Bn254.Net.Bn254.Mul(UInt256.FromBigEndianBytes(x1), + var (xUInt256, yUInt256) = NetBn254.Bn254.Mul(UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), UInt256.FromBigEndianBytes(s)); return (xUInt256.ToBigEndianBytes(), yUInt256.ToBigEndianBytes()); @@ -14,7 +15,7 @@ public static (byte[] x, byte[] y) Bn254G1Mul(byte[] x1, byte[] y1, byte[] s) public static (byte[] x3, byte[] y3) Bn254G1Add(byte[] x1, byte[] y1, byte[] x2, byte[] y2) { - var (x3UInt256, y3UInt256) = global::Bn254.Net.Bn254.Add(UInt256.FromBigEndianBytes(x1), + var (x3UInt256, y3UInt256) = NetBn254.Bn254.Add(UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), UInt256.FromBigEndianBytes(x2), UInt256.FromBigEndianBytes(y2)); return (x3UInt256.ToBigEndianBytes(), y3UInt256.ToBigEndianBytes()); @@ -31,7 +32,7 @@ public static bool Bn254Pairing((byte[], byte[], byte[], byte[], byte[], byte[]) UInt256.FromBigEndianBytes(x3), UInt256.FromBigEndianBytes(y3)); } - return global::Bn254.Net.Bn254.Pairing(elements); + return NetBn254.Bn254.Pairing(elements); } } } \ No newline at end of file diff --git a/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj b/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj deleted file mode 100644 index ff42c2fa80..0000000000 --- a/src/AElf.Sdk.CSharp.Internal/AElf.Sdk.CSharp.Internal.csproj +++ /dev/null @@ -1,28 +0,0 @@ - - - - net8.0 - AElf.Sdk.CSharp.Internal - true - latest - Types for the C# smart contract SDK. - AElf.Sdk.CSharp.Internal - - - - - all - - - all - - - all - - - - - - - - diff --git a/src/AElf.Sdk.CSharp.Internal/AssemblyInfo.cs b/src/AElf.Sdk.CSharp.Internal/AssemblyInfo.cs deleted file mode 100644 index 1b80097c7f..0000000000 --- a/src/AElf.Sdk.CSharp.Internal/AssemblyInfo.cs +++ /dev/null @@ -1,3 +0,0 @@ -using System.Runtime.CompilerServices; - -[assembly: InternalsVisibleTo("AElf.Sdk.CSharp")] \ No newline at end of file diff --git a/src/AElf.Sdk.CSharp.Internal/InternalBuiltIns.cs b/src/AElf.Sdk.CSharp.Internal/InternalBuiltIns.cs deleted file mode 100644 index 0d61e255b8..0000000000 --- a/src/AElf.Sdk.CSharp.Internal/InternalBuiltIns.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using AElf.Sdk.CSharp.Spec; -using Bn254.Net; -using Nethereum.Util; - -namespace AElf.Sdk.CSharp.Internal; - -internal class InternalBuiltIns : IBuiltIns -{ - public static void Initialize() - { - // call this method to ensure this assembly is loaded in the runtime. - } - - public bool Ed25519Verify(byte[] signature, byte[] message, byte[] publicKey) - { - try - { - var instance = new Rebex.Security.Cryptography.Ed25519(); - instance.FromPublicKey(publicKey); - return instance.VerifyMessage(message, signature); - } - catch (Exception e) - { - return false; - } - } - - public byte[] Keccak256(byte[] message) - { - return Sha3Keccack.Current.CalculateHash(message); - } - - public (byte[] x, byte[] y) Bn254G1Mul(byte[] x1, byte[] y1, byte[] s) - { - var (xUInt256, yUInt256) = Bn254.Net.Bn254.Mul(UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), - UInt256.FromBigEndianBytes(s)); - return (xUInt256.ToBigEndianBytes(), yUInt256.ToBigEndianBytes()); - } - - public (byte[] x3, byte[] y3) Bn254G1Add(byte[] x1, byte[] y1, byte[] x2, byte[] y2) - { - var (x3UInt256, y3UInt256) = Bn254.Net.Bn254.Add(UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), - UInt256.FromBigEndianBytes(x2), UInt256.FromBigEndianBytes(y2)); - return (x3UInt256.ToBigEndianBytes(), y3UInt256.ToBigEndianBytes()); - } - - public bool Bn254Pairing((byte[], byte[], byte[], byte[], byte[], byte[])[] input) - { - var elements = new (UInt256, UInt256, UInt256, UInt256, UInt256, UInt256)[input.Length]; - for (var i = 0; i < input.Length; i++) - { - var (x1, y1, x2, y2, x3, y3) = input[i]; - elements[i] = (UInt256.FromBigEndianBytes(x1), UInt256.FromBigEndianBytes(y1), - UInt256.FromBigEndianBytes(x2), UInt256.FromBigEndianBytes(y2), - UInt256.FromBigEndianBytes(x3), UInt256.FromBigEndianBytes(y3)); - } - - return Bn254.Net.Bn254.Pairing(elements); - } -} \ No newline at end of file diff --git a/src/AElf.Sdk.CSharp.Spec/AElf.Sdk.CSharp.Spec.csproj b/src/AElf.Sdk.CSharp.Spec/AElf.Sdk.CSharp.Spec.csproj deleted file mode 100644 index 81ab49bf3a..0000000000 --- a/src/AElf.Sdk.CSharp.Spec/AElf.Sdk.CSharp.Spec.csproj +++ /dev/null @@ -1,11 +0,0 @@ - - - - net8.0 - enable - enable - Release - true - - - diff --git a/src/AElf.Sdk.CSharp.Spec/IBuiltIns.cs b/src/AElf.Sdk.CSharp.Spec/IBuiltIns.cs deleted file mode 100644 index f19de71ebe..0000000000 --- a/src/AElf.Sdk.CSharp.Spec/IBuiltIns.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace AElf.Sdk.CSharp.Spec; - -public interface IBuiltIns -{ - bool Ed25519Verify(byte[] signature, byte[] message, byte[] publicKey); - byte[] Keccak256(byte[] message); - (byte[] x, byte[] y) Bn254G1Mul(byte[] x1, byte[] y1, byte[] s); - (byte[] x3, byte[] y3) Bn254G1Add(byte[] x1, byte[] y1, byte[] x2, byte[] y2); - bool Bn254Pairing((byte[], byte[], byte[], byte[], byte[], byte[])[] input); -} \ No newline at end of file diff --git a/src/AElf.Sdk.CSharp/AElf.Sdk.CSharp.csproj b/src/AElf.Sdk.CSharp/AElf.Sdk.CSharp.csproj index 00cf548872..3d27d43369 100644 --- a/src/AElf.Sdk.CSharp/AElf.Sdk.CSharp.csproj +++ b/src/AElf.Sdk.CSharp/AElf.Sdk.CSharp.csproj @@ -13,7 +13,6 @@ - diff --git a/src/AElf.Sdk.CSharp/CSharpSmartContractAbstract.cs b/src/AElf.Sdk.CSharp/CSharpSmartContractAbstract.cs index 5553b6eb5a..f550dc596e 100644 --- a/src/AElf.Sdk.CSharp/CSharpSmartContractAbstract.cs +++ b/src/AElf.Sdk.CSharp/CSharpSmartContractAbstract.cs @@ -1,6 +1,5 @@ using AElf.Kernel.SmartContract; using AElf.Types; -using AElf.Sdk.CSharp.Spec; namespace AElf.Sdk.CSharp; @@ -21,6 +20,6 @@ protected void Assert(bool asserted, string message = "Assertion failed!") } internal abstract void InternalInitialize(ISmartContractBridgeContext bridgeContext); - - public IBuiltIns BuiltIns { get; internal set; } + + // public IBuiltIns BuiltIns { get; internal set; } } \ No newline at end of file diff --git a/src/AElf.Sdk.CSharp/CSharpSmartContractContext.cs b/src/AElf.Sdk.CSharp/CSharpSmartContractContext.cs index caf5cbde5e..911d71a2e6 100644 --- a/src/AElf.Sdk.CSharp/CSharpSmartContractContext.cs +++ b/src/AElf.Sdk.CSharp/CSharpSmartContractContext.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; using AElf.Kernel.SmartContract; -using AElf.Sdk.CSharp.Internal; -using AElf.Sdk.CSharp.Spec; using AElf.Types; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; diff --git a/test/AElf.Contracts.Economic.TestBase/ContractsPreparation.cs b/test/AElf.Contracts.Economic.TestBase/ContractsPreparation.cs index cde20e76c9..5aeca9457c 100644 --- a/test/AElf.Contracts.Economic.TestBase/ContractsPreparation.cs +++ b/test/AElf.Contracts.Economic.TestBase/ContractsPreparation.cs @@ -18,7 +18,6 @@ using AElf.Cryptography.ECDSA; using AElf.CSharp.Core.Extension; using AElf.Kernel; -using AElf.Sdk.CSharp; using AElf.Standards.ACS3; using AElf.Types; using Google.Protobuf; diff --git a/test/AElf.Contracts.TestContract.VirtualTransactionEvent/Action.cs b/test/AElf.Contracts.TestContract.VirtualTransactionEvent/Action.cs index 99fa3348e2..9703205edf 100644 --- a/test/AElf.Contracts.TestContract.VirtualTransactionEvent/Action.cs +++ b/test/AElf.Contracts.TestContract.VirtualTransactionEvent/Action.cs @@ -1,5 +1,4 @@ -using AElf.Sdk.CSharp; -using AElf.Types; +using AElf.Types; using Google.Protobuf.WellKnownTypes; namespace AElf.Contracts.TestContract.VirtualTransactionEvent; diff --git a/test/AElf.Sdk.CSharp.Tests/CSharpSmartContractContextTests.cs b/test/AElf.Sdk.CSharp.Tests/CSharpSmartContractContextTests.cs index 19e57e247b..24ac83db54 100644 --- a/test/AElf.Sdk.CSharp.Tests/CSharpSmartContractContextTests.cs +++ b/test/AElf.Sdk.CSharp.Tests/CSharpSmartContractContextTests.cs @@ -15,40 +15,40 @@ namespace AElf.Sdk.CSharp.Tests; public class CSharpSmartContractContextTests : SdkCSharpTestBase { - [Fact] - public void Verify_Ed25519Verify() - { - var bridgeContext = GetRequiredService().Create(); - var origin = SampleAddress.AddressList[0]; - bridgeContext.TransactionContext = new TransactionContext - { - Origin = origin, - Transaction = new Transaction - { - From = SampleAddress.AddressList[1], - To = SampleAddress.AddressList[2] - } - }; - var contractContext = new CSharpSmartContractContext(bridgeContext); - var publicKey = "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"; - var message = ""; - var signature = "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"; - var ed25519VerifyResult = contractContext.Ed25519Verify( - ByteArrayHelper.HexStringToByteArray(signature), - ByteArrayHelper.HexStringToByteArray(message), - ByteArrayHelper.HexStringToByteArray(publicKey)); - ed25519VerifyResult.ShouldBe(true); - - var contractContext1 = new CSharpSmartContractContext(bridgeContext); - var publicKey1 = "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"; - var message1 = "1"; - var signature1 = "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"; - Should.Throw(() => contractContext1.Ed25519Verify( - ByteArrayHelper.HexStringToByteArray(signature1), - ByteArrayHelper.HexStringToByteArray(message1), - ByteArrayHelper.HexStringToByteArray(publicKey1))); - - } + // [Fact] + // public void Verify_Ed25519Verify() + // { + // var bridgeContext = GetRequiredService().Create(); + // var origin = SampleAddress.AddressList[0]; + // bridgeContext.TransactionContext = new TransactionContext + // { + // Origin = origin, + // Transaction = new Transaction + // { + // From = SampleAddress.AddressList[1], + // To = SampleAddress.AddressList[2] + // } + // }; + // var contractContext = new CSharpSmartContractContext(bridgeContext); + // var publicKey = "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"; + // var message = ""; + // var signature = "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"; + // var ed25519VerifyResult = contractContext.Ed25519Verify( + // ByteArrayHelper.HexStringToByteArray(signature), + // ByteArrayHelper.HexStringToByteArray(message), + // ByteArrayHelper.HexStringToByteArray(publicKey)); + // ed25519VerifyResult.ShouldBe(true); + // + // var contractContext1 = new CSharpSmartContractContext(bridgeContext); + // var publicKey1 = "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"; + // var message1 = "1"; + // var signature1 = "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"; + // Should.Throw(() => contractContext1.Ed25519Verify( + // ByteArrayHelper.HexStringToByteArray(signature1), + // ByteArrayHelper.HexStringToByteArray(message1), + // ByteArrayHelper.HexStringToByteArray(publicKey1))); + // + // } [Fact] public void Verify_Transaction_Origin_SetValue() @@ -88,124 +88,124 @@ public void Transaction_VerifySignature_Test() result.ShouldBeTrue(); } - [Fact] - public void keccak256_test() - { - var bridgeContext = GetRequiredService().Create(); - var origin = SampleAddress.AddressList[0]; - var contractContext = new CSharpSmartContractContext(bridgeContext); - byte[] message = System.Text.Encoding.UTF8.GetBytes("Test message"); - var fact = contractContext.Keccak256(message); - var expected = Sha3Keccack.Current.CalculateHash(message); - fact.ShouldBe(expected); - } - public static byte[] ToBytes32(BigIntValue value) - { - var bytes = value.ToBigEndianBytes(); - var newArray = new byte[32]; - for (int i = 0; i < bytes.Length; i++) - { - newArray[31 - i] = bytes[bytes.Length - 1 - i]; - } - - return newArray; - } - - [Fact] - public void Bn254G1Mul_Test() - { - var bridgeContext = GetRequiredService().Create(); - var contractContext = new CSharpSmartContractContext(bridgeContext); - - // Arrange - byte[] x1 = ToBytes32(new BigIntValue(0)); - byte[] y1 = ToBytes32(new BigIntValue(0)); - byte[] scalar = ToBytes32(new BigIntValue(0)); - - // use raw api to compute result - var (expectedXUInt256, expectedYUInt256) = Bn254.Net.Bn254.Mul( - UInt256.FromBigEndianBytes(x1), - UInt256.FromBigEndianBytes(y1), - UInt256.FromBigEndianBytes(scalar) - ); - var expectedX = expectedXUInt256.ToBigEndianBytes(); - var expectedY = expectedYUInt256.ToBigEndianBytes(); - - // Act - var (xResult, yResult) = contractContext.Bn254G1Mul(x1, y1, scalar); - - // Assert - xResult.ShouldBe(expectedX); - yResult.ShouldBe(expectedY); - } - - [Fact] - public void Bn254G1Add_Test() - { - var bridgeContext = GetRequiredService().Create(); - var contractContext = new CSharpSmartContractContext(bridgeContext); - - // Arrange - byte[] x1 = ToBytes32(new BigIntValue(0)); - byte[] y1 = ToBytes32(new BigIntValue(0)); - byte[] x2 = ToBytes32(new BigIntValue(0)); - byte[] y2 = ToBytes32(new BigIntValue(0)); - - // Use raw API to compute expected results - var (expectedX3UInt256, expectedY3UInt256) = Bn254.Net.Bn254.Add( - UInt256.FromBigEndianBytes(x1), - UInt256.FromBigEndianBytes(y1), - UInt256.FromBigEndianBytes(x2), - UInt256.FromBigEndianBytes(y2) - ); - var expectedX3 = expectedX3UInt256.ToBigEndianBytes(); - var expectedY3 = expectedY3UInt256.ToBigEndianBytes(); - - // Act - var (x3Result, y3Result) = contractContext.Bn254G1Add(x1, y1, x2, y2); - - // Assert - x3Result.ShouldBe(expectedX3); - y3Result.ShouldBe(expectedY3); - } - - - [Fact] - public void Bn254Pairing_Test() - { - var bridgeContext = GetRequiredService().Create(); - var contractContext = new CSharpSmartContractContext(bridgeContext); - - // Arrange - var input = new (byte[], byte[], byte[], byte[], byte[], byte[])[] - { - ( - ToBytes32(new BigIntValue(0)), - ToBytes32(new BigIntValue(0)), - ToBytes32(new BigIntValue(0)), - ToBytes32(new BigIntValue(0)), - ToBytes32(new BigIntValue(0)), - ToBytes32(new BigIntValue(0)) - ) - }; - - // Use raw API to compute expected results - bool expected = Bn254.Net.Bn254.Pairing(new (UInt256, UInt256, UInt256, UInt256, UInt256, UInt256)[] - { - ( - UInt256.FromBigEndianBytes(input[0].Item1), - UInt256.FromBigEndianBytes(input[0].Item2), - UInt256.FromBigEndianBytes(input[0].Item3), - UInt256.FromBigEndianBytes(input[0].Item4), - UInt256.FromBigEndianBytes(input[0].Item5), - UInt256.FromBigEndianBytes(input[0].Item6) - ) - }); - - // Act - bool result = contractContext.Bn254Pairing(input); - - // Assert - result.ShouldBe(expected); - } + // [Fact] + // public void keccak256_test() + // { + // var bridgeContext = GetRequiredService().Create(); + // var origin = SampleAddress.AddressList[0]; + // var contractContext = new CSharpSmartContractContext(bridgeContext); + // byte[] message = System.Text.Encoding.UTF8.GetBytes("Test message"); + // var fact = contractContext.Keccak256(message); + // var expected = Sha3Keccack.Current.CalculateHash(message); + // fact.ShouldBe(expected); + // } + // public static byte[] ToBytes32(BigIntValue value) + // { + // var bytes = value.ToBigEndianBytes(); + // var newArray = new byte[32]; + // for (int i = 0; i < bytes.Length; i++) + // { + // newArray[31 - i] = bytes[bytes.Length - 1 - i]; + // } + // + // return newArray; + // } + // + // [Fact] + // public void Bn254G1Mul_Test() + // { + // var bridgeContext = GetRequiredService().Create(); + // var contractContext = new CSharpSmartContractContext(bridgeContext); + // + // // Arrange + // byte[] x1 = ToBytes32(new BigIntValue(0)); + // byte[] y1 = ToBytes32(new BigIntValue(0)); + // byte[] scalar = ToBytes32(new BigIntValue(0)); + // + // // use raw api to compute result + // var (expectedXUInt256, expectedYUInt256) = Bn254.Net.Bn254.Mul( + // UInt256.FromBigEndianBytes(x1), + // UInt256.FromBigEndianBytes(y1), + // UInt256.FromBigEndianBytes(scalar) + // ); + // var expectedX = expectedXUInt256.ToBigEndianBytes(); + // var expectedY = expectedYUInt256.ToBigEndianBytes(); + // + // // Act + // var (xResult, yResult) = contractContext.Bn254G1Mul(x1, y1, scalar); + // + // // Assert + // xResult.ShouldBe(expectedX); + // yResult.ShouldBe(expectedY); + // } + // + // [Fact] + // public void Bn254G1Add_Test() + // { + // var bridgeContext = GetRequiredService().Create(); + // var contractContext = new CSharpSmartContractContext(bridgeContext); + // + // // Arrange + // byte[] x1 = ToBytes32(new BigIntValue(0)); + // byte[] y1 = ToBytes32(new BigIntValue(0)); + // byte[] x2 = ToBytes32(new BigIntValue(0)); + // byte[] y2 = ToBytes32(new BigIntValue(0)); + // + // // Use raw API to compute expected results + // var (expectedX3UInt256, expectedY3UInt256) = Bn254.Net.Bn254.Add( + // UInt256.FromBigEndianBytes(x1), + // UInt256.FromBigEndianBytes(y1), + // UInt256.FromBigEndianBytes(x2), + // UInt256.FromBigEndianBytes(y2) + // ); + // var expectedX3 = expectedX3UInt256.ToBigEndianBytes(); + // var expectedY3 = expectedY3UInt256.ToBigEndianBytes(); + // + // // Act + // var (x3Result, y3Result) = contractContext.Bn254G1Add(x1, y1, x2, y2); + // + // // Assert + // x3Result.ShouldBe(expectedX3); + // y3Result.ShouldBe(expectedY3); + // } + // + // + // [Fact] + // public void Bn254Pairing_Test() + // { + // var bridgeContext = GetRequiredService().Create(); + // var contractContext = new CSharpSmartContractContext(bridgeContext); + // + // // Arrange + // var input = new (byte[], byte[], byte[], byte[], byte[], byte[])[] + // { + // ( + // ToBytes32(new BigIntValue(0)), + // ToBytes32(new BigIntValue(0)), + // ToBytes32(new BigIntValue(0)), + // ToBytes32(new BigIntValue(0)), + // ToBytes32(new BigIntValue(0)), + // ToBytes32(new BigIntValue(0)) + // ) + // }; + // + // // Use raw API to compute expected results + // bool expected = Bn254.Net.Bn254.Pairing(new (UInt256, UInt256, UInt256, UInt256, UInt256, UInt256)[] + // { + // ( + // UInt256.FromBigEndianBytes(input[0].Item1), + // UInt256.FromBigEndianBytes(input[0].Item2), + // UInt256.FromBigEndianBytes(input[0].Item3), + // UInt256.FromBigEndianBytes(input[0].Item4), + // UInt256.FromBigEndianBytes(input[0].Item5), + // UInt256.FromBigEndianBytes(input[0].Item6) + // ) + // }); + // + // // Act + // bool result = contractContext.Bn254Pairing(input); + // + // // Assert + // result.ShouldBe(expected); + // } } \ No newline at end of file From 3383c90b6456cdf3598a54b8590d40d628117529 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Mon, 30 Dec 2024 09:52:57 +0800 Subject: [PATCH 77/83] remove priveteAssets --- src/AElf.Cryptography/AElf.Cryptography.csproj | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/src/AElf.Cryptography/AElf.Cryptography.csproj b/src/AElf.Cryptography/AElf.Cryptography.csproj index d652a84e0c..c26d4ec24f 100644 --- a/src/AElf.Cryptography/AElf.Cryptography.csproj +++ b/src/AElf.Cryptography/AElf.Cryptography.csproj @@ -10,15 +10,9 @@ - - all - - - all - - - all - + + + From ee4801fb6c2e52ef6d167b607f7c26f57b0af7c2 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Mon, 30 Dec 2024 10:00:26 +0800 Subject: [PATCH 78/83] adjust version of Nethereum.Web3 --- src/AElf.Cryptography/AElf.Cryptography.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/AElf.Cryptography/AElf.Cryptography.csproj b/src/AElf.Cryptography/AElf.Cryptography.csproj index c26d4ec24f..641e967bdd 100644 --- a/src/AElf.Cryptography/AElf.Cryptography.csproj +++ b/src/AElf.Cryptography/AElf.Cryptography.csproj @@ -12,7 +12,7 @@ - + From a2e35798009d1bb051eb2967fb80edf3dae3048e Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Mon, 30 Dec 2024 11:55:25 +0800 Subject: [PATCH 79/83] remove unused code --- .../Patchers/Module/SafeMath/Patcher.cs | 1 + .../ContractCodeLoadContext.cs | 2 +- .../AElf.Runtime.CSharp.csproj | 3 - .../CSharpSmartContractAbstract.cs | 2 - .../CSharpSmartContractContext.cs | 59 ++----- ...lainTransactionExecutingAsPluginService.cs | 1 - .../AElf.Sdk.CSharp.Tests.csproj | 8 - .../CSharpSmartContractContextTests.cs | 159 ------------------ .../ed25519_testdata.json | 44 ----- 9 files changed, 15 insertions(+), 264 deletions(-) delete mode 100644 test/AElf.Sdk.CSharp.Tests/ed25519_testdata.json diff --git a/src/AElf.CSharp.CodeOps/Patchers/Module/SafeMath/Patcher.cs b/src/AElf.CSharp.CodeOps/Patchers/Module/SafeMath/Patcher.cs index 2d8ec1ebe6..2bc2e46232 100644 --- a/src/AElf.CSharp.CodeOps/Patchers/Module/SafeMath/Patcher.cs +++ b/src/AElf.CSharp.CodeOps/Patchers/Module/SafeMath/Patcher.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; +using AElf.Sdk.CSharp; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Cecil.Rocks; diff --git a/src/AElf.Runtime.CSharp.Core/ContractCodeLoadContext.cs b/src/AElf.Runtime.CSharp.Core/ContractCodeLoadContext.cs index c8df9a2114..507ef7bdcc 100644 --- a/src/AElf.Runtime.CSharp.Core/ContractCodeLoadContext.cs +++ b/src/AElf.Runtime.CSharp.Core/ContractCodeLoadContext.cs @@ -28,7 +28,7 @@ protected override Assembly Load(AssemblyName assemblyName) /// private Assembly LoadFromFolderOrDefault(AssemblyName assemblyName) { - if ("AElf.Sdk.CSharp".Equals(assemblyName.Name)) + if (assemblyName.Name.StartsWith("AElf.Sdk")) { // Sdk assembly should NOT be shared using var stream = _sdkStreamManager.GetStream(assemblyName); diff --git a/src/AElf.Runtime.CSharp/AElf.Runtime.CSharp.csproj b/src/AElf.Runtime.CSharp/AElf.Runtime.CSharp.csproj index b9c1d1df61..bf9914645e 100644 --- a/src/AElf.Runtime.CSharp/AElf.Runtime.CSharp.csproj +++ b/src/AElf.Runtime.CSharp/AElf.Runtime.CSharp.csproj @@ -22,9 +22,6 @@ - - - diff --git a/src/AElf.Sdk.CSharp/CSharpSmartContractAbstract.cs b/src/AElf.Sdk.CSharp/CSharpSmartContractAbstract.cs index f550dc596e..31d642fdf0 100644 --- a/src/AElf.Sdk.CSharp/CSharpSmartContractAbstract.cs +++ b/src/AElf.Sdk.CSharp/CSharpSmartContractAbstract.cs @@ -20,6 +20,4 @@ protected void Assert(bool asserted, string message = "Assertion failed!") } internal abstract void InternalInitialize(ISmartContractBridgeContext bridgeContext); - - // public IBuiltIns BuiltIns { get; internal set; } } \ No newline at end of file diff --git a/src/AElf.Sdk.CSharp/CSharpSmartContractContext.cs b/src/AElf.Sdk.CSharp/CSharpSmartContractContext.cs index 911d71a2e6..5e3ed6c94a 100644 --- a/src/AElf.Sdk.CSharp/CSharpSmartContractContext.cs +++ b/src/AElf.Sdk.CSharp/CSharpSmartContractContext.cs @@ -14,12 +14,9 @@ namespace AElf.Sdk.CSharp; /// public class CSharpSmartContractContext : ISmartContractBridgeContext { - // private IBuiltIns BuiltInsImplementation { get; } - public CSharpSmartContractContext(ISmartContractBridgeContext smartContractBridgeContextImplementation) { SmartContractBridgeContextImplementation = smartContractBridgeContextImplementation; - // BuiltInsImplementation = new InternalBuiltIns(); } public ISmartContractBridgeContext SmartContractBridgeContextImplementation { get; } @@ -88,7 +85,7 @@ public void FireLogEvent(LogEvent logEvent) /// The height of the block that contains the transaction before charging. /// public Transaction Transaction => SmartContractBridgeContextImplementation.Transaction; - + /// /// The time included in the current blocks header. /// @@ -151,7 +148,7 @@ public void DeployContract(Address address, SmartContractRegistration registrati { SmartContractBridgeContextImplementation.DeployContract(address, registration, name); } - + /// /// Update a smart contract (only the genesis contract can call it). /// @@ -162,21 +159,17 @@ public void UpdateContract(Address address, SmartContractRegistration registrati { SmartContractBridgeContextImplementation.UpdateContract(address, registration, name); } - + public ContractInfoDto DeploySmartContract(Address address, SmartContractRegistration registration, Hash name) { - return SmartContractBridgeContextImplementation.DeploySmartContract(address, registration, name); + return SmartContractBridgeContextImplementation.DeploySmartContract(address,registration,name); } - - public ContractInfoDto UpdateSmartContract(Address address, SmartContractRegistration registration, Hash name, - string previousContractVersion) + public ContractInfoDto UpdateSmartContract(Address address, SmartContractRegistration registration, Hash name,string previousContractVersion) { - return SmartContractBridgeContextImplementation.UpdateSmartContract(address, registration, name, - previousContractVersion); + return SmartContractBridgeContextImplementation.UpdateSmartContract(address,registration,name,previousContractVersion); } - public ContractVersionCheckDto CheckContractVersion(string previousContractVersion, - SmartContractRegistration registration) + public ContractVersionCheckDto CheckContractVersion(string previousContractVersion, SmartContractRegistration registration) { return SmartContractBridgeContextImplementation.CheckContractVersion(previousContractVersion, registration); } @@ -228,14 +221,13 @@ public void SendVirtualInline(Hash fromVirtualAddress, Address toAddress, string SmartContractBridgeContextImplementation.SendVirtualInline(fromVirtualAddress, toAddress, methodName, args); } - - public void SendVirtualInline(Hash fromVirtualAddress, Address toAddress, string methodName, ByteString args, - bool logTransaction) + + public void SendVirtualInline(Hash fromVirtualAddress, Address toAddress, string methodName, ByteString args,bool logTransaction) { SmartContractBridgeContextImplementation.SendVirtualInline(fromVirtualAddress, toAddress, methodName, - args, logTransaction); + args,logTransaction); } - + /// /// Sends a virtual inline transaction to another contract. This method is only available to system smart contract. @@ -253,7 +245,7 @@ public void SendVirtualInlineBySystemContract(Hash fromVirtualAddress, Address t SmartContractBridgeContextImplementation.SendVirtualInlineBySystemContract(fromVirtualAddress, toAddress, methodName, args); } - + public void SendVirtualInlineBySystemContract(Hash fromVirtualAddress, Address toAddress, string methodName, ByteString args, bool logTransaction) { @@ -394,34 +386,9 @@ public Address ConvertVirtualAddressToContractAddressWithContractHashName(Hash v return SmartContractBridgeContextImplementation.ConvertVirtualAddressToContractAddressWithContractHashName( virtualAddress); } - + public bool ECVrfVerify(byte[] pubKey, byte[] alpha, byte[] pi, out byte[] beta) { return SmartContractBridgeContextImplementation.ECVrfVerify(pubKey, alpha, pi, out beta); } - - // public bool Ed25519Verify(byte[] signature, byte[] message, byte[] publicKey) - // { - // return BuiltInsImplementation.Ed25519Verify(signature, message, publicKey); - // } - // - // public byte[] Keccak256(byte[] message) - // { - // return BuiltInsImplementation.Keccak256(message); - // } - // - // public (byte[] x, byte[] y) Bn254G1Mul(byte[] x1, byte[] y1, byte[] s) - // { - // return BuiltInsImplementation.Bn254G1Mul(x1, y1, s); - // } - // - // public (byte[] x3, byte[] y3) Bn254G1Add(byte[] x1, byte[] y1, byte[] x2, byte[] y2) - // { - // return BuiltInsImplementation.Bn254G1Add(x1, y1, x2, y2); - // } - // - // public bool Bn254Pairing((byte[], byte[], byte[], byte[], byte[], byte[])[] input) - // { - // return BuiltInsImplementation.Bn254Pairing(input); - // } } \ No newline at end of file diff --git a/test/AElf.Kernel.SmartContract.ExecutionPluginForMethodFee.Tests/Service/PlainTransactionExecutingAsPluginService.cs b/test/AElf.Kernel.SmartContract.ExecutionPluginForMethodFee.Tests/Service/PlainTransactionExecutingAsPluginService.cs index 51d07eafe4..f43cef0e42 100644 --- a/test/AElf.Kernel.SmartContract.ExecutionPluginForMethodFee.Tests/Service/PlainTransactionExecutingAsPluginService.cs +++ b/test/AElf.Kernel.SmartContract.ExecutionPluginForMethodFee.Tests/Service/PlainTransactionExecutingAsPluginService.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; -using AElf.Kernel.Blockchain.Application; using AElf.Kernel.FeatureDisable.Core; using AElf.Kernel.SmartContract.Application; using AElf.Kernel.SmartContract.Domain; diff --git a/test/AElf.Sdk.CSharp.Tests/AElf.Sdk.CSharp.Tests.csproj b/test/AElf.Sdk.CSharp.Tests/AElf.Sdk.CSharp.Tests.csproj index 9a260f1451..b7379a81dc 100644 --- a/test/AElf.Sdk.CSharp.Tests/AElf.Sdk.CSharp.Tests.csproj +++ b/test/AElf.Sdk.CSharp.Tests/AElf.Sdk.CSharp.Tests.csproj @@ -4,14 +4,12 @@ false - all runtime; build; native; contentfiles; analyzers - @@ -32,10 +30,4 @@ - - - - all - - \ No newline at end of file diff --git a/test/AElf.Sdk.CSharp.Tests/CSharpSmartContractContextTests.cs b/test/AElf.Sdk.CSharp.Tests/CSharpSmartContractContextTests.cs index 24ac83db54..4e0f98d97a 100644 --- a/test/AElf.Sdk.CSharp.Tests/CSharpSmartContractContextTests.cs +++ b/test/AElf.Sdk.CSharp.Tests/CSharpSmartContractContextTests.cs @@ -1,12 +1,9 @@ -using System; using AElf.Cryptography; using AElf.Kernel; using AElf.Kernel.SmartContract; using AElf.Kernel.SmartContract.Application; using AElf.Types; -using Bn254.Net; using Google.Protobuf; -using Nethereum.Util; using Shouldly; using Xunit; using CustomContract = AElf.Runtime.CSharp.Tests.TestContract; @@ -15,41 +12,6 @@ namespace AElf.Sdk.CSharp.Tests; public class CSharpSmartContractContextTests : SdkCSharpTestBase { - // [Fact] - // public void Verify_Ed25519Verify() - // { - // var bridgeContext = GetRequiredService().Create(); - // var origin = SampleAddress.AddressList[0]; - // bridgeContext.TransactionContext = new TransactionContext - // { - // Origin = origin, - // Transaction = new Transaction - // { - // From = SampleAddress.AddressList[1], - // To = SampleAddress.AddressList[2] - // } - // }; - // var contractContext = new CSharpSmartContractContext(bridgeContext); - // var publicKey = "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"; - // var message = ""; - // var signature = "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"; - // var ed25519VerifyResult = contractContext.Ed25519Verify( - // ByteArrayHelper.HexStringToByteArray(signature), - // ByteArrayHelper.HexStringToByteArray(message), - // ByteArrayHelper.HexStringToByteArray(publicKey)); - // ed25519VerifyResult.ShouldBe(true); - // - // var contractContext1 = new CSharpSmartContractContext(bridgeContext); - // var publicKey1 = "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"; - // var message1 = "1"; - // var signature1 = "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"; - // Should.Throw(() => contractContext1.Ed25519Verify( - // ByteArrayHelper.HexStringToByteArray(signature1), - // ByteArrayHelper.HexStringToByteArray(message1), - // ByteArrayHelper.HexStringToByteArray(publicKey1))); - // - // } - [Fact] public void Verify_Transaction_Origin_SetValue() { @@ -87,125 +49,4 @@ public void Transaction_VerifySignature_Test() var result = bridgeContext.VerifySignature(transaction); result.ShouldBeTrue(); } - - // [Fact] - // public void keccak256_test() - // { - // var bridgeContext = GetRequiredService().Create(); - // var origin = SampleAddress.AddressList[0]; - // var contractContext = new CSharpSmartContractContext(bridgeContext); - // byte[] message = System.Text.Encoding.UTF8.GetBytes("Test message"); - // var fact = contractContext.Keccak256(message); - // var expected = Sha3Keccack.Current.CalculateHash(message); - // fact.ShouldBe(expected); - // } - // public static byte[] ToBytes32(BigIntValue value) - // { - // var bytes = value.ToBigEndianBytes(); - // var newArray = new byte[32]; - // for (int i = 0; i < bytes.Length; i++) - // { - // newArray[31 - i] = bytes[bytes.Length - 1 - i]; - // } - // - // return newArray; - // } - // - // [Fact] - // public void Bn254G1Mul_Test() - // { - // var bridgeContext = GetRequiredService().Create(); - // var contractContext = new CSharpSmartContractContext(bridgeContext); - // - // // Arrange - // byte[] x1 = ToBytes32(new BigIntValue(0)); - // byte[] y1 = ToBytes32(new BigIntValue(0)); - // byte[] scalar = ToBytes32(new BigIntValue(0)); - // - // // use raw api to compute result - // var (expectedXUInt256, expectedYUInt256) = Bn254.Net.Bn254.Mul( - // UInt256.FromBigEndianBytes(x1), - // UInt256.FromBigEndianBytes(y1), - // UInt256.FromBigEndianBytes(scalar) - // ); - // var expectedX = expectedXUInt256.ToBigEndianBytes(); - // var expectedY = expectedYUInt256.ToBigEndianBytes(); - // - // // Act - // var (xResult, yResult) = contractContext.Bn254G1Mul(x1, y1, scalar); - // - // // Assert - // xResult.ShouldBe(expectedX); - // yResult.ShouldBe(expectedY); - // } - // - // [Fact] - // public void Bn254G1Add_Test() - // { - // var bridgeContext = GetRequiredService().Create(); - // var contractContext = new CSharpSmartContractContext(bridgeContext); - // - // // Arrange - // byte[] x1 = ToBytes32(new BigIntValue(0)); - // byte[] y1 = ToBytes32(new BigIntValue(0)); - // byte[] x2 = ToBytes32(new BigIntValue(0)); - // byte[] y2 = ToBytes32(new BigIntValue(0)); - // - // // Use raw API to compute expected results - // var (expectedX3UInt256, expectedY3UInt256) = Bn254.Net.Bn254.Add( - // UInt256.FromBigEndianBytes(x1), - // UInt256.FromBigEndianBytes(y1), - // UInt256.FromBigEndianBytes(x2), - // UInt256.FromBigEndianBytes(y2) - // ); - // var expectedX3 = expectedX3UInt256.ToBigEndianBytes(); - // var expectedY3 = expectedY3UInt256.ToBigEndianBytes(); - // - // // Act - // var (x3Result, y3Result) = contractContext.Bn254G1Add(x1, y1, x2, y2); - // - // // Assert - // x3Result.ShouldBe(expectedX3); - // y3Result.ShouldBe(expectedY3); - // } - // - // - // [Fact] - // public void Bn254Pairing_Test() - // { - // var bridgeContext = GetRequiredService().Create(); - // var contractContext = new CSharpSmartContractContext(bridgeContext); - // - // // Arrange - // var input = new (byte[], byte[], byte[], byte[], byte[], byte[])[] - // { - // ( - // ToBytes32(new BigIntValue(0)), - // ToBytes32(new BigIntValue(0)), - // ToBytes32(new BigIntValue(0)), - // ToBytes32(new BigIntValue(0)), - // ToBytes32(new BigIntValue(0)), - // ToBytes32(new BigIntValue(0)) - // ) - // }; - // - // // Use raw API to compute expected results - // bool expected = Bn254.Net.Bn254.Pairing(new (UInt256, UInt256, UInt256, UInt256, UInt256, UInt256)[] - // { - // ( - // UInt256.FromBigEndianBytes(input[0].Item1), - // UInt256.FromBigEndianBytes(input[0].Item2), - // UInt256.FromBigEndianBytes(input[0].Item3), - // UInt256.FromBigEndianBytes(input[0].Item4), - // UInt256.FromBigEndianBytes(input[0].Item5), - // UInt256.FromBigEndianBytes(input[0].Item6) - // ) - // }); - // - // // Act - // bool result = contractContext.Bn254Pairing(input); - // - // // Assert - // result.ShouldBe(expected); - // } } \ No newline at end of file diff --git a/test/AElf.Sdk.CSharp.Tests/ed25519_testdata.json b/test/AElf.Sdk.CSharp.Tests/ed25519_testdata.json deleted file mode 100644 index 60d4a2bad4..0000000000 --- a/test/AElf.Sdk.CSharp.Tests/ed25519_testdata.json +++ /dev/null @@ -1,44 +0,0 @@ -[ - { - "secret_key": "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", - "public_key": "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", - "message": "", - "signed": "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b", - "signature": "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b" - }, - { - "secret_key": "4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb", - "public_key": "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c", - "message": "72", - "signed": "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c0072", - "signature": "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00" - }, - { - "secret_key": "c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7", - "public_key": "fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025", - "message": "af82", - "signed": "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40aaf82", - "signature": "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a" - }, - { - "secret_key": "0d4a05b07352a5436e180356da0ae6efa0345ff7fb1572575772e8005ed978e9", - "public_key": "e61a185bcef2613a6c7cb79763ce945d3b245d76114dd440bcf5f2dc1aa57057", - "message": "cbc77b", - "signed": "d9868d52c2bebce5f3fa5a79891970f309cb6591e3e1702a70276fa97c24b3a8e58606c38c9758529da50ee31b8219cba45271c689afa60b0ea26c99db19b00ccbc77b", - "signature": "d9868d52c2bebce5f3fa5a79891970f309cb6591e3e1702a70276fa97c24b3a8e58606c38c9758529da50ee31b8219cba45271c689afa60b0ea26c99db19b00c" - }, - { - "secret_key": "6df9340c138cc188b5fe4464ebaa3f7fc206a2d55c3434707e74c9fc04e20ebb", - "public_key": "c0dac102c4533186e25dc43128472353eaabdb878b152aeb8e001f92d90233a7", - "message": "5f4c8989", - "signed": "124f6fc6b0d100842769e71bd530664d888df8507df6c56dedfdb509aeb93416e26b918d38aa06305df3095697c18b2aa832eaa52edc0ae49fbae5a85e150c075f4c8989", - "signature": "124f6fc6b0d100842769e71bd530664d888df8507df6c56dedfdb509aeb93416e26b918d38aa06305df3095697c18b2aa832eaa52edc0ae49fbae5a85e150c07" - }, - { - "secret_key": "b780381a65edf8b78f6945e8dbec7941ac049fd4c61040cf0c324357975a293c", - "public_key": "e253af0766804b869bb1595be9765b534886bbaab8305bf50dbc7f899bfb5f01", - "message": "18b6bec097", - "signed": "b2fc46ad47af464478c199e1f8be169f1be6327c7f9a0a6689371ca94caf04064a01b22aff1520abd58951341603faed768cf78ce97ae7b038abfe456aa17c0918b6bec097", - "signature": "b2fc46ad47af464478c199e1f8be169f1be6327c7f9a0a6689371ca94caf04064a01b22aff1520abd58951341603faed768cf78ce97ae7b038abfe456aa17c09" - } -] \ No newline at end of file From 7b1eb9b7654b3bcfe76418b0dcc9a39416b37e12 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Wed, 1 Jan 2025 18:49:19 +0800 Subject: [PATCH 80/83] Add unit test --- .../Bn254HelperTest.cs | 111 ++++++++++++++++++ .../EdDsaHelperTest.cs | 25 ++++ .../KeccakHelperTest.cs | 22 ++++ 3 files changed, 158 insertions(+) create mode 100644 test/AElf.Cryptography.Tests/Bn254HelperTest.cs create mode 100644 test/AElf.Cryptography.Tests/EdDsaHelperTest.cs create mode 100644 test/AElf.Cryptography.Tests/KeccakHelperTest.cs diff --git a/test/AElf.Cryptography.Tests/Bn254HelperTest.cs b/test/AElf.Cryptography.Tests/Bn254HelperTest.cs new file mode 100644 index 0000000000..5a46f165bc --- /dev/null +++ b/test/AElf.Cryptography.Tests/Bn254HelperTest.cs @@ -0,0 +1,111 @@ +using AElf.Cryptography.Bn254; +using AElf.Types; +using Bn254.Net; +using Shouldly; +using Xunit; +using NetBn254 = Bn254.Net; + +namespace AElf.Cryptography.Tests; + +public class EdDsaHelperTest +{ + public static byte[] ToBytes32(BigIntValue value) + { + var bytes = value.ToBigEndianBytes(); + var newArray = new byte[32]; + for (int i = 0; i < bytes.Length; i++) + { + newArray[31 - i] = bytes[bytes.Length - 1 - i]; + } + + return newArray; + } + + [Fact] + public void Bn254G1Mul_Test() + { + // Arrange + byte[] x1 = ToBytes32(new BigIntValue(0)); + byte[] y1 = ToBytes32(new BigIntValue(0)); + byte[] scalar = ToBytes32(new BigIntValue(0)); + + // use raw api to compute result + var (expectedXuInt256, expectedYuInt256) = NetBn254.Bn254.Mul( + UInt256.FromBigEndianBytes(x1), + UInt256.FromBigEndianBytes(y1), + UInt256.FromBigEndianBytes(scalar) + ); + var expectedX = expectedXuInt256.ToBigEndianBytes(); + var expectedY = expectedYuInt256.ToBigEndianBytes(); + + // Act + var (xResult, yResult) = Bn254Helper.Bn254G1Mul(x1, y1, scalar); + + // Assert + xResult.ShouldBe(expectedX); + yResult.ShouldBe(expectedY); + } + + [Fact] + public void Bn254G1Add_Test() + { + // Arrange + byte[] x1 = ToBytes32(new BigIntValue(0)); + byte[] y1 = ToBytes32(new BigIntValue(0)); + byte[] x2 = ToBytes32(new BigIntValue(0)); + byte[] y2 = ToBytes32(new BigIntValue(0)); + + // Use raw API to compute expected results + var (expectedX3UInt256, expectedY3UInt256) = NetBn254.Bn254.Add( + UInt256.FromBigEndianBytes(x1), + UInt256.FromBigEndianBytes(y1), + UInt256.FromBigEndianBytes(x2), + UInt256.FromBigEndianBytes(y2) + ); + var expectedX3 = expectedX3UInt256.ToBigEndianBytes(); + var expectedY3 = expectedY3UInt256.ToBigEndianBytes(); + + // Act + var (x3Result, y3Result) = Bn254Helper.Bn254G1Add(x1, y1, x2, y2); + + // Assert + x3Result.ShouldBe(expectedX3); + y3Result.ShouldBe(expectedY3); + } + + [Fact] + public void Bn254Pairing_Test() + { + // Arrange + var input = new (byte[], byte[], byte[], byte[], byte[], byte[])[] + { + ( + ToBytes32(new BigIntValue(0)), + ToBytes32(new BigIntValue(0)), + ToBytes32(new BigIntValue(0)), + ToBytes32(new BigIntValue(0)), + ToBytes32(new BigIntValue(0)), + ToBytes32(new BigIntValue(0)) + ) + }; + + // Use raw API to compute expected results + bool expected = NetBn254.Bn254.Pairing(new (UInt256, UInt256, UInt256, UInt256, UInt256, UInt256)[] + { + ( + UInt256.FromBigEndianBytes(input[0].Item1), + UInt256.FromBigEndianBytes(input[0].Item2), + UInt256.FromBigEndianBytes(input[0].Item3), + UInt256.FromBigEndianBytes(input[0].Item4), + UInt256.FromBigEndianBytes(input[0].Item5), + UInt256.FromBigEndianBytes(input[0].Item6) + ) + }); + + // Act + bool result = Bn254Helper.Bn254Pairing(input); + + // Assert + result.ShouldBe(expected); + } +} \ No newline at end of file diff --git a/test/AElf.Cryptography.Tests/EdDsaHelperTest.cs b/test/AElf.Cryptography.Tests/EdDsaHelperTest.cs new file mode 100644 index 0000000000..443415463c --- /dev/null +++ b/test/AElf.Cryptography.Tests/EdDsaHelperTest.cs @@ -0,0 +1,25 @@ +using AElf.Cryptography.EdDSA; +using Shouldly; +using Xunit; + +namespace AElf.Cryptography.Tests; + +public class Bn254HelperTest +{ + [Fact] + public void Ed25519Verify_Test() + { + var publicKey = "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"; + var message = ""; + var signature = + "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"; + + var publicKeyBytes = ByteArrayHelper.HexStringToByteArray(publicKey); + var messageBytes = ByteArrayHelper.HexStringToByteArray(message); + var signatureBytes = ByteArrayHelper.HexStringToByteArray(signature); + + var ed25519VerifyResult = EdDsaHelper.Ed25519Verify(signatureBytes, messageBytes, publicKeyBytes); + + ed25519VerifyResult.ShouldBe(true); + } +} \ No newline at end of file diff --git a/test/AElf.Cryptography.Tests/KeccakHelperTest.cs b/test/AElf.Cryptography.Tests/KeccakHelperTest.cs new file mode 100644 index 0000000000..d6c8faa3fa --- /dev/null +++ b/test/AElf.Cryptography.Tests/KeccakHelperTest.cs @@ -0,0 +1,22 @@ +using System.Text; +using AElf.Cryptography.Keccak; +using Nethereum.Util; +using Shouldly; +using Xunit; + +namespace AElf.Cryptography.Tests; + +public class KeccakHelperTest +{ + [Fact] + public void Keccak256_Test() + { + byte[] message = Encoding.UTF8.GetBytes("Test message"); + + var expectedHash = Sha3Keccack.Current.CalculateHash(message); + + var computedHash = KeccakHelper.Keccak256(message); + + computedHash.ShouldBe(expectedHash); + } +} \ No newline at end of file From 99e57c9ff6825b82f4133a0f685e33c71802fa24 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Thu, 2 Jan 2025 17:37:41 +0800 Subject: [PATCH 81/83] Change method name to TransactionResultWithBVP --- .../Services/TransactionResultAppService.cs | 4 ++-- .../BlockChainAppServiceTest.cs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs index 1923b9f989..c382c0a8de 100644 --- a/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs +++ b/src/AElf.WebApp.Application.Chain/Services/TransactionResultAppService.cs @@ -25,7 +25,7 @@ public interface ITransactionResultAppService { Task GetTransactionResultAsync(string transactionId); - Task GetTransactionResultV2Async(string transactionId); + Task GetTransactionResultWithBVPAsync(string transactionId); Task> GetTransactionResultsAsync(string blockHash, int offset = 0, int limit = 10); @@ -127,7 +127,7 @@ await _transactionResultProxyService.InvalidTransactionResultService.GetInvalidT /// /// transaction id /// - public async Task GetTransactionResultV2Async(string transactionId) + public async Task GetTransactionResultWithBVPAsync(string transactionId) { Hash transactionIdHash; try diff --git a/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs b/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs index 926798cbe1..d72f7d6d4d 100644 --- a/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs +++ b/test/AElf.WebApp.Application.Chain.Tests/BlockChainAppServiceTest.cs @@ -687,7 +687,7 @@ public async Task Get_TransactionResult_Success_Test() } [Fact] - public async Task Get_TransactionResultV2_Expired_Test() + public async Task Get_TransactionResultWithBVP_Expired_Test() { // Generate a transaction var transaction = await _osTestHelper.GenerateTransferTransaction(); @@ -701,7 +701,7 @@ public async Task Get_TransactionResultV2_Expired_Test() // Check transaction status var response = await GetResponseAsObjectAsync( - $"/api/blockChain/transactionResultV2?transactionId={transactionHex}"); + $"/api/blockChain/transactionResultWithBVP?transactionId={transactionHex}"); response.StatusWithBVP.ShouldBe(TransactionResultStatus.Expired.ToString().ToUpper()); } From 03ede965e5951d45186d449ab4a6830e2fb1b09a Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Fri, 3 Jan 2025 16:36:56 +0800 Subject: [PATCH 82/83] Remove inline_transaction.proto --- protobuf/inline_transaction.proto | 15 --------------- 1 file changed, 15 deletions(-) delete mode 100644 protobuf/inline_transaction.proto diff --git a/protobuf/inline_transaction.proto b/protobuf/inline_transaction.proto deleted file mode 100644 index 8aa96497fe..0000000000 --- a/protobuf/inline_transaction.proto +++ /dev/null @@ -1,15 +0,0 @@ -syntax = "proto3"; - -option csharp_namespace = "AElf.Types"; - - -import "aelf/core.proto"; -import "aelf/options.proto"; - -service InlineTransaction { -} - -message InlineTransactionCreated { - option (aelf.is_event) = true; - aelf.Transaction transaction = 1 [(aelf.is_indexed) = true]; -} From 3688493daf8b0c3a8ad80a901c580b33150c25c2 Mon Sep 17 00:00:00 2001 From: chopin-fan Date: Fri, 3 Jan 2025 16:42:49 +0800 Subject: [PATCH 83/83] Remove poseidong --- src/AElf.CSharp.CodeOps/AElf.CSharp.CodeOps.csproj | 1 - 1 file changed, 1 deletion(-) diff --git a/src/AElf.CSharp.CodeOps/AElf.CSharp.CodeOps.csproj b/src/AElf.CSharp.CodeOps/AElf.CSharp.CodeOps.csproj index d931ee9e76..74a45d8ccf 100644 --- a/src/AElf.CSharp.CodeOps/AElf.CSharp.CodeOps.csproj +++ b/src/AElf.CSharp.CodeOps/AElf.CSharp.CodeOps.csproj @@ -11,7 +11,6 @@ -