From f503027356d553681aa211afb012b4c314a9f4b8 Mon Sep 17 00:00:00 2001 From: Shargon Date: Thu, 28 Jan 2021 22:37:10 +0100 Subject: [PATCH] Fix tx attributes (#2276) * Fix tx attributes * Optimize * Optimize * Remove reflection Co-authored-by: Erik Zhang --- src/neo/Network/P2P/Payloads/Transaction.cs | 11 ++++---- .../Network/P2P/Payloads/UT_Transaction.cs | 25 +++++++++++++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/src/neo/Network/P2P/Payloads/Transaction.cs b/src/neo/Network/P2P/Payloads/Transaction.cs index 5d8ffa4b3a..5ec7297fb2 100644 --- a/src/neo/Network/P2P/Payloads/Transaction.cs +++ b/src/neo/Network/P2P/Payloads/Transaction.cs @@ -220,14 +220,15 @@ void IInteroperable.FromStackItem(StackItem stackItem) public T GetAttribute() where T : TransactionAttribute { - return GetAttributes()?.First(); + return GetAttributes().FirstOrDefault(); } - public T[] GetAttributes() where T : TransactionAttribute + public IEnumerable GetAttributes() where T : TransactionAttribute { - _attributesCache ??= attributes.GroupBy(p => p.GetType()).ToDictionary(p => p.Key, p => (TransactionAttribute[])p.OfType().ToArray()); - _attributesCache.TryGetValue(typeof(T), out var result); - return (T[])result; + _attributesCache ??= attributes.GroupBy(p => p.GetType()).ToDictionary(p => p.Key, p => p.ToArray()); + if (_attributesCache.TryGetValue(typeof(T), out var result)) + return result.OfType(); + return Enumerable.Empty(); } public override int GetHashCode() diff --git a/tests/neo.UnitTests/Network/P2P/Payloads/UT_Transaction.cs b/tests/neo.UnitTests/Network/P2P/Payloads/UT_Transaction.cs index 77d4d5f750..d9e4cab9b8 100644 --- a/tests/neo.UnitTests/Network/P2P/Payloads/UT_Transaction.cs +++ b/tests/neo.UnitTests/Network/P2P/Payloads/UT_Transaction.cs @@ -1072,6 +1072,31 @@ public void ToJson() jObj["sysfee"].AsString().Should().Be("4200000000"); } + [TestMethod] + public void Test_GetAttribute() + { + var tx = new Transaction() + { + Attributes = Array.Empty(), + NetworkFee = 0, + Nonce = (uint)Environment.TickCount, + Script = new byte[Transaction.MaxTransactionSize], + Signers = new Signer[] { new Signer() { Account = UInt160.Zero } }, + SystemFee = 0, + ValidUntilBlock = 0, + Version = 0, + Witnesses = new Witness[0], + }; + + Assert.IsNull(tx.GetAttribute()); + Assert.IsNull(tx.GetAttribute()); + + tx.Attributes = new TransactionAttribute[] { new HighPriorityAttribute() }; + + Assert.IsNull(tx.GetAttribute()); + Assert.IsNotNull(tx.GetAttribute()); + } + [TestMethod] public void Test_VerifyStateIndependent() {