forked from hyperledger/besu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainnetTransactionValidator.java
429 lines (368 loc) · 16.8 KB
/
MainnetTransactionValidator.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
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
/*
* Copyright Hyperledger Besu Contributors.
*
* 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.evm.account.Account.MAX_NONCE;
import org.hyperledger.besu.config.GenesisConfigOptions;
import org.hyperledger.besu.crypto.SECPSignature;
import org.hyperledger.besu.crypto.SignatureAlgorithmFactory;
import org.hyperledger.besu.datatypes.Blob;
import org.hyperledger.besu.datatypes.BlobsWithCommitments;
import org.hyperledger.besu.datatypes.Hash;
import org.hyperledger.besu.datatypes.KZGCommitment;
import org.hyperledger.besu.datatypes.TransactionType;
import org.hyperledger.besu.datatypes.VersionedHash;
import org.hyperledger.besu.datatypes.Wei;
import org.hyperledger.besu.ethereum.GasLimitCalculator;
import org.hyperledger.besu.ethereum.core.Transaction;
import org.hyperledger.besu.ethereum.mainnet.feemarket.FeeMarket;
import org.hyperledger.besu.ethereum.transaction.TransactionInvalidReason;
import org.hyperledger.besu.evm.account.Account;
import org.hyperledger.besu.evm.gascalculator.GasCalculator;
import java.math.BigInteger;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import ethereum.ckzg4844.CKZG4844JNI;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32;
import org.bouncycastle.crypto.digests.SHA256Digest;
/**
* Validates a transaction based on Frontier protocol runtime requirements.
*
* <p>The {@link MainnetTransactionValidator} performs the intrinsic gas cost check on the given
* {@link Transaction}.
*/
public class MainnetTransactionValidator implements TransactionValidator {
private final GasCalculator gasCalculator;
private final GasLimitCalculator gasLimitCalculator;
private final FeeMarket feeMarket;
private final boolean disallowSignatureMalleability;
private final Optional<BigInteger> chainId;
private final Set<TransactionType> acceptedTransactionTypes;
private final int maxInitcodeSize;
private final Optional<GenesisConfigOptions> genesisOptions;
public MainnetTransactionValidator(
final GasCalculator gasCalculator,
final GasLimitCalculator gasLimitCalculator,
final FeeMarket feeMarket,
final boolean checkSignatureMalleability,
final Optional<BigInteger> chainId,
final Set<TransactionType> acceptedTransactionTypes,
final int maxInitcodeSize) {
this.gasCalculator = gasCalculator;
this.gasLimitCalculator = gasLimitCalculator;
this.feeMarket = feeMarket;
this.disallowSignatureMalleability = checkSignatureMalleability;
this.chainId = chainId;
this.acceptedTransactionTypes = acceptedTransactionTypes;
this.maxInitcodeSize = maxInitcodeSize;
this.genesisOptions = Optional.empty();
}
public MainnetTransactionValidator(
final GasCalculator gasCalculator,
final GasLimitCalculator gasLimitCalculator,
final FeeMarket feeMarket,
final boolean checkSignatureMalleability,
final Optional<BigInteger> chainId,
final Set<TransactionType> acceptedTransactionTypes,
final int maxInitcodeSize,
final Optional<GenesisConfigOptions> genesisOptions) {
this.gasCalculator = gasCalculator;
this.gasLimitCalculator = gasLimitCalculator;
this.feeMarket = feeMarket;
this.disallowSignatureMalleability = checkSignatureMalleability;
this.chainId = chainId;
this.acceptedTransactionTypes = acceptedTransactionTypes;
this.maxInitcodeSize = maxInitcodeSize;
this.genesisOptions = genesisOptions;
}
@Override
public ValidationResult<TransactionInvalidReason> validate(
final Transaction transaction,
final long blockTimestamp,
final Optional<Wei> baseFee,
final TransactionValidationParams transactionValidationParams) {
if (transaction.getType() != TransactionType.OPTIMISM_DEPOSIT) {
final ValidationResult<TransactionInvalidReason> signatureResult =
validateTransactionSignature(transaction);
if (!signatureResult.isValid()) {
return signatureResult;
}
}
if (transaction.getType().supportsBlob()) {
final ValidationResult<TransactionInvalidReason> blobTransactionResult =
validateBlobTransaction(transaction);
if (!blobTransactionResult.isValid()) {
return blobTransactionResult;
}
if (transaction.getBlobsWithCommitments().isPresent()) {
final ValidationResult<TransactionInvalidReason> blobsResult =
validateTransactionsBlobs(transaction);
if (!blobsResult.isValid()) {
return blobsResult;
}
}
}
final TransactionType transactionType = transaction.getType();
if (!acceptedTransactionTypes.contains(transactionType)) {
return ValidationResult.invalid(
TransactionInvalidReason.INVALID_TRANSACTION_FORMAT,
String.format(
"Transaction type %s is invalid, accepted transaction types are %s",
transactionType, acceptedTransactionTypes));
}
if (transaction.getType().equals(TransactionType.OPTIMISM_DEPOSIT)) {
// genesisOptions.orElseThrow();
if (transaction.getIsSystemTx().orElse(false)) {
var regolithTime = genesisOptions.get().getRegolithTime();
if (genesisOptions.get().isOptimism() && regolithTime.orElseThrow() <= blockTimestamp) {
return ValidationResult.invalid(
TransactionInvalidReason.SYSTEM_TX_NOT_SUPPORT,
String.format(
"system tx not supported: address = %s", transaction.getSender().toHexString()));
}
}
return ValidationResult.valid();
}
if (transaction.getNonce() == MAX_NONCE) {
return ValidationResult.invalid(
TransactionInvalidReason.NONCE_OVERFLOW, "Nonce must be less than 2^64-1");
}
if (transaction.isContractCreation() && transaction.getPayload().size() > maxInitcodeSize) {
return ValidationResult.invalid(
TransactionInvalidReason.INITCODE_TOO_LARGE,
String.format(
"Initcode size of %d exceeds maximum size of %s",
transaction.getPayload().size(), maxInitcodeSize));
}
return validateCostAndFee(transaction, baseFee, transactionValidationParams);
}
private ValidationResult<TransactionInvalidReason> validateCostAndFee(
final Transaction transaction,
final Optional<Wei> maybeBaseFee,
final TransactionValidationParams transactionValidationParams) {
if (maybeBaseFee.isPresent()) {
final Wei price = feeMarket.getTransactionPriceCalculator().price(transaction, maybeBaseFee);
if (!transactionValidationParams.isAllowMaxFeeGasBelowBaseFee()
&& price.compareTo(maybeBaseFee.orElseThrow()) < 0) {
return ValidationResult.invalid(
TransactionInvalidReason.GAS_PRICE_BELOW_CURRENT_BASE_FEE,
"gasPrice is less than the current BaseFee");
}
// assert transaction.max_fee_per_gas >= transaction.max_priority_fee_per_gas
if (transaction.getType().supports1559FeeMarket()
&& transaction
.getMaxPriorityFeePerGas()
.get()
.getAsBigInteger()
.compareTo(transaction.getMaxFeePerGas().get().getAsBigInteger())
> 0) {
return ValidationResult.invalid(
TransactionInvalidReason.MAX_PRIORITY_FEE_PER_GAS_EXCEEDS_MAX_FEE_PER_GAS,
"max priority fee per gas cannot be greater than max fee per gas");
}
}
if (transaction.getType().supportsBlob()) {
final long txTotalBlobGas = gasCalculator.blobGasCost(transaction.getBlobCount());
if (txTotalBlobGas > gasLimitCalculator.currentBlobGasLimit()) {
return ValidationResult.invalid(
TransactionInvalidReason.TOTAL_BLOB_GAS_TOO_HIGH,
String.format(
"total blob gas %d exceeds max blob gas per block %d",
txTotalBlobGas, gasLimitCalculator.currentBlobGasLimit()));
}
}
final long intrinsicGasCost =
gasCalculator.transactionIntrinsicGasCost(
transaction.getPayload(), transaction.isContractCreation())
+ (transaction.getAccessList().map(gasCalculator::accessListGasCost).orElse(0L));
if (Long.compareUnsigned(intrinsicGasCost, transaction.getGasLimit()) > 0) {
return ValidationResult.invalid(
TransactionInvalidReason.INTRINSIC_GAS_EXCEEDS_GAS_LIMIT,
String.format(
"intrinsic gas cost %s exceeds gas limit %s",
intrinsicGasCost, transaction.getGasLimit()));
}
return ValidationResult.valid();
}
@Override
public ValidationResult<TransactionInvalidReason> validateForSender(
final Transaction transaction,
final Account sender,
final TransactionValidationParams validationParams) {
if (TransactionType.OPTIMISM_DEPOSIT.equals(transaction.getType())) {
return ValidationResult.valid();
}
Wei senderBalance = Account.DEFAULT_BALANCE;
long senderNonce = Account.DEFAULT_NONCE;
Hash codeHash = Hash.EMPTY;
if (sender != null) {
senderBalance = sender.getBalance();
senderNonce = sender.getNonce();
if (sender.getCodeHash() != null) codeHash = sender.getCodeHash();
}
// todo calculate gas cost with l1 gas cost
final Wei upfrontCost =
transaction.getUpfrontCost(gasCalculator.blobGasCost(transaction.getBlobCount()));
if (upfrontCost.compareTo(senderBalance) > 0) {
return ValidationResult.invalid(
TransactionInvalidReason.UPFRONT_COST_EXCEEDS_BALANCE,
String.format(
"transaction up-front cost %s exceeds transaction sender account balance %s",
upfrontCost.toQuantityHexString(), senderBalance.toQuantityHexString()));
}
if (transaction.getNonce() < senderNonce) {
return ValidationResult.invalid(
TransactionInvalidReason.NONCE_TOO_LOW,
String.format(
"transaction nonce %s below sender account nonce %s",
transaction.getNonce(), senderNonce));
}
if (!validationParams.isAllowFutureNonce() && senderNonce != transaction.getNonce()) {
return ValidationResult.invalid(
TransactionInvalidReason.NONCE_TOO_HIGH,
String.format(
"transaction nonce %s does not match sender account nonce %s.",
transaction.getNonce(), senderNonce));
}
if (!validationParams.isAllowContractAddressAsSender() && !codeHash.equals(Hash.EMPTY)) {
return ValidationResult.invalid(
TransactionInvalidReason.TX_SENDER_NOT_AUTHORIZED,
String.format(
"Sender %s has deployed code and so is not authorized to send transactions",
transaction.getSender()));
}
return ValidationResult.valid();
}
private ValidationResult<TransactionInvalidReason> validateTransactionSignature(
final Transaction transaction) {
if (chainId.isPresent()
&& (transaction.getChainId().isPresent() && !transaction.getChainId().equals(chainId))) {
return ValidationResult.invalid(
TransactionInvalidReason.WRONG_CHAIN_ID,
String.format(
"transaction was meant for chain id %s and not this chain id %s",
transaction.getChainId().get(), chainId.get()));
}
if (chainId.isEmpty() && transaction.getChainId().isPresent()) {
return ValidationResult.invalid(
TransactionInvalidReason.REPLAY_PROTECTED_SIGNATURES_NOT_SUPPORTED,
"replay protected signatures is not supported");
}
final SECPSignature signature = transaction.getSignature();
final BigInteger halfCurveOrder = SignatureAlgorithmFactory.getInstance().getHalfCurveOrder();
if (disallowSignatureMalleability && signature.getS().compareTo(halfCurveOrder) > 0) {
return ValidationResult.invalid(
TransactionInvalidReason.INVALID_SIGNATURE,
String.format(
"Signature s value should be less than %s, but got %s",
halfCurveOrder, signature.getS()));
}
// org.bouncycastle.math.ec.ECCurve.AbstractFp.decompressPoint throws an
// IllegalArgumentException for "Invalid point compression" for bad signatures.
try {
transaction.getSender();
} catch (final IllegalArgumentException e) {
return ValidationResult.invalid(
TransactionInvalidReason.INVALID_SIGNATURE,
"sender could not be extracted from transaction signature");
}
return ValidationResult.valid();
}
public ValidationResult<TransactionInvalidReason> validateBlobTransaction(
final Transaction transaction) {
if (transaction.getType().supportsBlob() && transaction.getTo().isEmpty()) {
return ValidationResult.invalid(
TransactionInvalidReason.INVALID_TRANSACTION_FORMAT,
"transaction blob transactions cannot have a to address");
}
if (transaction.getVersionedHashes().isEmpty()) {
return ValidationResult.invalid(
TransactionInvalidReason.INVALID_BLOBS,
"transaction blob transactions must specify one or more versioned hashes");
}
return ValidationResult.valid();
}
public ValidationResult<TransactionInvalidReason> validateTransactionsBlobs(
final Transaction transaction) {
if (transaction.getBlobsWithCommitments().isEmpty()) {
return ValidationResult.invalid(
TransactionInvalidReason.INVALID_BLOBS,
"transaction blobs are empty, cannot verify without blobs");
}
BlobsWithCommitments blobsWithCommitments = transaction.getBlobsWithCommitments().get();
if (blobsWithCommitments.getBlobs().size() != blobsWithCommitments.getKzgCommitments().size()) {
return ValidationResult.invalid(
TransactionInvalidReason.INVALID_BLOBS,
"transaction blobs and commitments are not the same size");
}
if (transaction.getVersionedHashes().isEmpty()) {
return ValidationResult.invalid(
TransactionInvalidReason.INVALID_BLOBS,
"transaction versioned hashes are empty, cannot verify without versioned hashes");
}
final List<VersionedHash> versionedHashes = transaction.getVersionedHashes().get();
for (int i = 0; i < versionedHashes.size(); i++) {
final KZGCommitment commitment = blobsWithCommitments.getKzgCommitments().get(i);
final VersionedHash versionedHash = versionedHashes.get(i);
if (versionedHash.getVersionId() != VersionedHash.SHA256_VERSION_ID) {
return ValidationResult.invalid(
TransactionInvalidReason.INVALID_BLOBS,
"transaction blobs commitment version is not supported. Expected "
+ VersionedHash.SHA256_VERSION_ID
+ ", found "
+ versionedHash.getVersionId());
}
final VersionedHash calculatedVersionedHash = hashCommitment(commitment);
if (!calculatedVersionedHash.equals(versionedHash)) {
return ValidationResult.invalid(
TransactionInvalidReason.INVALID_BLOBS,
"transaction blobs commitment hash does not match commitment");
}
}
final byte[] blobs =
Bytes.wrap(blobsWithCommitments.getBlobs().stream().map(Blob::getData).toList())
.toArrayUnsafe();
final byte[] kzgCommitments =
Bytes.wrap(
blobsWithCommitments.getKzgCommitments().stream()
.map(kc -> (Bytes) kc.getData())
.toList())
.toArrayUnsafe();
final byte[] kzgProofs =
Bytes.wrap(
blobsWithCommitments.getKzgProofs().stream()
.map(kp -> (Bytes) kp.getData())
.toList())
.toArrayUnsafe();
final boolean kzgVerification =
CKZG4844JNI.verifyBlobKzgProofBatch(
blobs, kzgCommitments, kzgProofs, blobsWithCommitments.getBlobs().size());
if (!kzgVerification) {
return ValidationResult.invalid(
TransactionInvalidReason.INVALID_BLOBS,
"transaction blobs kzg proof verification failed");
}
return ValidationResult.valid();
}
private VersionedHash hashCommitment(final KZGCommitment commitment) {
final SHA256Digest digest = new SHA256Digest();
digest.update(commitment.getData().toArrayUnsafe(), 0, commitment.getData().size());
final byte[] dig = new byte[digest.getDigestSize()];
digest.doFinal(dig, 0);
dig[0] = VersionedHash.SHA256_VERSION_ID;
return new VersionedHash(Bytes32.wrap(dig));
}
}