Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: concurrency conflict in MemPool.TryRemoveUnVerified #3500

18 changes: 13 additions & 5 deletions src/Neo/Ledger/MemoryPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -445,12 +445,20 @@ private void RemoveConflictsOfVerified(PoolItem item)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal bool TryRemoveUnVerified(UInt256 hash, [MaybeNullWhen(false)] out PoolItem? item)
{
if (!_unverifiedTransactions.TryGetValue(hash, out item))
return false;
_txRwLock.EnterWriteLock();
try
{
if (!_unverifiedTransactions.TryGetValue(hash, out item))
return false;

_unverifiedTransactions.Remove(hash);
_unverifiedSortedTransactions.Remove(item);
return true;
_unverifiedTransactions.Remove(hash);
_unverifiedSortedTransactions.Remove(item);
return true;
}
shargon marked this conversation as resolved.
Show resolved Hide resolved
finally
{
_txRwLock.ExitWriteLock();
}
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
Expand Down
19 changes: 19 additions & 0 deletions tests/Neo.UnitTests/Ledger/UT_MemoryPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -747,6 +747,25 @@ public void TestUpdatePoolForBlockPersisted()
_unit.VerifiedCount.Should().Be(0);
}

[TestMethod]
public void TestTryRemoveUnVerified()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how could this test the conflict?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Race condition is hard to test.

{
AddTransactions(32);
_unit.SortedTxCount.Should().Be(32);

var txs = _unit.GetSortedVerifiedTransactions().ToArray();
_unit.InvalidateVerifiedTransactions();

_unit.SortedTxCount.Should().Be(0);

foreach (var tx in txs)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe _unit.UnVerifiedCount.Should().Be(32); before the loop

{
_unit.TryRemoveUnVerified(tx.Hash, out _);
}

_unit.UnVerifiedCount.Should().Be(0);
}

public static StorageKey CreateStorageKey(int id, byte prefix, byte[] key = null)
{
byte[] buffer = GC.AllocateUninitializedArray<byte>(sizeof(byte) + (key?.Length ?? 0));
Expand Down
Loading