Skip to content
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

7702 refactor, remove CodeDelegationAccount abstraction #8408

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
b34ae92
7702 refactor, remove CodeDelegationAccount abstraction
daniellehrner Mar 11, 2025
9f9c6ba
fix check if account has a code delegation
daniellehrner Mar 14, 2025
35d1b91
fix unit test
daniellehrner Mar 14, 2025
bf436bd
fix CodeDelegationProcessorTest
daniellehrner Mar 14, 2025
c5b34f8
fix warming of target address, fix account retrieval
daniellehrner Mar 18, 2025
1897206
bugfix: use target address for calculation of code resolution
daniellehrner Mar 19, 2025
5e8f614
move CodeDelegationService from CodeDelegationProcessor.process() to …
daniellehrner Mar 20, 2025
06514c4
added test for CodeDelegationHelper, added debug logs when running ou…
daniellehrner Mar 21, 2025
08fad2a
Merge branch 'main' into feat/issue-8392/remove_code_delegation_abstr…
daniellehrner Mar 21, 2025
b37abd0
Merge branch 'main' into feat/issue-8392/remove_code_delegation_abstr…
daniellehrner Mar 25, 2025
99e53e2
remove Optional from getTargetAccount()
daniellehrner Mar 25, 2025
e069fe5
changed check for code delegation in MainnetTransactionProcessor, reo…
daniellehrner Mar 26, 2025
0f9f630
Merge branch 'main' into feat/issue-8392/remove_code_delegation_abstr…
daniellehrner Mar 26, 2025
af7fe7e
code resolution gas must be deducted before we check for frame depth …
daniellehrner Mar 27, 2025
484d0bc
Merge branch 'main' into feat/issue-8392/remove_code_delegation_abstr…
daniellehrner Mar 27, 2025
8b5e8f1
add getTransactionType to mocks of transactions
daniellehrner Mar 27, 2025
02ce0bd
check code hash before getting code to return empty bytes for account…
daniellehrner Mar 28, 2025
2a3f946
Merge branch 'main' into feat/issue-8392/remove_code_delegation_abstr…
daniellehrner Mar 28, 2025
007c8c6
check code hash for null before equals, fix test
daniellehrner Mar 29, 2025
42794f3
Merge branch 'main' into feat/issue-8392/remove_code_delegation_abstr…
daniellehrner Mar 29, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -121,9 +121,9 @@ public SECPSignature signature() {

@Override
public Optional<Address> authorizer() {
// recId needs to be between 0 and 3, otherwise the signature is invalid
// recId needs to be between either 0 or 1, otherwise the signature is invalid
// which means we can't recover the authorizer.
if (signature.getRecId() < 0 || signature.getRecId() > 3) {
if (signature.getRecId() > 1 || signature.getRecId() < 0) {
return Optional.empty();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
import org.hyperledger.besu.ethereum.core.CodeDelegation;
import org.hyperledger.besu.ethereum.core.Transaction;
import org.hyperledger.besu.evm.account.MutableAccount;
import org.hyperledger.besu.evm.worldstate.EVMWorldUpdater;
import org.hyperledger.besu.evm.worldstate.CodeDelegationService;
import org.hyperledger.besu.evm.worldstate.WorldUpdater;

import java.math.BigInteger;
import java.util.Optional;
Expand All @@ -33,11 +34,15 @@ public class CodeDelegationProcessor {

private final Optional<BigInteger> maybeChainId;
private final BigInteger halfCurveOrder;
private final CodeDelegationService codeDelegationService;

public CodeDelegationProcessor(
final Optional<BigInteger> maybeChainId, final BigInteger halfCurveOrder) {
final Optional<BigInteger> maybeChainId,
final BigInteger halfCurveOrder,
final CodeDelegationService codeDelegationService) {
this.maybeChainId = maybeChainId;
this.halfCurveOrder = halfCurveOrder;
this.codeDelegationService = codeDelegationService;
}

/**
Expand All @@ -57,12 +62,12 @@ public CodeDelegationProcessor(
* <li>Increase the nonce of `authority` by one.
* </ol>
*
* @param evmWorldUpdater The world state updater which is aware of code delegation.
* @param worldUpdater The world state updater which is aware of code delegation.
* @param transaction The transaction being processed.
* @return The result of the code delegation processing.
*/
public CodeDelegationResult process(
final EVMWorldUpdater evmWorldUpdater, final Transaction transaction) {
final WorldUpdater worldUpdater, final Transaction transaction) {
final CodeDelegationResult result = new CodeDelegationResult();

transaction
Expand All @@ -71,15 +76,15 @@ public CodeDelegationResult process(
.forEach(
codeDelegation ->
processCodeDelegation(
evmWorldUpdater,
worldUpdater,
(org.hyperledger.besu.ethereum.core.CodeDelegation) codeDelegation,
result));

return result;
}

private void processCodeDelegation(
final EVMWorldUpdater evmWorldUpdater,
final WorldUpdater worldUpdater,
final CodeDelegation codeDelegation,
final CodeDelegationResult result) {
LOG.trace("Processing code delegation: {}", codeDelegation);
Expand Down Expand Up @@ -114,7 +119,7 @@ private void processCodeDelegation(
LOG.trace("Set code delegation for authority: {}", authorizer.get());

final Optional<MutableAccount> maybeAuthorityAccount =
Optional.ofNullable(evmWorldUpdater.getAccount(authorizer.get()));
Optional.ofNullable(worldUpdater.getAccount(authorizer.get()));

result.addAccessedDelegatorAddress(authorizer.get());

Expand All @@ -125,11 +130,11 @@ private void processCodeDelegation(
if (codeDelegation.nonce() != 0) {
return;
}
authority = evmWorldUpdater.createAccount(authorizer.get());
authority = worldUpdater.createAccount(authorizer.get());
} else {
authority = maybeAuthorityAccount.get();

if (!evmWorldUpdater.codeDelegationService().canSetCodeDelegation(authority)) {
if (!codeDelegationService.canSetCodeDelegation(authority)) {
return;
}

Expand All @@ -148,9 +153,7 @@ private void processCodeDelegation(
result.incrementAlreadyExistingDelegators();
}

evmWorldUpdater
.codeDelegationService()
.processCodeDelegation(authority, codeDelegation.address());
codeDelegationService.processCodeDelegation(authority, codeDelegation.address());
authority.incrementNonce();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
import org.hyperledger.besu.evm.internal.EvmConfiguration;
import org.hyperledger.besu.evm.processor.ContractCreationProcessor;
import org.hyperledger.besu.evm.processor.MessageCallProcessor;
import org.hyperledger.besu.evm.worldstate.CodeDelegationService;
import org.hyperledger.besu.evm.worldstate.WorldState;
import org.hyperledger.besu.evm.worldstate.WorldUpdater;
import org.hyperledger.besu.plugin.services.MetricsSystem;
Expand Down Expand Up @@ -744,9 +745,6 @@ static ProtocolSpecBuilder cancunDefinition(
.maxStackSize(evmConfiguration.evmStackSize())
.feeMarket(feeMarket)
.coinbaseFeePriceCalculator(CoinbaseFeePriceCalculator.eip1559())
.codeDelegationProcessor(
new CodeDelegationProcessor(
chainId, SIGNATURE_ALGORITHM.get().getHalfCurveOrder()))
.build())
// change to check for max blob gas per block for EIP-4844
.transactionValidatorFactoryBuilder(
Expand Down Expand Up @@ -891,6 +889,29 @@ static ProtocolSpecBuilder pragueDefinition(
TransactionType.BLOB,
TransactionType.DELEGATE_CODE),
evm.getMaxInitcodeSize()))
// CodeDelegationProcessor
.transactionProcessorBuilder(
(gasCalculator,
feeMarket,
transactionValidator,
contractCreationProcessor,
messageCallProcessor) ->
MainnetTransactionProcessor.builder()
.gasCalculator(gasCalculator)
.transactionValidatorFactory(transactionValidator)
.contractCreationProcessor(contractCreationProcessor)
.messageCallProcessor(messageCallProcessor)
.clearEmptyAccounts(true)
.warmCoinbase(true)
.maxStackSize(evmConfiguration.evmStackSize())
.feeMarket(feeMarket)
.coinbaseFeePriceCalculator(CoinbaseFeePriceCalculator.eip1559())
.codeDelegationProcessor(
new CodeDelegationProcessor(
chainId,
SIGNATURE_ALGORITHM.get().getHalfCurveOrder(),
new CodeDelegationService()))
.build())

// TODO SLD EIP-7840 Can we dynamically wire in the appropriate GasCalculator instead of
// overriding
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,14 @@
import static org.hyperledger.besu.ethereum.mainnet.PrivateStateUtils.KEY_TRANSACTION;
import static org.hyperledger.besu.ethereum.mainnet.PrivateStateUtils.KEY_TRANSACTION_HASH;
import static org.hyperledger.besu.evm.internal.Words.clampedAdd;
import static org.hyperledger.besu.evm.worldstate.CodeDelegationHelper.getTargetAccount;
import static org.hyperledger.besu.evm.worldstate.CodeDelegationHelper.hasCodeDelegation;

import org.hyperledger.besu.collections.trie.BytesTrieSet;
import org.hyperledger.besu.datatypes.AccessListEntry;
import org.hyperledger.besu.datatypes.Address;
import org.hyperledger.besu.datatypes.Hash;
import org.hyperledger.besu.datatypes.TransactionType;
import org.hyperledger.besu.datatypes.Wei;
import org.hyperledger.besu.ethereum.core.ProcessableBlockHeader;
import org.hyperledger.besu.ethereum.core.Transaction;
Expand All @@ -34,6 +38,7 @@
import org.hyperledger.besu.ethereum.trie.MerkleTrieException;
import org.hyperledger.besu.evm.Code;
import org.hyperledger.besu.evm.account.Account;
import org.hyperledger.besu.evm.account.CodeDelegationAccount;
import org.hyperledger.besu.evm.account.MutableAccount;
import org.hyperledger.besu.evm.blockhash.BlockHashLookup;
import org.hyperledger.besu.evm.code.CodeInvalid;
Expand All @@ -45,7 +50,6 @@
import org.hyperledger.besu.evm.processor.ContractCreationProcessor;
import org.hyperledger.besu.evm.processor.MessageCallProcessor;
import org.hyperledger.besu.evm.tracing.OperationTracer;
import org.hyperledger.besu.evm.worldstate.EVMWorldUpdater;
import org.hyperledger.besu.evm.worldstate.WorldUpdater;

import java.util.Deque;
Expand Down Expand Up @@ -266,7 +270,6 @@ public TransactionProcessingResult processTransaction(
final TransactionValidationParams transactionValidationParams,
final PrivateMetadataUpdater privateMetadataUpdater,
final Wei blobGasPrice) {
final EVMWorldUpdater evmWorldUpdater = new EVMWorldUpdater(worldState, gasCalculator);
try {
final var transactionValidator = transactionValidatorFactory.get();
LOG.trace("Starting execution of {}", transaction);
Expand All @@ -285,7 +288,7 @@ public TransactionProcessingResult processTransaction(
}

final Address senderAddress = transaction.getSender();
final MutableAccount sender = evmWorldUpdater.getOrCreateSenderAccount(senderAddress);
final MutableAccount sender = worldState.getOrCreateSenderAccount(senderAddress);

validationResult =
transactionValidator.validateForSender(transaction, sender, transactionValidationParams);
Expand All @@ -294,7 +297,7 @@ public TransactionProcessingResult processTransaction(
return TransactionProcessingResult.invalid(validationResult);
}

operationTracer.tracePrepareTransaction(evmWorldUpdater, transaction);
operationTracer.tracePrepareTransaction(worldState, transaction);

final Set<Address> warmAddressList = new BytesTrieSet<>(Address.SIZE);

Expand All @@ -321,19 +324,19 @@ public TransactionProcessingResult processTransaction(
sender.getBalance());

long codeDelegationRefund = 0L;
if (transaction.getCodeDelegationList().isPresent()) {
if (transaction.getType().equals(TransactionType.DELEGATE_CODE)) {
if (maybeCodeDelegationProcessor.isEmpty()) {
throw new RuntimeException("Code delegation processor is required for 7702 transactions");
}

final CodeDelegationResult codeDelegationResult =
maybeCodeDelegationProcessor.get().process(evmWorldUpdater, transaction);
maybeCodeDelegationProcessor.get().process(worldState, transaction);
warmAddressList.addAll(codeDelegationResult.accessedDelegatorAddresses());
codeDelegationRefund =
gasCalculator.calculateDelegateCodeGasRefund(
(codeDelegationResult.alreadyExistingDelegators()));

evmWorldUpdater.commit();
worldState.commit();
}

final List<AccessListEntry> accessListEntries = transaction.getAccessList().orElse(List.of());
Expand Down Expand Up @@ -369,7 +372,7 @@ public TransactionProcessingResult processTransaction(
transaction.getGasLimit(),
intrinsicGas);

final WorldUpdater worldUpdater = evmWorldUpdater.updater();
final WorldUpdater worldUpdater = worldState.updater();
final ImmutableMap.Builder<String, Object> contextVariablesBuilder =
ImmutableMap.<String, Object>builder()
.put(KEY_IS_PERSISTING_PRIVATE_STATE, isPersistingPrivateState)
Expand Down Expand Up @@ -425,32 +428,15 @@ public TransactionProcessingResult processTransaction(
} else {
@SuppressWarnings("OptionalGetWithoutIsPresent") // isContractCall tests isPresent
final Address to = transaction.getTo().get();
final Optional<Account> maybeContract = Optional.ofNullable(evmWorldUpdater.get(to));

if (maybeContract.isPresent() && maybeContract.get().hasDelegatedCode()) {
warmAddressList.add(maybeContract.get().codeDelegationAddress().get());
}
final Code code = processCodeFromAccount(worldState, warmAddressList, worldState.get(to));

initialFrame =
commonMessageFrameBuilder
.type(MessageFrame.Type.MESSAGE_CALL)
.address(to)
.contract(to)
.inputData(transaction.getPayload())
.code(
maybeContract
.map(
c -> {
if (c.hasDelegatedCode()) {
return messageCallProcessor.getCodeFromEVM(
c.getCodeDelegationTargetHash().get(),
c.getCodeDelegationTargetCode().get());
}

return messageCallProcessor.getCodeFromEVM(
c.getCodeHash(), c.getCode());
})
.orElse(CodeV0.EMPTY_CODE))
.code(code)
.accessListWarmAddresses(warmAddressList)
.build();
}
Expand Down Expand Up @@ -529,12 +515,12 @@ public TransactionProcessingResult processTransaction(

operationTracer.traceBeforeRewardTransaction(worldUpdater, transaction, coinbaseWeiDelta);
if (!coinbaseWeiDelta.isZero() || !clearEmptyAccounts) {
final var coinbase = evmWorldUpdater.getOrCreate(miningBeneficiary);
final var coinbase = worldState.getOrCreate(miningBeneficiary);
coinbase.incrementBalance(coinbaseWeiDelta);
}

operationTracer.traceEndTransaction(
evmWorldUpdater.updater(),
worldState.updater(),
transaction,
initialFrame.getState() == MessageFrame.State.COMPLETED_SUCCESS,
initialFrame.getOutputData(),
Expand All @@ -543,10 +529,10 @@ public TransactionProcessingResult processTransaction(
initialFrame.getSelfDestructs(),
0L);

initialFrame.getSelfDestructs().forEach(evmWorldUpdater::deleteAccount);
initialFrame.getSelfDestructs().forEach(worldState::deleteAccount);

if (clearEmptyAccounts) {
evmWorldUpdater.clearAccountsThatAreEmpty();
worldState.clearAccountsThatAreEmpty();
}

if (initialFrame.getState() == MessageFrame.State.COMPLETED_SUCCESS) {
Expand Down Expand Up @@ -574,7 +560,7 @@ public TransactionProcessingResult processTransaction(
}
} catch (final MerkleTrieException re) {
operationTracer.traceEndTransaction(
evmWorldUpdater.updater(),
worldState.updater(),
transaction,
false,
Bytes.EMPTY,
Expand All @@ -587,7 +573,7 @@ public TransactionProcessingResult processTransaction(
throw re;
} catch (final RuntimeException re) {
operationTracer.traceEndTransaction(
evmWorldUpdater.updater(),
worldState.updater(),
transaction,
false,
Bytes.EMPTY,
Expand Down Expand Up @@ -641,6 +627,35 @@ private String printableStackTraceFromThrowable(final RuntimeException re) {
return builder.toString();
}

private Code processCodeFromAccount(
final WorldUpdater worldUpdater, final Set<Address> warmAddressList, final Account contract) {
if (contract == null) {
return CodeV0.EMPTY_CODE;
}

final Hash codeHash = contract.getCodeHash();
if (codeHash == null || codeHash.equals(Hash.EMPTY)) {
return CodeV0.EMPTY_CODE;
}

if (hasCodeDelegation(contract.getCode())) {
return delegationTargetCode(worldUpdater, warmAddressList, contract);
}

return messageCallProcessor.getCodeFromEVM(contract.getCodeHash(), contract.getCode());
}

private Code delegationTargetCode(
final WorldUpdater worldUpdater, final Set<Address> warmAddressList, final Account contract) {
// we need to look up the target account and its code, but do NOT charge gas for it
final CodeDelegationAccount targetAccount =
getTargetAccount(worldUpdater, gasCalculator, contract);
warmAddressList.add(targetAccount.getTargetAddress());

return messageCallProcessor.getCodeFromEVM(
targetAccount.getCodeHash(), targetAccount.getCode());
}

public static Builder builder() {
return new Builder();
}
Expand Down
Loading