-
Notifications
You must be signed in to change notification settings - Fork 715
Expand file tree
/
Copy pathTransactionProcessorTests.cs
More file actions
743 lines (608 loc) · 33.7 KB
/
Copy pathTransactionProcessorTests.cs
File metadata and controls
743 lines (608 loc) · 33.7 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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
// SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited
// SPDX-License-Identifier: LGPL-3.0-only
using System;
using Nethermind.Core;
using Nethermind.Core.Attributes;
using Nethermind.Core.Eip2930;
using Nethermind.Core.Extensions;
using Nethermind.Core.Specs;
using Nethermind.Specs;
using Nethermind.Core.Test.Builders;
using Nethermind.Crypto;
using Nethermind.Int256;
using Nethermind.Evm.Tracing;
using Nethermind.Blockchain.Tracing.ParityStyle;
using Nethermind.Evm.TransactionProcessing;
using Nethermind.Logging;
using Nethermind.Specs.Forks;
using Nethermind.Evm.State;
using NUnit.Framework;
using Nethermind.Config;
using System.Collections.Generic;
using Nethermind.Blockchain;
using Nethermind.Blockchain.Tracing;
using Nethermind.Core.Test;
namespace Nethermind.Evm.Test;
[TestFixture(true)]
[TestFixture(false)]
[Todo(Improve.Refactor, "Check why fixture test cases did not work")]
[Parallelizable(ParallelScope.All)]
[FixtureLifeCycle(LifeCycle.InstancePerTestCase)]
public partial class TransactionProcessorTests(bool eip155Enabled)
{
private readonly ISpecProvider _specProvider = MainnetSpecProvider.Instance;
private IEthereumEcdsa _ethereumEcdsa;
private ITransactionProcessor _transactionProcessor;
private IWorldState _stateProvider;
private BlockHeader _baseBlock = null!;
private IDisposable _stateCloser;
private static readonly UInt256 AccountBalance = 1.Ether;
[SetUp]
public void Setup()
{
_stateProvider = TestWorldStateFactory.CreateForTest();
_stateCloser = _stateProvider.BeginScope(IWorldState.PreGenesis);
_stateProvider.CreateAccount(TestItem.AddressA, AccountBalance);
_stateProvider.Commit(_specProvider.GenesisSpec);
_stateProvider.CommitTree(0);
_baseBlock = Build.A.BlockHeader.WithStateRoot(_stateProvider.StateRoot).TestObject;
EthereumCodeInfoRepository codeInfoRepository = new(_stateProvider);
EthereumVirtualMachine virtualMachine = new(new TestBlockhashProvider(_specProvider), _specProvider, LimboLogs.Instance);
_transactionProcessor = new EthereumTransactionProcessor(BlobBaseFeeCalculator.Instance, _specProvider, _stateProvider, virtualMachine, codeInfoRepository, LimboLogs.Instance);
_ethereumEcdsa = new EthereumEcdsa(_specProvider.ChainId);
}
[TearDown]
public void Teardown() => _stateCloser.Dispose();
[Test]
public void Can_process_simple_transaction()
{
Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled).WithGasLimit(100000).TestObject;
Block block = Build.A.Block.WithNumber(1).WithTransactions(tx).TestObject;
TransactionResult result = Execute(tx, block);
Assert.That(result.TransactionExecuted, Is.True);
}
[TestCase(true, true)]
[TestCase(true, false)]
[TestCase(false, true)]
[TestCase(false, false)]
public void Sets_state_root_on_receipts_before_eip658(bool withStateDiff, bool withTrace)
{
Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled).WithGasLimit(100000).TestObject;
ulong blockNumber = eip155Enabled
? MainnetSpecProvider.ByzantiumBlockNumber
: MainnetSpecProvider.ByzantiumBlockNumber - 1;
Block block = Build.A.Block.WithNumber(blockNumber).WithTransactions(tx).TestObject;
BlockReceiptsTracer tracer = BuildTracer(tx, withStateDiff, withTrace);
_ = Execute(tx, block, tracer);
if (eip155Enabled) // we use eip155 check just as a proxy on 658
{
Assert.That(tracer.TxReceipts![0].PostTransactionState, Is.Null);
}
else
{
Assert.That(tracer.TxReceipts![0].PostTransactionState, Is.Not.Null);
}
}
[Test]
public void Can_handle_quick_fail_on_intrinsic_gas()
{
Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled).WithGasLimit(20000).TestObject;
Block block = Build.A.Block.WithNumber(1).WithTransactions(tx).TestObject;
TransactionResult result = Execute(tx, block);
Assert.That(result.TransactionExecuted, Is.False);
}
[Test]
public void Can_handle_quick_fail_on_missing_sender()
{
Transaction tx = Build.A.Transaction.Signed(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled).WithGasLimit(100000).TestObject;
Block block = Build.A.Block.WithNumber(1).WithTransactions(tx).TestObject;
TransactionResult result = Execute(tx, block);
Assert.That(result.TransactionExecuted, Is.False);
}
[Test]
public void Can_handle_quick_fail_on_non_existing_sender_account()
{
Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyB, eip155Enabled).WithGasLimit(100000).TestObject;
Block block = Build.A.Block.WithNumber(1).WithTransactions(tx).TestObject;
TransactionResult result = Execute(tx, block);
Assert.That(result.TransactionExecuted, Is.False);
}
[Test]
public void Can_handle_quick_fail_on_invalid_nonce()
{
Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled).WithGasLimit(100000).WithNonce(100).TestObject;
Block block = Build.A.Block.WithNumber(1).WithTransactions(tx).TestObject;
TransactionResult result = Execute(tx, block);
Assert.That(result.TransactionExecuted, Is.False);
}
[Test]
public void Can_handle_quick_fail_on_not_enough_balance_on_intrinsic_gas()
{
AccessList.Builder accessListBuilder = new();
foreach (Address address in TestItem.Addresses)
{
accessListBuilder.AddAddress(address);
}
Transaction tx = Build.A.Transaction
.WithGasLimit(GasCostOf.Transaction * 2)
.WithAccessList(accessListBuilder.Build())
.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled)
.TestObject;
tx.Value = (ulong)(AccountBalance - 3 * GasCostOf.Transaction);
Block block = Build.A.Block.WithNumber(MainnetSpecProvider.BerlinBlockNumber).WithTransactions(tx).TestObject;
TransactionResult result = Execute(tx, block);
Assert.That(result.TransactionExecuted, Is.False);
}
[Test]
public void Can_handle_quick_fail_on_not_enough_balance_on_reserved_gas_payment()
{
Transaction tx = Build.A.Transaction
.WithGasLimit(GasCostOf.Transaction * 2)
.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled)
.TestObject;
tx.Value = AccountBalance - GasCostOf.Transaction;
Block block = Build.A.Block.WithNumber(MainnetSpecProvider.BerlinBlockNumber).WithTransactions(tx).TestObject;
TransactionResult result = Execute(tx, block);
Assert.That(result.TransactionExecuted, Is.False);
}
[Test]
public void Can_handle_quick_fail_when_balance_is_lower_than_fee_cap_times_gas()
{
Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled)
.WithMaxPriorityFeePerGas(5.GWei)
.WithMaxFeePerGas(10.Ether)
.WithType(TxType.EIP1559)
.WithGasLimit(100000).TestObject;
Block block = Build.A.Block.WithNumber(MainnetSpecProvider.LondonBlockNumber).WithTransactions(tx).TestObject;
TransactionResult result = Execute(tx, block);
Assert.That(result.TransactionExecuted, Is.False);
}
[Test]
public void Can_handle_quick_fail_on_above_block_gas_limit()
{
Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled).WithGasLimit(100000).TestObject;
Block block = Build.A.Block.WithNumber(1).WithTransactions(tx).WithGasLimit(20000).TestObject;
TransactionResult result = Execute(tx, block);
Assert.That(result.TransactionExecuted, Is.False);
}
[Test]
public void Balance_is_not_changed_on_call_and_restore()
{
ulong gasLimit = 100000ul;
Transaction tx = Build.A.Transaction
.WithValue(AccountBalance - (UInt256)gasLimit)
.WithGasPrice(1)
.WithGasLimit(gasLimit)
.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled).TestObject;
Block block = Build.A.Block.WithNumber(1ul).WithTransactions(tx).WithGasLimit(gasLimit).TestObject;
_transactionProcessor.CallAndRestore(tx, new BlockExecutionContext(block.Header, _specProvider.GetSpec(block.Header)), NullTxTracer.Instance);
Assert.That(_stateProvider.GetBalance(TestItem.PrivateKeyA.Address), Is.EqualTo(1.Ether));
}
[Test]
public void Account_is_not_created_on_call_and_restore()
{
ulong gasLimit = 100000ul;
Transaction tx = Build.A.Transaction
.WithValue(0.Ether)
.WithGasPrice(1)
.WithGasLimit(gasLimit)
.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyD, eip155Enabled)
.TestObject;
Block block = Build.A.Block.WithNumber(1ul).WithTransactions(tx).WithGasLimit(gasLimit).TestObject;
Assert.That(_stateProvider.AccountExists(TestItem.PrivateKeyD.Address), Is.False);
_transactionProcessor.CallAndRestore(tx, new BlockExecutionContext(block.Header, _specProvider.GetSpec(block.Header)), NullTxTracer.Instance);
Assert.That(_stateProvider.AccountExists(TestItem.PrivateKeyD.Address), Is.False);
}
[Test]
public void Nonce_is_not_changed_on_call_and_restore()
{
ulong gasLimit = 100000ul;
Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled).WithValue(1.Ether - (UInt256)gasLimit).WithGasPrice(1).WithGasLimit(gasLimit).TestObject;
Block block = Build.A.Block.WithNumber(1ul).WithTransactions(tx).WithGasLimit(gasLimit).TestObject;
_transactionProcessor.CallAndRestore(tx, new BlockExecutionContext(block.Header, _specProvider.GetSpec(block.Header)), NullTxTracer.Instance);
Assert.That(_stateProvider.GetNonce(TestItem.PrivateKeyA.Address), Is.EqualTo(0ul));
}
[TestCase(true)]
[TestCase(false)]
public void Can_estimate_with_value(bool systemUser)
{
ulong gasLimit = 100000ul;
Transaction tx = Build.A.Transaction.WithValue(ulong.MaxValue).WithGasLimit(gasLimit)
.WithSenderAddress(systemUser ? Address.SystemUser : TestItem.AddressA).TestObject;
Block block = Build.A.Block.WithParent(_baseBlock).WithTransactions(tx).WithGasLimit(gasLimit).TestObject;
EstimateGasTracer tracer = new();
TransactionResult result = _transactionProcessor.CallAndRestore(tx, new BlockExecutionContext(block.Header, _specProvider.GetSpec(block.Header)), tracer);
if (!systemUser)
{
Assert.That(result, Is.EqualTo(TransactionResult.InsufficientMaxFeePerGasForSenderBalance));
}
else
{
Assert.That(tracer.GasSpent, Is.EqualTo(21000ul));
}
}
[TestCaseSource(nameof(EstimateWithHighTxValueTestCases))]
public ulong Should_not_estimate_tx_with_high_value(UInt256 txValue)
{
ulong gasLimit = 100000ul;
Transaction tx = Build.A.Transaction
.WithValue(txValue)
.WithGasPrice(0)
.WithGasLimit(gasLimit)
.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled)
.TestObject;
Block block = Build.A.Block.WithNumber(1ul).WithTransactions(tx).WithGasLimit(gasLimit).TestObject;
EstimateGasTracer tracer = new();
BlocksConfig blocksConfig = new();
GasEstimator estimator = new(_transactionProcessor, _stateProvider, _specProvider, blocksConfig);
ulong estimate = estimator.Estimate(tx, block.Header, tracer, out string? err, 0);
if (txValue == AccountBalance)
{
// Gas price is zero so no gas payment is needed; sending the full balance as value is valid.
Assert.That(err, Is.Null);
Assert.That(estimate, Is.EqualTo(GasCostOf.Transaction));
}
else if (txValue + (UInt256)gasLimit > AccountBalance)
{
Assert.That(err, Is.Not.Null); // Should have error
Assert.That(err, Is.EqualTo(GasEstimator.InsufficientBalance));
}
else
{
Assert.That(err, Is.Null); // Should succeed
}
return estimate;
}
public static IEnumerable<TestCaseData> EstimateWithHighTxValueTestCases
{
get
{
UInt256 gasLimit = 100000;
yield return new TestCaseData((UInt256)1)
{ TestName = "Sanity check", ExpectedResult = GasCostOf.Transaction };
yield return new TestCaseData(AccountBalance - 1 - gasLimit)
{ TestName = "Less than account balance", ExpectedResult = GasCostOf.Transaction };
yield return new TestCaseData(AccountBalance - GasCostOf.Transaction - gasLimit)
{ TestName = "Account balance - tx cost", ExpectedResult = GasCostOf.Transaction };
yield return new TestCaseData(AccountBalance - GasCostOf.Transaction - gasLimit + 1)
{ TestName = "More than (account balance - tx cost)", ExpectedResult = GasCostOf.Transaction };
yield return new TestCaseData(AccountBalance)
{ TestName = "Exactly account balance", ExpectedResult = GasCostOf.Transaction };
yield return new TestCaseData(AccountBalance + 1)
{ TestName = "More than account balance", ExpectedResult = 0ul };
yield return new TestCaseData((UInt256)ulong.MaxValue - gasLimit)
{ TestName = "Max value possible", ExpectedResult = 0ul };
}
}
[TestCase(562949953421312ul)]
[TestCase(562949953421311ul)]
public void Should_reject_tx_with_high_max_fee_per_gas(ulong topDigit)
{
Transaction tx = Build.A.Transaction.WithMaxFeePerGas(new(0, 0, 0, topDigit)).WithGasLimit(32768)
.WithType(TxType.EIP1559).WithValue(0)
.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled)
.TestObject;
ulong blockNumber = MainnetSpecProvider.LondonBlockNumber;
Block block = Build.A.Block.WithNumber(blockNumber).WithTransactions(tx).TestObject;
TransactionResult result = Execute(tx, block);
Assert.That(result.TransactionExecuted, Is.False);
}
[TestCase]
public void Can_estimate_simple()
{
ulong gasLimit = 100000ul;
Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled).WithGasLimit(gasLimit).TestObject;
Block block = Build.A.Block.WithParent(_baseBlock).WithTransactions(tx).WithGasLimit(gasLimit).TestObject;
EstimateGasTracer tracer = new();
BlocksConfig blocksConfig = new();
GasEstimator estimator = new(_transactionProcessor, _stateProvider, _specProvider, blocksConfig);
_transactionProcessor.CallAndRestore(tx, new BlockExecutionContext(block.Header, _specProvider.GetSpec(block.Header)), tracer);
Assert.That(tracer.GasSpent, Is.EqualTo(21000ul));
Assert.That(estimator.Estimate(tx, block.Header, tracer, out string? err, 0), Is.EqualTo(21000ul));
Assert.That(err, Is.Null);
}
[TestCase]
public void Can_estimate_with_refund()
{
byte[] initByteCode = Prepare.EvmCode
.PushData(1)
.PushData(1)
.Op(Instruction.SSTORE)
.PushData(0)
.PushData(1)
.Op(Instruction.SSTORE)
.Op(Instruction.STOP)
.Done;
ulong gasLimit = 100000ul;
Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled).WithCode(initByteCode).WithGasLimit(gasLimit).TestObject;
Block block = Build.A.Block.WithNumber(MainnetSpecProvider.MuirGlacierBlockNumber).WithTransactions(tx).WithGasLimit(2ul * gasLimit).TestObject;
EthereumIntrinsicGas intrinsicGas = IntrinsicGasCalculator.Calculate(tx, MuirGlacier.Instance);
BlockExecutionContext blkCtx = new(block.Header, _specProvider.GetSpec(block.Header));
EstimateGasTracer tracer = new();
_transactionProcessor.CallAndRestore(tx, blkCtx, tracer);
BlocksConfig blocksConfig = new();
GasEstimator estimator = new(_transactionProcessor, _stateProvider, _specProvider, blocksConfig);
ulong actualIntrinsic = tx.GasLimit - tracer.IntrinsicGasAt;
Assert.That(actualIntrinsic, Is.EqualTo(intrinsicGas.Standard));
IReleaseSpec releaseSpec = Berlin.Instance;
Assert.That(tracer.CalculateAdditionalGasRequired(tx, releaseSpec), Is.EqualTo((ulong)RefundOf.SSetReversedEip2200 + GasCostOf.CallStipend - GasCostOf.SStoreNetMeteredEip2200 + 1ul));
Assert.That(tracer.GasSpent, Is.EqualTo(54764ul));
ulong estimate = estimator.Estimate(tx, block.Header, tracer, out string? err, 0);
Assert.That(estimate, Is.EqualTo(75465ul));
Assert.That(err, Is.Null);
ConfirmEnoughEstimate(tx, block, estimate);
}
[Test(Description = "Since the second call is a CREATE operation it has intrinsic gas of 21000 + 32000 + data")]
public void Can_estimate_with_destroy_refund_and_below_intrinsic_pre_berlin()
{
byte[] initByteCode = Prepare.EvmCode.ForInitOf(Prepare.EvmCode.PushData(Address.Zero).Op(Instruction.SELFDESTRUCT).Done).Done;
Address contractAddress = ContractAddress.From(TestItem.PrivateKeyA.Address, 0);
byte[] byteCode = Prepare.EvmCode
.Call(contractAddress, 46179)
.Op(Instruction.STOP).Done;
ulong gasLimit = 100000ul;
Transaction initTx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled).WithCode(initByteCode).WithGasLimit(gasLimit).TestObject;
Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled).WithCode(byteCode).WithGasLimit(gasLimit).WithNonce(1ul).TestObject;
Block block = Build.A.Block.WithNumber(MainnetSpecProvider.MuirGlacierBlockNumber).WithTransactions(tx).WithGasLimit(2ul * gasLimit).TestObject;
IReleaseSpec releaseSpec = MuirGlacier.Instance;
EthereumIntrinsicGas intrinsicGas = IntrinsicGasCalculator.Calculate(tx, releaseSpec);
BlockExecutionContext blkCtx = new(block.Header, releaseSpec);
TransactionResult initResult = _transactionProcessor.Execute(initTx, blkCtx, NullTxTracer.Instance);
EstimateGasTracer tracer = new();
_transactionProcessor.CallAndRestore(tx, blkCtx, tracer);
BlocksConfig blocksConfig = new();
GasEstimator estimator = new(_transactionProcessor, _stateProvider, _specProvider, blocksConfig);
ulong actualIntrinsic = tx.GasLimit - tracer.IntrinsicGasAt;
Assert.That(actualIntrinsic, Is.EqualTo(intrinsicGas.Standard));
Assert.That(tracer.CalculateAdditionalGasRequired(tx, releaseSpec), Is.EqualTo(24080ul));
ulong estimate = estimator.Estimate(tx, block.Header, tracer, out string? err, 0);
Assert.That(tracer.GasSpent, Is.EqualTo(54224ul));
Assert.That(estimate, Is.EqualTo(54225ul));
Assert.That(err, Is.Null);
ConfirmEnoughEstimate(tx, block, estimate);
}
private void ConfirmEnoughEstimate(Transaction tx, Block block, ulong estimate)
{
BlockExecutionContext blkCtx = new(block.Header, _specProvider.GetSpec(block.Header));
CallOutputTracer outputTracer = new();
tx.GasLimit = estimate;
_transactionProcessor.CallAndRestore(tx, blkCtx, outputTracer);
Assert.That(outputTracer.StatusCode, Is.EqualTo(StatusCode.Success), $"transaction should succeed at the estimate ({estimate})");
outputTracer = new CallOutputTracer();
tx.GasLimit = Math.Min(estimate - 1, estimate * 63 / 64);
_transactionProcessor.CallAndRestore(tx, blkCtx, outputTracer);
Assert.That(outputTracer.StatusCode, Is.EqualTo(StatusCode.Failure), $"transaction should fail below the estimate ({tx.GasLimit})");
}
[TestCase]
public void Can_estimate_with_stipend()
{
byte[] initByteCode = Prepare.EvmCode
.CallWithValue(Address.Zero, 0, 1)
.Op(Instruction.STOP)
.Done;
ulong gasLimit = 100000ul;
Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled).WithCode(initByteCode).WithGasLimit(gasLimit).TestObject;
Block block = Build.A.Block.WithNumber(MainnetSpecProvider.MuirGlacierBlockNumber).WithTransactions(tx).WithGasLimit(2ul * gasLimit).TestObject;
IReleaseSpec releaseSpec = MuirGlacier.Instance;
EthereumIntrinsicGas intrinsicGas = IntrinsicGasCalculator.Calculate(tx, releaseSpec);
BlockExecutionContext blkCtx = new(block.Header, releaseSpec);
EstimateGasTracer tracer = new();
_transactionProcessor.CallAndRestore(tx, blkCtx, tracer);
BlocksConfig blocksConfig = new();
GasEstimator estimator = new(_transactionProcessor, _stateProvider, _specProvider, blocksConfig);
ulong actualIntrinsic = tx.GasLimit - tracer.IntrinsicGasAt;
Assert.That(actualIntrinsic, Is.EqualTo(intrinsicGas.Standard));
Assert.That(tracer.CalculateAdditionalGasRequired(tx, releaseSpec), Is.EqualTo(2300ul));
Assert.That(tracer.GasSpent, Is.EqualTo(85669ul));
ulong estimate = estimator.Estimate(tx, block.Header, tracer, out string? err, 0);
Assert.That(estimate, Is.EqualTo(87969ul));
Assert.That(err, Is.Null);
ConfirmEnoughEstimate(tx, block, estimate);
}
[TestCase]
public void Can_estimate_with_stipend_and_refund()
{
byte[] initByteCode = Prepare.EvmCode
.CallWithValue(Address.Zero, 0, 1)
.PushData(1)
.PushData(1)
.Op(Instruction.SSTORE)
.PushData(0)
.PushData(1)
.Op(Instruction.SSTORE)
.Op(Instruction.STOP)
.Done;
ulong gasLimit = 200000ul;
Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled).WithCode(initByteCode).WithGasLimit(gasLimit).TestObject;
Block block = Build.A.Block.WithNumber(MainnetSpecProvider.MuirGlacierBlockNumber).WithTransactions(tx).WithGasLimit(2ul * gasLimit).TestObject;
IReleaseSpec releaseSpec = _specProvider.GetSpec(block.Header);
EthereumIntrinsicGas intrinsicGas = IntrinsicGasCalculator.Calculate(tx, releaseSpec);
BlockExecutionContext blkCtx = new(block.Header, releaseSpec);
EstimateGasTracer tracer = new();
_transactionProcessor.CallAndRestore(tx, blkCtx, tracer);
BlocksConfig blocksConfig = new();
GasEstimator estimator = new(_transactionProcessor, _stateProvider, _specProvider, blocksConfig);
ulong actualIntrinsic = tx.GasLimit - tracer.IntrinsicGasAt;
Assert.That(actualIntrinsic, Is.EqualTo(intrinsicGas.Standard));
Assert.That(tracer.CalculateAdditionalGasRequired(tx, releaseSpec), Is.EqualTo((ulong)RefundOf.SSetReversedEip2200 + GasCostOf.CallStipend));
ulong estimate = estimator.Estimate(tx, block.Header, tracer, out string? err, 0);
Assert.That(tracer.GasSpent, Is.EqualTo(87429ul));
Assert.That(estimate, Is.EqualTo(108130ul));
Assert.That(err, Is.Null);
ConfirmEnoughEstimate(tx, block, estimate);
}
[TestCase]
public void Can_estimate_with_single_call()
{
byte[] initByteCode = Prepare.EvmCode
.ForInitOf(Bytes.FromHexString("6000")).Done;
Address contractAddress = ContractAddress.From(TestItem.PrivateKeyA.Address, 0);
byte[] byteCode = Prepare.EvmCode
.Call(contractAddress, 46179).Done;
ulong gasLimit = 100000ul;
Transaction initTx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled).WithCode(initByteCode).WithGasLimit(gasLimit).TestObject;
Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled).WithCode(byteCode).WithGasLimit(gasLimit).WithNonce(1ul).TestObject;
Block block = Build.A.Block.WithNumber(MainnetSpecProvider.MuirGlacierBlockNumber).WithTransactions(tx).WithGasLimit(2ul * gasLimit).TestObject;
IReleaseSpec releaseSpec = _specProvider.GetSpec(block.Header);
EthereumIntrinsicGas intrinsicGas = IntrinsicGasCalculator.Calculate(tx, releaseSpec);
BlockExecutionContext blkCtx = new(block.Header, releaseSpec);
_transactionProcessor.Execute(initTx, blkCtx, NullTxTracer.Instance);
EstimateGasTracer tracer = new();
_transactionProcessor.CallAndRestore(tx, blkCtx, tracer);
BlocksConfig blocksConfig = new();
GasEstimator estimator = new(_transactionProcessor, _stateProvider, _specProvider, blocksConfig);
ulong actualIntrinsic = tx.GasLimit - tracer.IntrinsicGasAt;
Assert.That(actualIntrinsic, Is.EqualTo(intrinsicGas.Standard));
Assert.That(tracer.CalculateAdditionalGasRequired(tx, releaseSpec), Is.EqualTo(1ul));
ulong estimate = estimator.Estimate(tx, block.Header, tracer, out string? err, 0);
Assert.That(tracer.GasSpent, Is.EqualTo(54224ul));
Assert.That(estimate, Is.EqualTo(54224ul));
Assert.That(err, Is.Null);
ConfirmEnoughEstimate(tx, block, estimate);
}
[TestCase]
public void Disables_Eip158_for_system_transactions()
{
ulong blockNumber = MainnetSpecProvider.SpuriousDragonBlockNumber + 1;
_stateProvider.CreateAccount(TestItem.PrivateKeyA.Address, 0.Ether);
IReleaseSpec spec = _specProvider.GetSpec((ForkActivation)blockNumber);
_stateProvider.Commit(spec);
Transaction tx = Build.A.SystemTransaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled)
.WithGasPrice(0)
.WithValue(0)
.TestObject;
Block block = Build.A.Block.WithNumber(blockNumber).WithTransactions(tx).TestObject;
BlockReceiptsTracer tracer = BuildTracer(tx, false, false);
Execute(tx, block, tracer);
Assert.That(_stateProvider.AccountExists(tx.SenderAddress!), Is.True);
}
[TestCase]
public void Balance_is_changed_on_buildup_and_restored()
{
ulong gasLimit = 100000ul;
Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled).WithValue(0).WithGasPrice(1).WithGasLimit(gasLimit).TestObject;
Block block = Build.A.Block.WithNumber(MainnetSpecProvider.ByzantiumBlockNumber).WithTransactions(tx).WithGasLimit(gasLimit).TestObject;
Snapshot state = _stateProvider.TakeSnapshot();
_transactionProcessor.BuildUp(tx, new BlockExecutionContext(block.Header, _specProvider.GetSpec(block.Header)), NullTxTracer.Instance);
Assert.That(_stateProvider.GetBalance(TestItem.PrivateKeyA.Address), Is.EqualTo(AccountBalance - GasCostOf.Transaction));
_stateProvider.Restore(state);
Assert.That(_stateProvider.GetBalance(TestItem.PrivateKeyA.Address), Is.EqualTo(AccountBalance));
}
[TestCase]
public void Account_is_not_created_on_buildup_and_restore()
{
ulong gasLimit = 100000ul;
Transaction tx = Build.A.Transaction
.WithValue(0.Ether)
.WithGasPrice(1)
.WithGasLimit(gasLimit)
.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyD, eip155Enabled)
.TestObject;
Block block = Build.A.Block.WithNumber(MainnetSpecProvider.ByzantiumBlockNumber).WithTransactions(tx).WithGasLimit(gasLimit).TestObject;
Assert.That(_stateProvider.AccountExists(TestItem.PrivateKeyD.Address), Is.False);
Snapshot state = _stateProvider.TakeSnapshot();
_transactionProcessor.BuildUp(tx, new BlockExecutionContext(block.Header, _specProvider.GetSpec(block.Header)), NullTxTracer.Instance);
Assert.That(_stateProvider.AccountExists(TestItem.PrivateKeyD.Address), Is.True);
_stateProvider.Restore(state);
Assert.That(_stateProvider.AccountExists(TestItem.PrivateKeyD.Address), Is.False);
}
[TestCase]
public void Nonce_is_not_changed_on_buildup_and_restore()
{
ulong gasLimit = 100000ul;
Transaction tx = Build.A.Transaction
.WithValue(AccountBalance - (UInt256)gasLimit)
.WithGasPrice(1)
.WithGasLimit(gasLimit)
.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled)
.TestObject;
Block block = Build.A.Block.WithNumber(MainnetSpecProvider.ByzantiumBlockNumber).WithTransactions(tx).WithGasLimit(gasLimit).TestObject;
Snapshot state = _stateProvider.TakeSnapshot();
_transactionProcessor.BuildUp(tx, new BlockExecutionContext(block.Header, _specProvider.GetSpec(block.Header)), NullTxTracer.Instance);
Assert.That(_stateProvider.GetNonce(TestItem.PrivateKeyA.Address), Is.EqualTo(1ul));
_stateProvider.Restore(state);
Assert.That(_stateProvider.GetNonce(TestItem.PrivateKeyA.Address), Is.EqualTo(0ul));
}
[TestCase]
public void State_changed_twice_in_buildup_should_have_correct_gas_cost()
{
ulong gasLimit = 100000ul;
Transaction tx1 = Build.A.Transaction
.WithValue(0).WithGasPrice(1).WithGasLimit(GasCostOf.Transaction)
.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled)
.TestObject;
Transaction tx2 = Build.A.Transaction
.WithValue(0).WithNonce(1ul).WithGasPrice(1).WithGasLimit(GasCostOf.Transaction)
.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled)
.TestObject;
Block block = Build.A.Block.WithNumber(MainnetSpecProvider.ByzantiumBlockNumber).WithTransactions(tx1, tx2).WithGasLimit(gasLimit).TestObject;
Snapshot state = _stateProvider.TakeSnapshot();
BlockExecutionContext blkCtx = new(block.Header, _specProvider.GetSpec(block.Header));
_transactionProcessor.BuildUp(tx1, blkCtx, NullTxTracer.Instance);
Assert.That(_stateProvider.GetBalance(TestItem.PrivateKeyA.Address), Is.EqualTo(AccountBalance - GasCostOf.Transaction));
_transactionProcessor.BuildUp(tx2, blkCtx, NullTxTracer.Instance);
Assert.That(_stateProvider.GetBalance(TestItem.PrivateKeyA.Address), Is.EqualTo(AccountBalance - GasCostOf.Transaction * 2));
_stateProvider.Restore(state);
Assert.That(_stateProvider.GetBalance(TestItem.PrivateKeyA.Address), Is.EqualTo(AccountBalance));
}
private BlockReceiptsTracer BuildTracer(Transaction tx, bool stateDiff, bool trace)
{
ParityTraceTypes types = ParityTraceTypes.None;
if (stateDiff)
{
types |= ParityTraceTypes.StateDiff;
}
if (trace)
{
types |= ParityTraceTypes.Trace;
}
IBlockTracer otherTracer = types != ParityTraceTypes.None ? new ParityLikeBlockTracer(tx.Hash!, ParityTraceTypes.Trace | ParityTraceTypes.StateDiff) : NullBlockTracer.Instance;
BlockReceiptsTracer tracer = new();
tracer.SetOtherTracer(otherTracer);
return tracer;
}
private TransactionResult Execute(Transaction tx, Block block, BlockReceiptsTracer? tracer = null)
{
tracer?.StartNewBlockTrace(block);
tracer?.StartNewTxTrace(tx);
TransactionResult result = _transactionProcessor.Execute(tx, new BlockExecutionContext(block.Header, _specProvider.GetSpec(block.Header)), tracer ?? NullTxTracer.Instance);
if (result)
{
tracer?.EndTxTrace();
tracer?.EndBlockTrace();
}
return result;
}
[Test]
public void Warmup_does_not_update_SpentGas()
{
Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled)
.WithGasLimit(100000).TestObject;
Block block = Build.A.Block.WithNumber(1).WithTransactions(tx).TestObject;
// Use a sentinel value because the SpentGas getter returns GasLimit when _spentGas is 0
const long sentinel = 42;
tx.SpentGas = sentinel;
_transactionProcessor.Warmup(tx, new BlockExecutionContext(block.Header, _specProvider.GetSpec(block.Header)), NullTxTracer.Instance);
Assert.That(tx.SpentGas, Is.EqualTo(sentinel), "Warmup must not modify tx.SpentGas");
}
[Test]
public void Warmup_does_not_modify_sender_nonce()
{
Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled)
.WithGasLimit(100000).TestObject;
Block block = Build.A.Block.WithNumber(1).WithTransactions(tx).TestObject;
ulong nonceBefore = _stateProvider.GetNonce(TestItem.AddressA);
_transactionProcessor.Warmup(tx, new BlockExecutionContext(block.Header, _specProvider.GetSpec(block.Header)), NullTxTracer.Instance);
Assert.That(_stateProvider.GetNonce(TestItem.AddressA), Is.EqualTo(nonceBefore), "Warmup must not increment sender nonce");
}
[Test]
public void Warmup_does_not_deduct_sender_balance()
{
Transaction tx = Build.A.Transaction.SignedAndResolved(_ethereumEcdsa, TestItem.PrivateKeyA, eip155Enabled)
.WithGasLimit(100000).TestObject;
Block block = Build.A.Block.WithNumber(1).WithTransactions(tx).TestObject;
UInt256 balanceBefore = _stateProvider.GetBalance(TestItem.AddressA);
_transactionProcessor.Warmup(tx, new BlockExecutionContext(block.Header, _specProvider.GetSpec(block.Header)), NullTxTracer.Instance);
Assert.That(_stateProvider.GetBalance(TestItem.AddressA), Is.EqualTo(balanceBefore), "Warmup must not deduct sender balance (should use SystemTransactionProcessor path)");
}
}