Skip to content

Commit

Permalink
Fix tx attributes (#2276)
Browse files Browse the repository at this point in the history
* Fix tx attributes

* Optimize

* Optimize

* Remove reflection

Co-authored-by: Erik Zhang <erik@neo.org>
  • Loading branch information
shargon and erikzhang committed Jan 28, 2021
1 parent 87856b9 commit f503027
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/neo/Network/P2P/Payloads/Transaction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -220,14 +220,15 @@ void IInteroperable.FromStackItem(StackItem stackItem)

public T GetAttribute<T>() where T : TransactionAttribute
{
return GetAttributes<T>()?.First();
return GetAttributes<T>().FirstOrDefault();
}

public T[] GetAttributes<T>() where T : TransactionAttribute
public IEnumerable<T> GetAttributes<T>() where T : TransactionAttribute
{
_attributesCache ??= attributes.GroupBy(p => p.GetType()).ToDictionary(p => p.Key, p => (TransactionAttribute[])p.OfType<T>().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<T>();
return Enumerable.Empty<T>();
}

public override int GetHashCode()
Expand Down
25 changes: 25 additions & 0 deletions tests/neo.UnitTests/Network/P2P/Payloads/UT_Transaction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<TransactionAttribute>(),
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<OracleResponse>());
Assert.IsNull(tx.GetAttribute<HighPriorityAttribute>());

tx.Attributes = new TransactionAttribute[] { new HighPriorityAttribute() };

Assert.IsNull(tx.GetAttribute<OracleResponse>());
Assert.IsNotNull(tx.GetAttribute<HighPriorityAttribute>());
}

[TestMethod]
public void Test_VerifyStateIndependent()
{
Expand Down

0 comments on commit f503027

Please sign in to comment.