/
AbstractBlockProcessor.java
255 lines (220 loc) · 10.3 KB
/
AbstractBlockProcessor.java
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
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.ethereum.mainnet;
import static org.hyperledger.besu.ethereum.mainnet.feemarket.ExcessBlobGasCalculator.calculateExcessBlobGasForParent;
import static org.hyperledger.besu.evm.operation.BlockHashOperation.BlockHashLookup;
import org.hyperledger.besu.datatypes.Address;
import org.hyperledger.besu.datatypes.TransactionType;
import org.hyperledger.besu.datatypes.Wei;
import org.hyperledger.besu.ethereum.BlockProcessingOutputs;
import org.hyperledger.besu.ethereum.BlockProcessingResult;
import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.MutableWorldState;
import org.hyperledger.besu.ethereum.core.Request;
import org.hyperledger.besu.ethereum.core.Transaction;
import org.hyperledger.besu.ethereum.core.TransactionReceipt;
import org.hyperledger.besu.ethereum.core.Withdrawal;
import org.hyperledger.besu.ethereum.mainnet.requests.RequestProcessorCoordinator;
import org.hyperledger.besu.ethereum.privacy.storage.PrivateMetadataUpdater;
import org.hyperledger.besu.ethereum.processing.TransactionProcessingResult;
import org.hyperledger.besu.ethereum.trie.MerkleTrieException;
import org.hyperledger.besu.ethereum.trie.diffbased.common.worldview.DiffBasedWorldState;
import org.hyperledger.besu.ethereum.trie.diffbased.common.worldview.accumulator.DiffBasedWorldStateUpdateAccumulator;
import org.hyperledger.besu.ethereum.vm.CachingBlockHashLookup;
import org.hyperledger.besu.evm.gascalculator.CancunGasCalculator;
import org.hyperledger.besu.evm.tracing.OperationTracer;
import org.hyperledger.besu.evm.worldstate.WorldState;
import org.hyperledger.besu.evm.worldstate.WorldUpdater;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractBlockProcessor implements BlockProcessor {
@FunctionalInterface
public interface TransactionReceiptFactory {
TransactionReceipt create(
TransactionType transactionType,
TransactionProcessingResult result,
WorldState worldState,
long gasUsed);
}
private static final Logger LOG = LoggerFactory.getLogger(AbstractBlockProcessor.class);
static final int MAX_GENERATION = 6;
protected final MainnetTransactionProcessor transactionProcessor;
protected final AbstractBlockProcessor.TransactionReceiptFactory transactionReceiptFactory;
final Wei blockReward;
protected final boolean skipZeroBlockRewards;
private final ProtocolSchedule protocolSchedule;
protected final MiningBeneficiaryCalculator miningBeneficiaryCalculator;
protected AbstractBlockProcessor(
final MainnetTransactionProcessor transactionProcessor,
final TransactionReceiptFactory transactionReceiptFactory,
final Wei blockReward,
final MiningBeneficiaryCalculator miningBeneficiaryCalculator,
final boolean skipZeroBlockRewards,
final ProtocolSchedule protocolSchedule) {
this.transactionProcessor = transactionProcessor;
this.transactionReceiptFactory = transactionReceiptFactory;
this.blockReward = blockReward;
this.miningBeneficiaryCalculator = miningBeneficiaryCalculator;
this.skipZeroBlockRewards = skipZeroBlockRewards;
this.protocolSchedule = protocolSchedule;
}
@Override
public BlockProcessingResult processBlock(
final Blockchain blockchain,
final MutableWorldState worldState,
final BlockHeader blockHeader,
final List<Transaction> transactions,
final List<BlockHeader> ommers,
final Optional<List<Withdrawal>> maybeWithdrawals,
final PrivateMetadataUpdater privateMetadataUpdater) {
final List<TransactionReceipt> receipts = new ArrayList<>();
long currentGasUsed = 0;
long currentBlobGasUsed = 0;
final ProtocolSpec protocolSpec = protocolSchedule.getByBlockHeader(blockHeader);
protocolSpec.getBlockHashProcessor().processBlockHashes(blockchain, worldState, blockHeader);
for (final Transaction transaction : transactions) {
if (!hasAvailableBlockBudget(blockHeader, transaction, currentGasUsed)) {
return new BlockProcessingResult(Optional.empty(), "provided gas insufficient");
}
final WorldUpdater worldStateUpdater = worldState.updater();
final BlockHashLookup blockHashLookup = new CachingBlockHashLookup(blockHeader, blockchain);
final Address miningBeneficiary =
miningBeneficiaryCalculator.calculateBeneficiary(blockHeader);
Optional<BlockHeader> maybeParentHeader =
blockchain.getBlockHeader(blockHeader.getParentHash());
Wei blobGasPrice =
maybeParentHeader
.map(
parentHeader ->
protocolSpec
.getFeeMarket()
.blobGasPricePerGas(
calculateExcessBlobGasForParent(protocolSpec, parentHeader)))
.orElse(Wei.ZERO);
final TransactionProcessingResult result =
transactionProcessor.processTransaction(
worldStateUpdater,
blockHeader,
transaction,
miningBeneficiary,
OperationTracer.NO_TRACING,
blockHashLookup,
true,
TransactionValidationParams.processingBlock(),
privateMetadataUpdater,
blobGasPrice);
if (result.isInvalid()) {
String errorMessage =
MessageFormat.format(
"Block processing error: transaction invalid {0}. Block {1} Transaction {2}",
result.getValidationResult().getErrorMessage(),
blockHeader.getHash().toHexString(),
transaction.getHash().toHexString());
LOG.info(errorMessage);
if (worldState instanceof DiffBasedWorldState) {
((DiffBasedWorldStateUpdateAccumulator<?>) worldStateUpdater).reset();
}
return new BlockProcessingResult(Optional.empty(), errorMessage);
}
worldStateUpdater.commit();
currentGasUsed += transaction.getGasLimit() - result.getGasRemaining();
if (transaction.getVersionedHashes().isPresent()) {
currentBlobGasUsed +=
(transaction.getVersionedHashes().get().size() * CancunGasCalculator.BLOB_GAS_PER_BLOB);
}
final TransactionReceipt transactionReceipt =
transactionReceiptFactory.create(
transaction.getType(), result, worldState, currentGasUsed);
receipts.add(transactionReceipt);
}
if (blockHeader.getBlobGasUsed().isPresent()
&& currentBlobGasUsed != blockHeader.getBlobGasUsed().get()) {
String errorMessage =
String.format(
"block did not consume expected blob gas: header %d, transactions %d",
blockHeader.getBlobGasUsed().get(), currentBlobGasUsed);
LOG.error(errorMessage);
return new BlockProcessingResult(Optional.empty(), errorMessage);
}
final Optional<WithdrawalsProcessor> maybeWithdrawalsProcessor =
protocolSpec.getWithdrawalsProcessor();
if (maybeWithdrawalsProcessor.isPresent() && maybeWithdrawals.isPresent()) {
try {
maybeWithdrawalsProcessor
.get()
.processWithdrawals(maybeWithdrawals.get(), worldState.updater());
} catch (final Exception e) {
LOG.error("failed processing withdrawals", e);
return new BlockProcessingResult(Optional.empty(), e);
}
}
// EIP-7685: process EL requests
final Optional<RequestProcessorCoordinator> requestProcessor =
protocolSpec.getRequestProcessorCoordinator();
Optional<List<Request>> maybeRequests = Optional.empty();
if (requestProcessor.isPresent()) {
maybeRequests = requestProcessor.get().process(worldState, receipts);
}
if (!rewardCoinbase(worldState, blockHeader, ommers, skipZeroBlockRewards)) {
// no need to log, rewardCoinbase logs the error.
if (worldState instanceof DiffBasedWorldState) {
((DiffBasedWorldStateUpdateAccumulator<?>) worldState.updater()).reset();
}
return new BlockProcessingResult(Optional.empty(), "ommer too old");
}
try {
worldState.persist(blockHeader);
} catch (MerkleTrieException e) {
LOG.trace("Merkle trie exception during Transaction processing ", e);
if (worldState instanceof DiffBasedWorldState) {
((DiffBasedWorldStateUpdateAccumulator<?>) worldState.updater()).reset();
}
throw e;
} catch (Exception e) {
LOG.error("failed persisting block", e);
return new BlockProcessingResult(Optional.empty(), e);
}
return new BlockProcessingResult(
Optional.of(new BlockProcessingOutputs(worldState, receipts, maybeRequests)));
}
protected boolean hasAvailableBlockBudget(
final BlockHeader blockHeader, final Transaction transaction, final long currentGasUsed) {
final long remainingGasBudget = blockHeader.getGasLimit() - currentGasUsed;
if (Long.compareUnsigned(transaction.getGasLimit(), remainingGasBudget) > 0) {
LOG.info(
"Block processing error: transaction gas limit {} exceeds available block budget"
+ " remaining {}. Block {} Transaction {}",
transaction.getGasLimit(),
remainingGasBudget,
blockHeader.getHash().toHexString(),
transaction.getHash().toHexString());
return false;
}
return true;
}
protected MiningBeneficiaryCalculator getMiningBeneficiaryCalculator() {
return miningBeneficiaryCalculator;
}
abstract boolean rewardCoinbase(
final MutableWorldState worldState,
final BlockHeader header,
final List<BlockHeader> ommers,
final boolean skipZeroBlockRewards);
}