-
Notifications
You must be signed in to change notification settings - Fork 666
Expand file tree
/
Copy pathBlockProcessorTests.cs
More file actions
286 lines (243 loc) · 12 KB
/
BlockProcessorTests.cs
File metadata and controls
286 lines (243 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited
// SPDX-License-Identifier: LGPL-3.0-only
using FluentAssertions;
using Nethermind.Blockchain.BeaconBlockRoot;
using Nethermind.Blockchain.Blocks;
using Nethermind.Blockchain.Receipts;
using Nethermind.Blockchain.Test.Validators;
using Nethermind.Consensus.ExecutionRequests;
using Nethermind.Consensus.Processing;
using Nethermind.Consensus.Producers;
using Nethermind.Consensus.Rewards;
using Nethermind.Consensus.Withdrawals;
using Nethermind.Core;
using Nethermind.Core.Eip2930;
using Nethermind.Core.Extensions;
using Nethermind.Core.Specs;
using Nethermind.Core.Test;
using Nethermind.Core.Test.Blockchain;
using Nethermind.Core.Test.Builders;
using Nethermind.Evm.TransactionProcessing;
using Nethermind.JsonRpc.Test.Modules;
using Nethermind.Logging;
using Nethermind.Specs;
using Nethermind.Specs.Forks;
using Nethermind.Evm.State;
using Nethermind.State;
using Nethermind.TxPool;
using NSubstitute;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using Nethermind.Blockchain.Tracing;
using Nethermind.Evm;
namespace Nethermind.Blockchain.Test;
[Parallelizable(ParallelScope.All)]
public class BlockProcessorTests
{
private static (BlockProcessor processor, BranchProcessor branchProcessor, IWorldState stateProvider) CreateProcessorAndBranch(
IRewardCalculator? rewardCalculator = null,
IBlockCachePreWarmer? preWarmer = null)
{
IWorldState stateProvider = TestWorldStateFactory.CreateForTest(parallel: true);
ITransactionProcessor transactionProcessor = Substitute.For<ITransactionProcessor>();
BlockProcessor processor = new(HoodiSpecProvider.Instance,
TestBlockValidator.AlwaysValid,
rewardCalculator ?? NoBlockRewards.Instance,
new BlockProcessor.BlockValidationTransactionsExecutor(
stateProvider,
new ExecuteTransactionProcessorAdapter(transactionProcessor),
new BlobBaseFeeCalculator(),
HoodiSpecProvider.Instance,
Substitute.For<IBlockhashProvider>(),
Substitute.For<ICodeInfoRepository>(),
LimboLogs.Instance),
stateProvider,
NullReceiptStorage.Instance,
new BeaconBlockRootHandler(transactionProcessor, stateProvider),
Substitute.For<IBlockhashStore>(),
LimboLogs.Instance,
new WithdrawalProcessor(stateProvider, LimboLogs.Instance),
new ExecutionRequestsProcessor(transactionProcessor));
BranchProcessor branchProcessor = new(
processor,
HoodiSpecProvider.Instance,
stateProvider,
new BeaconBlockRootHandler(transactionProcessor, stateProvider),
Substitute.For<IBlockhashProvider>(),
LimboLogs.Instance,
preWarmer);
return (processor, branchProcessor, stateProvider);
}
[Test, MaxTime(Timeout.MaxTestTime)]
public async Task Prepared_block_contains_author_field()
{
(_, BranchProcessor branchProcessor, _) = CreateProcessorAndBranch();
BlockHeader header = Build.A.BlockHeader.WithAuthor(TestItem.AddressD).TestObject;
Block block = Build.A.Block.WithHeader(header).TestObject;
Block[] processedBlocks = await branchProcessor.Process(
null,
new List<Block> { block },
ProcessingOptions.None,
NullBlockTracer.Instance);
Assert.That(processedBlocks.Length, Is.EqualTo(1), "length");
Assert.That(processedBlocks[0].Author, Is.EqualTo(block.Author), "author");
}
[Test, MaxTime(Timeout.MaxTestTime)]
public async Task Recovers_state_on_cancel()
{
(_, BranchProcessor branchProcessor, _) = CreateProcessorAndBranch(
rewardCalculator: new RewardCalculator(MainnetSpecProvider.Instance));
BlockHeader header = Build.A.BlockHeader.WithNumber(1).WithAuthor(TestItem.AddressD).TestObject;
Block block = Build.A.Block.WithTransactions(1, MuirGlacier.Instance).WithHeader(header).TestObject;
Assert.ThrowsAsync<OperationCanceledException>(() => branchProcessor.Process(
null,
new List<Block> { block },
ProcessingOptions.None,
AlwaysCancelBlockTracer.Instance));
Assert.ThrowsAsync<OperationCanceledException>(() => branchProcessor.Process(
null,
new List<Block> { block },
ProcessingOptions.None,
AlwaysCancelBlockTracer.Instance));
}
[MaxTime(Timeout.MaxTestTime)]
[TestCase(20)]
[TestCase(63)]
[TestCase(64)]
[TestCase(65)]
[TestCase(127)]
[TestCase(128)]
[TestCase(129)]
[TestCase(130)]
[TestCase(1000)]
[TestCase(2000)]
public async Task Process_long_running_branch(int blocksAmount)
{
Address address = TestItem.Addresses[0];
TestSingleReleaseSpecProvider spec = new(ConstantinopleFix.Instance);
TestRpcBlockchain testRpc = await TestRpcBlockchain.ForTest(SealEngineType.NethDev)
.Build(spec);
testRpc.TestWallet.UnlockAccount(address, new SecureString());
await testRpc.AddFunds(address, 1.Ether);
await testRpc.AddBlock();
SemaphoreSlim suggestedBlockResetEvent = new SemaphoreSlim(0);
testRpc.BlockTree.NewHeadBlock += (_, _) =>
{
suggestedBlockResetEvent.Release(1);
};
int branchLength = blocksAmount + (int)testRpc.BlockTree.BestKnownNumber + 1;
((BlockTree)testRpc.BlockTree).AddBranch(branchLength, (int)testRpc.BlockTree.BestKnownNumber);
(await suggestedBlockResetEvent.WaitAsync(TestBlockchain.DefaultTimeout * 10)).Should().BeTrue();
Assert.That((int)testRpc.BlockTree.BestKnownNumber, Is.EqualTo(branchLength - 1));
}
[Test, MaxTime(Timeout.MaxTestTime)]
public async Task TransactionsExecuted_event_fires_during_ProcessOne()
{
(BlockProcessor processor, _, IWorldState stateProvider) = CreateProcessorAndBranch();
bool eventFired = false;
processor.TransactionsExecuted += () => eventFired = true;
using IDisposable scope = stateProvider.BeginScope(null);
BlockHeader header = Build.A.BlockHeader.WithAuthor(TestItem.AddressD).TestObject;
Block block = Build.A.Block.WithHeader(header).TestObject;
IReleaseSpec spec = HoodiSpecProvider.Instance.GetSpec(block.Header);
await processor.ProcessOne(block, ProcessingOptions.NoValidation, NullBlockTracer.Instance, spec, CancellationToken.None);
eventFired.Should().BeTrue("TransactionsExecuted should fire after ProcessTransactions completes");
}
[Test, MaxTime(Timeout.MaxTestTime)]
public async Task BranchProcessor_cancels_prewarmer_via_TransactionsExecuted_event()
{
TokenCapturingPreWarmer preWarmer = new();
(_, BranchProcessor branchProcessor, _) = CreateProcessorAndBranch(preWarmer: preWarmer);
BlockHeader header = Build.A.BlockHeader.WithAuthor(TestItem.AddressD).TestObject;
Block block = Build.A.Block.WithHeader(header).WithTransactions(3, MuirGlacier.Instance).TestObject;
await branchProcessor.Process(
null,
new List<Block> { block },
ProcessingOptions.NoValidation,
NullBlockTracer.Instance);
preWarmer.CapturedToken.IsCancellationRequested.Should().BeTrue(
"prewarmer CancellationToken should be cancelled via TransactionsExecuted event after tx processing");
}
[Test, MaxTime(Timeout.MaxTestTime)]
public async Task BranchProcessor_unsubscribes_from_TransactionsExecuted_after_processing()
{
(BlockProcessor processor, BranchProcessor branchProcessor, IWorldState stateProvider) = CreateProcessorAndBranch();
BlockHeader header = Build.A.BlockHeader.WithAuthor(TestItem.AddressD).TestObject;
Block block = Build.A.Block.WithHeader(header).TestObject;
await branchProcessor.Process(
null,
new List<Block> { block },
ProcessingOptions.NoValidation,
NullBlockTracer.Instance);
// After Process returns, the event handler should be unsubscribed.
// Verify by checking that firing the event doesn't cause issues
// (if still subscribed, it would try to cancel a disposed CTS).
int externalHandlerCallCount = 0;
processor.TransactionsExecuted += () => externalHandlerCallCount++;
// Process another block to trigger the event — only our handler should fire
using IDisposable scope = stateProvider.BeginScope(null);
Block block2 = Build.A.Block.WithHeader(Build.A.BlockHeader.WithAuthor(TestItem.AddressD).TestObject).TestObject;
IReleaseSpec spec = HoodiSpecProvider.Instance.GetSpec(block2.Header);
await processor.ProcessOne(block2, ProcessingOptions.NoValidation, NullBlockTracer.Instance, spec, CancellationToken.None);
externalHandlerCallCount.Should().Be(1, "only the externally subscribed handler should fire, BranchProcessor should have unsubscribed");
}
[Test, MaxTime(Timeout.MaxTestTime)]
public async Task BranchProcessor_no_prewarmer_still_processes_successfully()
{
(_, BranchProcessor branchProcessor, _) = CreateProcessorAndBranch(preWarmer: null);
BlockHeader header = Build.A.BlockHeader.WithAuthor(TestItem.AddressD).TestObject;
Block block = Build.A.Block.WithHeader(header).WithTransactions(3, MuirGlacier.Instance).TestObject;
Block[] processedBlocks = await branchProcessor.Process(
null,
new List<Block> { block },
ProcessingOptions.NoValidation,
NullBlockTracer.Instance);
processedBlocks.Should().HaveCount(1, "block should process successfully without a prewarmer");
}
[Test]
public void NullBlockProcessor_TransactionsExecuted_subscribe_unsubscribe_is_safe()
{
IBlockProcessor processor = NullBlockProcessor.Instance;
// Should not throw
Action handler = () => { };
processor.TransactionsExecuted += handler;
processor.TransactionsExecuted -= handler;
}
[Test]
public void BlockProductionTransactionPicker_validates_block_length_using_proper_tx_form()
{
IReleaseSpec spec = Osaka.Instance;
ISpecProvider specProvider = new TestSingleReleaseSpecProvider(spec);
Transaction transactionWithNetworkForm = Build.A.Transaction
.WithShardBlobTxTypeAndFields(1, true, spec)
.SignedAndResolved()
.TestObject;
BlockProcessor.BlockProductionTransactionPicker txPicker = new(specProvider, transactionWithNetworkForm.GetLength(true) / 1.KiB - 1);
BlockToProduce newBlock = new(Build.A.BlockHeader.WithExcessBlobGas(0).TestObject);
WorldStateStab stateProvider = new();
using var _ = stateProvider.BeginScope(IWorldState.PreGenesis);
Transaction? addedTransaction = null;
txPicker.AddingTransaction += (s, e) => addedTransaction = e.Transaction;
txPicker.CanAddTransaction(newBlock, transactionWithNetworkForm, new HashSet<Transaction>(), stateProvider);
Assert.That(addedTransaction, Is.EqualTo(transactionWithNetworkForm));
}
/// <summary>
/// Manual IBlockCachePreWarmer that captures the CancellationToken for test verification.
/// NSubstitute cannot proxy ReadOnlySpan<T> (ref struct) parameters.
/// </summary>
private class TokenCapturingPreWarmer : IBlockCachePreWarmer
{
public CancellationToken CapturedToken { get; private set; }
public Task PreWarmCaches(Block suggestedBlock, BlockHeader? parent, IReleaseSpec spec,
CancellationToken cancellationToken = default, params ReadOnlySpan<IHasAccessList> systemAccessLists)
{
CapturedToken = cancellationToken;
return Task.CompletedTask;
}
public CacheType ClearCaches() => default;
}
}