Skip to content

Commit

Permalink
all: implement eip-7002 EL triggered withdrawal requests
Browse files Browse the repository at this point in the history
  • Loading branch information
lightclient committed Apr 23, 2024
1 parent e86bac2 commit 3e2561f
Show file tree
Hide file tree
Showing 9 changed files with 272 additions and 38 deletions.
85 changes: 48 additions & 37 deletions beacon/engine/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,24 +59,25 @@ type payloadAttributesMarshaling struct {

// ExecutableData is the data necessary to execute an EL payload.
type ExecutableData struct {
ParentHash common.Hash `json:"parentHash" gencodec:"required"`
FeeRecipient common.Address `json:"feeRecipient" gencodec:"required"`
StateRoot common.Hash `json:"stateRoot" gencodec:"required"`
ReceiptsRoot common.Hash `json:"receiptsRoot" gencodec:"required"`
LogsBloom []byte `json:"logsBloom" gencodec:"required"`
Random common.Hash `json:"prevRandao" gencodec:"required"`
Number uint64 `json:"blockNumber" gencodec:"required"`
GasLimit uint64 `json:"gasLimit" gencodec:"required"`
GasUsed uint64 `json:"gasUsed" gencodec:"required"`
Timestamp uint64 `json:"timestamp" gencodec:"required"`
ExtraData []byte `json:"extraData" gencodec:"required"`
BaseFeePerGas *big.Int `json:"baseFeePerGas" gencodec:"required"`
BlockHash common.Hash `json:"blockHash" gencodec:"required"`
Transactions [][]byte `json:"transactions" gencodec:"required"`
Withdrawals []*types.Withdrawal `json:"withdrawals"`
BlobGasUsed *uint64 `json:"blobGasUsed"`
ExcessBlobGas *uint64 `json:"excessBlobGas"`
Deposits types.Deposits `json:"depositRequests"`
ParentHash common.Hash `json:"parentHash" gencodec:"required"`
FeeRecipient common.Address `json:"feeRecipient" gencodec:"required"`
StateRoot common.Hash `json:"stateRoot" gencodec:"required"`
ReceiptsRoot common.Hash `json:"receiptsRoot" gencodec:"required"`
LogsBloom []byte `json:"logsBloom" gencodec:"required"`
Random common.Hash `json:"prevRandao" gencodec:"required"`
Number uint64 `json:"blockNumber" gencodec:"required"`
GasLimit uint64 `json:"gasLimit" gencodec:"required"`
GasUsed uint64 `json:"gasUsed" gencodec:"required"`
Timestamp uint64 `json:"timestamp" gencodec:"required"`
ExtraData []byte `json:"extraData" gencodec:"required"`
BaseFeePerGas *big.Int `json:"baseFeePerGas" gencodec:"required"`
BlockHash common.Hash `json:"blockHash" gencodec:"required"`
Transactions [][]byte `json:"transactions" gencodec:"required"`
Withdrawals []*types.Withdrawal `json:"withdrawals"`
BlobGasUsed *uint64 `json:"blobGasUsed"`
ExcessBlobGas *uint64 `json:"excessBlobGas"`
Deposits types.Deposits `json:"depositRequests"`
WithdrawalRequests types.WithdrawalRequests `json:"withdrawalRequests"`
}

// JSON type overrides for executableData.
Expand Down Expand Up @@ -232,15 +233,24 @@ func ExecutableDataToBlock(params ExecutableData, versionedHashes []common.Hash,
withdrawalsRoot = &h
}

// Only set requestsHash if there exists requests in the ExecutableData. This
// allows CLs to continue using the data structure before requests are
// enabled.
var (
requestsHash *common.Hash
requests types.Requests
)
if params.Deposits != nil {
requests = params.Deposits.Requests()
requests = append(requests, params.Deposits.Requests()...)
}
if params.WithdrawalRequests != nil {
requests = append(requests, params.WithdrawalRequests.Requests()...)
}
if requests != nil {
h := types.DeriveSha(requests, trie.NewStackTrie(nil))
requestsHash = &h
}

header := &types.Header{
ParentHash: params.ParentHash,
UncleHash: types.EmptyUncleHash,
Expand Down Expand Up @@ -275,24 +285,25 @@ func ExecutableDataToBlock(params ExecutableData, versionedHashes []common.Hash,
// fields from the given block. It assumes the given block is post-merge block.
func BlockToExecutableData(block *types.Block, fees *big.Int, sidecars []*types.BlobTxSidecar) *ExecutionPayloadEnvelope {
data := &ExecutableData{
BlockHash: block.Hash(),
ParentHash: block.ParentHash(),
FeeRecipient: block.Coinbase(),
StateRoot: block.Root(),
Number: block.NumberU64(),
GasLimit: block.GasLimit(),
GasUsed: block.GasUsed(),
BaseFeePerGas: block.BaseFee(),
Timestamp: block.Time(),
ReceiptsRoot: block.ReceiptHash(),
LogsBloom: block.Bloom().Bytes(),
Transactions: encodeTransactions(block.Transactions()),
Random: block.MixDigest(),
ExtraData: block.Extra(),
Withdrawals: block.Withdrawals(),
BlobGasUsed: block.BlobGasUsed(),
ExcessBlobGas: block.ExcessBlobGas(),
Deposits: block.Deposits(),
BlockHash: block.Hash(),
ParentHash: block.ParentHash(),
FeeRecipient: block.Coinbase(),
StateRoot: block.Root(),
Number: block.NumberU64(),
GasLimit: block.GasLimit(),
GasUsed: block.GasUsed(),
BaseFeePerGas: block.BaseFee(),
Timestamp: block.Time(),
ReceiptsRoot: block.ReceiptHash(),
LogsBloom: block.Bloom().Bytes(),
Transactions: encodeTransactions(block.Transactions()),
Random: block.MixDigest(),
ExtraData: block.Extra(),
Withdrawals: block.Withdrawals(),
BlobGasUsed: block.BlobGasUsed(),
ExcessBlobGas: block.ExcessBlobGas(),
Deposits: block.Deposits(),
WithdrawalRequests: block.WithdrawalRequests(),
}
bundle := BlobsBundleV1{
Commitments: make([]hexutil.Bytes, 0),
Expand Down
96 changes: 96 additions & 0 deletions core/blockchain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package core

import (
"encoding/binary"
"errors"
"fmt"
"math/big"
Expand Down Expand Up @@ -4303,3 +4304,98 @@ func TestEIP6110(t *testing.T) {
}
}
}

// TestEIP7002 verifies that withdrawal requests are processed correctly in the
// pre-deploy and parsed out correctly via the system call.
func TestEIP7002(t *testing.T) {
var (
engine = beacon.NewFaker()

// A sender who makes transactions, has some funds
key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
addr = crypto.PubkeyToAddress(key.PublicKey)
funds = new(big.Int).Mul(common.Big1, big.NewInt(params.Ether))
config = *params.AllEthashProtocolChanges
gspec = &Genesis{
Config: &config,
Alloc: types.GenesisAlloc{
addr: {Balance: funds},
params.WithdrawalRequestsAddress: {Code: common.FromHex("3373fffffffffffffffffffffffffffffffffffffffe146090573615156028575f545f5260205ff35b366038141561012e5760115f54600182026001905f5b5f82111560595781019083028483029004916001019190603e565b90939004341061012e57600154600101600155600354806003026004013381556001015f3581556001016020359055600101600355005b6003546002548082038060101160a4575060105b5f5b81811460dd5780604c02838201600302600401805490600101805490600101549160601b83528260140152906034015260010160a6565b910180921460ed579060025560f8565b90505f6002555f6003555b5f548061049d141561010757505f5b60015460028282011161011c5750505f610122565b01600290035b5f555f600155604c025ff35b5f5ffd")},
},
}
)
gspec.Config.BerlinBlock = common.Big0
gspec.Config.LondonBlock = common.Big0
gspec.Config.TerminalTotalDifficulty = common.Big0
gspec.Config.TerminalTotalDifficultyPassed = true
gspec.Config.ShanghaiTime = u64(0)
gspec.Config.CancunTime = u64(0)
gspec.Config.PragueTime = u64(0)
signer := types.LatestSigner(gspec.Config)

// Withdrawal requests to send.
wxs := types.WithdrawalRequests{
{
Source: addr,
PublicKey: [48]byte{42},
Amount: 42,
},
{
Source: addr,
PublicKey: [48]byte{13, 37},
Amount: 1337,
},
}

_, blocks, _ := GenerateChainWithGenesis(gspec, engine, 1, func(i int, b *BlockGen) {
for i, wx := range wxs {
data := make([]byte, 56)
copy(data, wx.PublicKey[:])
binary.LittleEndian.PutUint64(data[48:], wx.Amount)
txdata := &types.DynamicFeeTx{
ChainID: gspec.Config.ChainID,
Nonce: uint64(i),
To: &params.WithdrawalRequestsAddress,
Value: big.NewInt(1),
Gas: 500000,
GasFeeCap: newGwei(5),
GasTipCap: big.NewInt(2),
AccessList: nil,
Data: data,
}
tx := types.NewTx(txdata)
tx, _ = types.SignTx(tx, signer, key)
b.AddTx(tx)
}
})
chain, err := NewBlockChain(rawdb.NewMemoryDatabase(), nil, gspec, nil, engine, vm.Config{Tracer: logger.NewMarkdownLogger(&logger.Config{}, os.Stderr).Hooks()}, nil, nil)
if err != nil {
t.Fatalf("failed to create tester chain: %v", err)
}
defer chain.Stop()
if n, err := chain.InsertChain(blocks); err != nil {
t.Fatalf("block %d: failed to insert into chain: %v", n, err)
}
block := chain.GetBlockByNumber(1)
if block == nil {
t.Fatalf("failed to retrieve block 1")
}

// Verify the withdrawal requests match.
got := block.WithdrawalRequests()
if len(got) != 2 {
t.Fatalf("wrong number of withdrawal requests: wanted 2, got %d", len(wxs))
}
for i, want := range wxs {
if want.Source != got[i].Source {
t.Fatalf("wrong source address: want %s, got %s", want.Source, got[i].Source)
}
if want.PublicKey != got[i].PublicKey {
t.Fatalf("wrong public key: want %s, got %s", common.Bytes2Hex(want.PublicKey[:]), common.Bytes2Hex(got[i].PublicKey[:]))
}
if want.Amount != got[i].Amount {
t.Fatalf("wrong amount: want %d, got %d", want.Amount, got[i].Amount)
}
}

}
7 changes: 7 additions & 0 deletions core/chain_makers.go
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,13 @@ func GenerateChain(config *params.ChainConfig, parent *types.Block, engine conse
}
requests = append(requests, d...)
}

var (
blockContext = NewEVMBlockContext(b.header, b.cm, &b.header.Coinbase)
vmenv = vm.NewEVM(blockContext, vm.TxContext{}, b.statedb, b.cm.config, vm.Config{})
)
wxs := ProcessDequeueWithdrawalRequests(vmenv, statedb)
requests = append(requests, wxs...)
}

body := types.Body{Transactions: b.txs, Uncles: b.uncles, Withdrawals: b.withdrawals, Requests: requests}
Expand Down
34 changes: 34 additions & 0 deletions core/state_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package core

import (
"encoding/binary"
"errors"
"fmt"
"math/big"
Expand Down Expand Up @@ -108,6 +109,8 @@ func (p *StateProcessor) Process(block *types.Block, statedb *state.StateDB, cfg
if err != nil {
return nil, err
}
wxs := ProcessDequeueWithdrawalRequests(vmenv, statedb)
requests = append(requests, wxs...)
}

// Finalize the block, applying any consensus engine specific extras (e.g. block rewards)
Expand Down Expand Up @@ -233,3 +236,34 @@ func ParseDepositLogs(logs []*types.Log) (types.Requests, error) {
}
return deposits, nil
}

// ProcessDequeueWithdrawalRequests applies the EIP-7002 system call to the withdrawal requests contract.
func ProcessDequeueWithdrawalRequests(vmenv *vm.EVM, statedb *state.StateDB) types.Requests {
msg := &Message{
From: params.SystemAddress,
GasLimit: 30_000_000,
GasPrice: common.Big0,
GasFeeCap: common.Big0,
GasTipCap: common.Big0,
To: &params.WithdrawalRequestsAddress,
}
vmenv.Reset(NewEVMTxContext(msg), statedb)
statedb.AddAddressToAccessList(params.WithdrawalRequestsAddress)
ret, _, _ := vmenv.Call(vm.AccountRef(msg.From), *msg.To, msg.Data, 30_000_000, common.U2560)
statedb.Finalise(true)

// Parse out the exits.
var reqs types.Requests
for i := 0; i < len(ret)/76; i++ {
start := i * 76
var pubkey [48]byte
copy(pubkey[:], ret[start+20:start+68])
wx := &types.WithdrawalRequest{
Source: common.BytesToAddress(ret[start : start+20]),
PublicKey: pubkey,
Amount: binary.LittleEndian.Uint64(ret[start+68:]),
}
reqs = append(reqs, types.NewRequest(wx))
}
return reqs
}
9 changes: 9 additions & 0 deletions core/types/block.go
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,15 @@ func (b *Block) Deposits() Deposits {
}
return deps
}
func (b *Block) WithdrawalRequests() WithdrawalRequests {
var wxs WithdrawalRequests
for _, r := range b.requests {
if w, ok := r.inner.(*WithdrawalRequest); ok {
wxs = append(wxs, w)
}
}
return wxs
}

func (b *Block) Transaction(hash common.Hash) *Transaction {
for _, transaction := range b.transactions {
Expand Down
5 changes: 4 additions & 1 deletion core/types/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ var (

// Request types.
const (
DepositRequestType = 0x00
DepositRequestType = 0x00
WithdrawalRequestType = 0x01
)

// Request is an EIP-7685 request object. It represents execution layer
Expand Down Expand Up @@ -143,6 +144,8 @@ func (r *Request) decode(b []byte) (RequestData, error) {
switch b[0] {
case DepositRequestType:
inner = new(Deposit)
case WithdrawalRequestType:
inner = new(WithdrawalRequest)
default:
return nil, ErrRequestTypeNotSupported
}
Expand Down
71 changes: 71 additions & 0 deletions core/types/withdrawal_request.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// Copyright 2024 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package types

import (
"bytes"
"encoding/binary"

"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/rlp"
)

// WithdrawalRequest represents an EIP-7002 withdrawal request from source for
// the validator associated with the public key for amount.
type WithdrawalRequest struct {
Source common.Address `json:"source"`
PublicKey BLSPublicKey `json:"pubkey"`
Amount uint64 `json:"amount"`
}

func (w *WithdrawalRequest) Bytes() []byte {
out := make([]byte, 76)
copy(out, w.Source.Bytes())
copy(out[20:], w.PublicKey[:])
binary.LittleEndian.PutUint64(out, w.Amount)
return out
}

// WithdrawalRequests implements DerivableList for withdrawal requests.
type WithdrawalRequests []*WithdrawalRequest

// Len returns the length of s.
func (s WithdrawalRequests) Len() int { return len(s) }

// EncodeIndex encodes the i'th withdrawal request to w.
func (s WithdrawalRequests) EncodeIndex(i int, w *bytes.Buffer) {
rlp.Encode(w, s[i])
}

// Requests creates a deep copy of each deposit and returns a slice of the
// withdrwawal requests as Request objects.
func (s WithdrawalRequests) Requests() (reqs Requests) {
for _, d := range s {
reqs = append(reqs, NewRequest(d))
}
return
}

func (w *WithdrawalRequest) requestType() byte { return WithdrawalRequestType }
func (w *WithdrawalRequest) encode(b *bytes.Buffer) error { return rlp.Encode(b, w) }
func (w *WithdrawalRequest) decode(input []byte) error { return rlp.DecodeBytes(input, w) }
func (w *WithdrawalRequest) copy() RequestData {
return &WithdrawalRequest{
Source: w.Source,
PublicKey: w.PublicKey,
Amount: w.Amount,
}
}

0 comments on commit 3e2561f

Please sign in to comment.