-
Notifications
You must be signed in to change notification settings - Fork 473
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
New filter restricting delegations in txpool #8022
Open
ak88
wants to merge
21
commits into
master
Choose a base branch
from
feature/delegations-in-txpool
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+418
−8
Open
Changes from 20 commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
1a48fd6
start
ak88 64c0936
reject if pending delegation
ak88 e7df773
unit test
ak88 7be934f
remove
ak88 aa2a818
Merge branch 'master' into feature/delegations-in-txpool
ak88 edb1c21
combine address and nonce
ak88 775dda6
combine nonce and address
ak88 1f8fa39
delegation cache
ak88 d35ba1d
tx filter test
ak88 ce4cf84
Format
ak88 2e6e13a
remove delegations when evicted
ak88 963bba1
format
ak88 a7aa58e
Merge branch 'master' into feature/delegations-in-txpool
ak88 ee6fd89
small refactor
ak88 93ecfea
Merge branch 'feature/delegations-in-txpool' of https://github.com/Ne…
ak88 5bdab60
skip bad sigs
ak88 067d504
Update src/Nethermind/Nethermind.TxPool/DelegationCache.cs
ak88 cc6b5d7
code review changes
ak88 e8fbbbc
avoid array allocation
ak88 b0ad70f
Merge branch 'master' into feature/delegations-in-txpool
ak88 5d4ac71
code review
ak88 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
161 changes: 161 additions & 0 deletions
161
src/Nethermind/Nethermind.TxPool.Test/OnlyOneTxPerDelegatedAccountFilterTest.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,161 @@ | ||
// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited | ||
// SPDX-License-Identifier: LGPL-3.0-only | ||
|
||
using Nethermind.Core; | ||
using Nethermind.Core.Specs; | ||
using Nethermind.Core.Test.Builders; | ||
using Nethermind.Crypto; | ||
using Nethermind.Db; | ||
using Nethermind.Evm; | ||
using Nethermind.Logging; | ||
using Nethermind.Specs.Forks; | ||
using Nethermind.State; | ||
using Nethermind.Trie.Pruning; | ||
using Nethermind.TxPool.Collections; | ||
using Nethermind.TxPool.Filters; | ||
using NSubstitute; | ||
using NUnit.Framework; | ||
using Org.BouncyCastle.Pqc.Crypto.Lms; | ||
using System; | ||
using System.Collections; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using System.Text; | ||
using System.Threading.Tasks; | ||
|
||
namespace Nethermind.TxPool.Test; | ||
internal class OnlyOneTxPerDelegatedAccountFilterTest | ||
{ | ||
[Test] | ||
public void Accept_SenderIsNotDelegated_ReturnsAccepted() | ||
{ | ||
IChainHeadSpecProvider headInfoProvider = Substitute.For<IChainHeadSpecProvider>(); | ||
headInfoProvider.GetCurrentHeadSpec().Returns(Prague.Instance); | ||
TxDistinctSortedPool standardPool = new TxDistinctSortedPool(MemoryAllowance.MemPoolSize, Substitute.For<IComparer<Transaction>>(), NullLogManager.Instance); | ||
TxDistinctSortedPool blobPool = new BlobTxDistinctSortedPool(10, Substitute.For<IComparer<Transaction>>(), NullLogManager.Instance); | ||
OnlyOneTxPerDelegatedAccountFilter filter = new(headInfoProvider, standardPool, blobPool, Substitute.For<IReadOnlyStateProvider>(), new CodeInfoRepository(), new DelegationCache()); | ||
Transaction transaction = Build.A.Transaction.SignedAndResolved(new EthereumEcdsa(0), TestItem.PrivateKeyA).TestObject; | ||
TxFilteringState state = new(); | ||
|
||
AcceptTxResult result = filter.Accept(transaction, ref state, TxHandlingOptions.None); | ||
|
||
Assert.That(result, Is.EqualTo(AcceptTxResult.Accepted)); | ||
} | ||
|
||
[Test] | ||
public void Accept_SenderIsDelegatedWithNoTransactionsInPool_ReturnsAccepted() | ||
{ | ||
IChainHeadSpecProvider headInfoProvider = Substitute.For<IChainHeadSpecProvider>(); | ||
headInfoProvider.GetCurrentHeadSpec().Returns(Prague.Instance); | ||
TxDistinctSortedPool standardPool = new TxDistinctSortedPool(MemoryAllowance.MemPoolSize, Substitute.For<IComparer<Transaction>>(), NullLogManager.Instance); | ||
TxDistinctSortedPool blobPool = new BlobTxDistinctSortedPool(10, Substitute.For<IComparer<Transaction>>(), NullLogManager.Instance); | ||
OnlyOneTxPerDelegatedAccountFilter filter = new(headInfoProvider, standardPool, blobPool, Substitute.For<IReadOnlyStateProvider>(), new CodeInfoRepository(), new DelegationCache()); | ||
Transaction transaction = Build.A.Transaction.SignedAndResolved(new EthereumEcdsa(0), TestItem.PrivateKeyA).TestObject; | ||
TxFilteringState state = new(); | ||
|
||
AcceptTxResult result = filter.Accept(transaction, ref state, TxHandlingOptions.None); | ||
|
||
Assert.That(result, Is.EqualTo(AcceptTxResult.Accepted)); | ||
ak88 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
[Test] | ||
public void Accept_SenderIsDelegatedWithOneTransactionInPoolWithSameNonce_ReturnsAccepted() | ||
{ | ||
IChainHeadSpecProvider headInfoProvider = Substitute.For<IChainHeadSpecProvider>(); | ||
headInfoProvider.GetCurrentHeadSpec().Returns(Prague.Instance); | ||
TxDistinctSortedPool standardPool = new TxDistinctSortedPool(MemoryAllowance.MemPoolSize, Substitute.For<IComparer<Transaction>>(), NullLogManager.Instance); | ||
TxDistinctSortedPool blobPool = new BlobTxDistinctSortedPool(10, Substitute.For<IComparer<Transaction>>(), NullLogManager.Instance); | ||
Transaction inPool = Build.A.Transaction.SignedAndResolved(new EthereumEcdsa(0), TestItem.PrivateKeyA).TestObject; | ||
standardPool.TryInsert(inPool.Hash, inPool); | ||
IDb stateDb = new MemDb(); | ||
IDb codeDb = new MemDb(); | ||
TrieStore trieStore = new(stateDb, LimboLogs.Instance); | ||
IWorldState stateProvider = new WorldState(trieStore, codeDb, LimboLogs.Instance); | ||
stateProvider.CreateAccount(TestItem.AddressA, 0); | ||
CodeInfoRepository codeInfoRepository = new(); | ||
byte[] code = [.. Eip7702Constants.DelegationHeader, .. TestItem.PrivateKeyA.Address.Bytes]; | ||
codeInfoRepository.InsertCode(stateProvider, code, TestItem.AddressA, Prague.Instance); | ||
OnlyOneTxPerDelegatedAccountFilter filter = new(headInfoProvider, standardPool, blobPool, stateProvider, codeInfoRepository, new DelegationCache()); | ||
Transaction transaction = Build.A.Transaction.SignedAndResolved(new EthereumEcdsa(0), TestItem.PrivateKeyA).TestObject; | ||
TxFilteringState state = new(); | ||
|
||
AcceptTxResult result = filter.Accept(transaction, ref state, TxHandlingOptions.None); | ||
|
||
Assert.That(result, Is.EqualTo(AcceptTxResult.Accepted)); | ||
} | ||
|
||
[Test] | ||
public void Accept_SenderIsDelegatedWithOneTransactionInPoolWithDifferentNonce_ReturnsOnlyOneTxPerDelegatedAccount() | ||
{ | ||
IChainHeadSpecProvider headInfoProvider = Substitute.For<IChainHeadSpecProvider>(); | ||
headInfoProvider.GetCurrentHeadSpec().Returns(Prague.Instance); | ||
TxDistinctSortedPool standardPool = new TxDistinctSortedPool(MemoryAllowance.MemPoolSize, Substitute.For<IComparer<Transaction>>(), NullLogManager.Instance); | ||
TxDistinctSortedPool blobPool = new BlobTxDistinctSortedPool(10, Substitute.For<IComparer<Transaction>>(), NullLogManager.Instance); | ||
Transaction inPool = Build.A.Transaction.SignedAndResolved(new EthereumEcdsa(0), TestItem.PrivateKeyA).TestObject; | ||
standardPool.TryInsert(inPool.Hash, inPool); | ||
IDb stateDb = new MemDb(); | ||
IDb codeDb = new MemDb(); | ||
TrieStore trieStore = new(stateDb, LimboLogs.Instance); | ||
IWorldState stateProvider = new WorldState(trieStore, codeDb, LimboLogs.Instance); | ||
stateProvider.CreateAccount(TestItem.AddressA, 0); | ||
CodeInfoRepository codeInfoRepository = new(); | ||
byte[] code = [.. Eip7702Constants.DelegationHeader, .. TestItem.PrivateKeyA.Address.Bytes]; | ||
codeInfoRepository.InsertCode(stateProvider, code, TestItem.AddressA, Prague.Instance); | ||
OnlyOneTxPerDelegatedAccountFilter filter = new(headInfoProvider, standardPool, blobPool, stateProvider, codeInfoRepository, new DelegationCache()); | ||
Transaction transaction = Build.A.Transaction.WithNonce(1).SignedAndResolved(new EthereumEcdsa(0), TestItem.PrivateKeyA).TestObject; | ||
TxFilteringState state = new(); | ||
|
||
AcceptTxResult result = filter.Accept(transaction, ref state, TxHandlingOptions.None); | ||
|
||
Assert.That(result, Is.EqualTo(AcceptTxResult.OnlyOneTxPerDelegatedAccount)); | ||
} | ||
|
||
private static object[] EipActiveCases = | ||
{ | ||
new object[]{ true, AcceptTxResult.OnlyOneTxPerDelegatedAccount }, | ||
new object[]{ false, AcceptTxResult.Accepted}, | ||
}; | ||
[TestCaseSource(nameof(EipActiveCases))] | ||
public void Accept_Eip7702IsNotActivated_ReturnsExpected(bool isActive, AcceptTxResult expected) | ||
{ | ||
IChainHeadSpecProvider headInfoProvider = Substitute.For<IChainHeadSpecProvider>(); | ||
headInfoProvider.GetCurrentHeadSpec().Returns(isActive ? Prague.Instance : Cancun.Instance); | ||
TxDistinctSortedPool standardPool = new TxDistinctSortedPool(MemoryAllowance.MemPoolSize, Substitute.For<IComparer<Transaction>>(), NullLogManager.Instance); | ||
TxDistinctSortedPool blobPool = new BlobTxDistinctSortedPool(10, Substitute.For<IComparer<Transaction>>(), NullLogManager.Instance); | ||
Transaction inPool = Build.A.Transaction.WithNonce(0).SignedAndResolved(new EthereumEcdsa(0), TestItem.PrivateKeyA).TestObject; | ||
standardPool.TryInsert(inPool.Hash, inPool); | ||
IDb stateDb = new MemDb(); | ||
IDb codeDb = new MemDb(); | ||
TrieStore trieStore = new(stateDb, LimboLogs.Instance); | ||
IWorldState stateProvider = new WorldState(trieStore, codeDb, LimboLogs.Instance); | ||
stateProvider.CreateAccount(TestItem.AddressA, 0); | ||
CodeInfoRepository codeInfoRepository = new(); | ||
byte[] code = [.. Eip7702Constants.DelegationHeader, .. TestItem.PrivateKeyA.Address.Bytes]; | ||
codeInfoRepository.InsertCode(stateProvider, code, TestItem.AddressA, Prague.Instance); | ||
OnlyOneTxPerDelegatedAccountFilter filter = new(headInfoProvider, standardPool, blobPool, stateProvider, codeInfoRepository, new DelegationCache()); | ||
Transaction transaction = Build.A.Transaction.WithNonce(1).SignedAndResolved(new EthereumEcdsa(0), TestItem.PrivateKeyA).TestObject; | ||
TxFilteringState state = new(); | ||
|
||
AcceptTxResult result = filter.Accept(transaction, ref state, TxHandlingOptions.None); | ||
|
||
Assert.That(result, Is.EqualTo(expected)); | ||
} | ||
|
||
[Test] | ||
public void Accept_SenderHasPendingDelegation_ReturnsPendingDelegation() | ||
{ | ||
IChainHeadSpecProvider headInfoProvider = Substitute.For<IChainHeadSpecProvider>(); | ||
headInfoProvider.GetCurrentHeadSpec().Returns(Prague.Instance); | ||
TxDistinctSortedPool standardPool = new TxDistinctSortedPool(MemoryAllowance.MemPoolSize, Substitute.For<IComparer<Transaction>>(), NullLogManager.Instance); | ||
TxDistinctSortedPool blobPool = new BlobTxDistinctSortedPool(10, Substitute.For<IComparer<Transaction>>(), NullLogManager.Instance); | ||
DelegationCache pendingDelegations = new(); | ||
pendingDelegations.IncrementDelegationCount(TestItem.AddressA, 0); | ||
OnlyOneTxPerDelegatedAccountFilter filter = new(headInfoProvider, standardPool, blobPool, Substitute.For<IReadOnlyStateProvider>(), new CodeInfoRepository(), pendingDelegations); | ||
Transaction transaction = Build.A.Transaction.WithNonce(0).SignedAndResolved(new EthereumEcdsa(0), TestItem.PrivateKeyA).TestObject; | ||
TxFilteringState state = new(); | ||
|
||
AcceptTxResult result = filter.Accept(transaction, ref state, TxHandlingOptions.None); | ||
|
||
Assert.That(result, Is.EqualTo(AcceptTxResult.PendingDelegation)); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -530,6 +530,14 @@ public bool TryGetBucketsWorstValue(TGroupKey groupKey, out TValue? item) | |
return false; | ||
} | ||
|
||
public bool BucketEmptyExcept(TGroupKey groupKey, Func<TValue, bool> predicate) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe better name |
||
{ | ||
using var lockRelease = Lock.Acquire(); | ||
if (_buckets.TryGetValue(groupKey, out EnhancedSortedSet<TValue>? bucket) && bucket.Count > 0) | ||
return bucket.Any(predicate); | ||
return true; | ||
} | ||
|
||
protected void EnsureCapacity(int? expectedCapacity = null) | ||
{ | ||
expectedCapacity ??= _capacity; // expectedCapacity is added for testing purpose. null should be used in production code | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
// SPDX-FileCopyrightText: 2024 Demerzel Solutions Limited | ||
// SPDX-License-Identifier: LGPL-3.0-only | ||
|
||
using Nethermind.Core; | ||
using Nethermind.Int256; | ||
using System; | ||
using System.Collections.Concurrent; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using System.Runtime.CompilerServices; | ||
using System.Text; | ||
using System.Threading.Tasks; | ||
|
||
namespace Nethermind.TxPool; | ||
internal sealed class DelegationCache | ||
{ | ||
private readonly ConcurrentDictionary<UInt256, int> _pendingDelegations = new(); | ||
|
||
public bool HasPending(AddressAsKey key, UInt256 nonce) | ||
{ | ||
return _pendingDelegations.ContainsKey(KeyMask(key, nonce)); | ||
} | ||
|
||
public void DecrementDelegationCount(AddressAsKey key, UInt256 nonce) | ||
{ | ||
InternalIncrement(key, nonce, false); | ||
} | ||
public void IncrementDelegationCount(AddressAsKey key, UInt256 nonce) | ||
{ | ||
InternalIncrement(key, nonce, true); | ||
} | ||
|
||
private void InternalIncrement(AddressAsKey key, UInt256 nonce, bool increment) | ||
{ | ||
UInt256 addressPlusNonce = KeyMask(key, nonce); | ||
|
||
int value = increment ? 1 : -1; | ||
var lastCount = _pendingDelegations.AddOrUpdate(addressPlusNonce, | ||
(k) => | ||
{ | ||
if (increment) | ||
return 1; | ||
return 0; | ||
}, | ||
(k, c) => c + value); | ||
|
||
if (lastCount == 0) | ||
{ | ||
//Remove() is threadsafe and only removes if the count is the same as the updated one | ||
((ICollection<KeyValuePair<UInt256, int>>)_pendingDelegations).Remove( | ||
new KeyValuePair<UInt256, int>(addressPlusNonce, lastCount)); | ||
} | ||
} | ||
|
||
private static UInt256 KeyMask(AddressAsKey key, UInt256 nonce) | ||
{ | ||
//A nonce cannot exceed 2^64-1 and an address is 20 bytes, so we can pack them together in one u256 | ||
ref byte baseRef = ref key.Value.Bytes[0]; | ||
return new UInt256(Unsafe.ReadUnaligned<ulong>(ref baseRef), | ||
Unsafe.ReadUnaligned<ulong>(ref Unsafe.Add(ref baseRef, 8)), | ||
Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref baseRef, 16)), | ||
nonce.u1); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
38 changes: 38 additions & 0 deletions
38
src/Nethermind/Nethermind.TxPool/Filters/OnlyOneTxPerDelegatedAccountFilter.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
using Nethermind.Core; | ||
using Nethermind.Core.Specs; | ||
using Nethermind.Evm; | ||
using Nethermind.Int256; | ||
using Nethermind.State; | ||
using Nethermind.TxPool.Collections; | ||
using System.Collections.Concurrent; | ||
|
||
namespace Nethermind.TxPool.Filters | ||
{ | ||
internal sealed class OnlyOneTxPerDelegatedAccountFilter( | ||
IChainHeadSpecProvider specProvider, | ||
TxDistinctSortedPool standardPool, | ||
TxDistinctSortedPool blobPool, | ||
IReadOnlyStateProvider worldState, | ||
ICodeInfoRepository codeInfoRepository, | ||
DelegationCache pendingDelegations) : IIncomingTxFilter | ||
{ | ||
public AcceptTxResult Accept(Transaction tx, ref TxFilteringState state, TxHandlingOptions txHandlingOptions) | ||
{ | ||
IReleaseSpec spec = specProvider.GetCurrentHeadSpec(); | ||
if (!spec.IsEip7702Enabled) | ||
return AcceptTxResult.Accepted; | ||
|
||
if (pendingDelegations.HasPending(tx.SenderAddress!, tx.Nonce)) | ||
return AcceptTxResult.PendingDelegation; | ||
|
||
if (!codeInfoRepository.TryGetDelegation(worldState, tx.SenderAddress!, out _)) | ||
return AcceptTxResult.Accepted; | ||
//Transactios from the same source can only be either blob transactions or some other type | ||
if (!standardPool.BucketEmptyExcept(tx.SenderAddress!, (t) => t.Nonce == tx.Nonce) || !blobPool.BucketEmptyExcept(tx.SenderAddress!, (t) => t.Nonce == tx.Nonce)) | ||
ak88 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
return AcceptTxResult.OnlyOneTxPerDelegatedAccount; | ||
} | ||
return AcceptTxResult.Accepted; | ||
} | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We are setting up a filter in every test, repeating the same lines of code. Maybe worth to move it to method e.g.
CreateFilter(stateProvider)
, which is returningOnlyOneTxPerDelegatedAccountFilter filter
?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Or even move state provider setup into it and return (filter, stateProvider?)?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
But it's just details about code repeating in test class, feel free to ignore and focus on more important things