types.go 8.24 KB
Newer Older
1
package sources
2 3

import (
4
	"context"
5 6 7
	"fmt"
	"math/big"

8 9 10 11 12
	"github.com/ethereum/go-ethereum/common/hexutil"
	"github.com/holiman/uint256"

	"github.com/ethereum/go-ethereum/rpc"

13 14 15 16 17 18
	"github.com/ethereum-optimism/optimism/op-node/eth"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/trie"
)

19 20 21
type BatchCallContextFn func(ctx context.Context, b []rpc.BatchElem) error

// Note: these types are used, instead of the geth types, to enable:
22 23 24 25
// - batched calls of many block requests (standard bindings do extra uncle-header fetches, cannot be batched nicely)
// - ignore uncle data (does not even exist anymore post-Merge)
// - use cached block hash, if we trust the RPC.
// - verify transactions list matches tx-root, to ensure consistency with block-hash, if we do not trust the RPC
26
// - verify block contents are compatible with Post-Merge ExecutionPayload format
27 28 29 30 31 32
//
// Transaction-sender data from the RPC is not cached, since ethclient.setSenderFromServer is private,
// and we only need to compute the sender for transactions into the inbox.
//
// This way we minimize RPC calls, enable batching, and can choose to verify what the RPC gives us.

33 34
// HeaderInfo contains all the header-info required to implement the eth.BlockInfo interface,
// used in the rollup state-transition, with pre-computed block hash.
35 36 37
type HeaderInfo struct {
	hash        common.Hash
	parentHash  common.Hash
38
	coinbase    common.Address
39 40 41 42 43 44 45 46 47
	root        common.Hash
	number      uint64
	time        uint64
	mixDigest   common.Hash // a.k.a. the randomness field post-merge.
	baseFee     *big.Int
	txHash      common.Hash
	receiptHash common.Hash
}

48
var _ eth.BlockInfo = (*HeaderInfo)(nil)
49 50 51 52 53 54 55 56 57

func (info *HeaderInfo) Hash() common.Hash {
	return info.hash
}

func (info *HeaderInfo) ParentHash() common.Hash {
	return info.parentHash
}

58 59 60 61
func (info *HeaderInfo) Coinbase() common.Address {
	return info.coinbase
}

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
func (info *HeaderInfo) Root() common.Hash {
	return info.root
}

func (info *HeaderInfo) NumberU64() uint64 {
	return info.number
}

func (info *HeaderInfo) Time() uint64 {
	return info.time
}

func (info *HeaderInfo) MixDigest() common.Hash {
	return info.mixDigest
}

func (info *HeaderInfo) BaseFee() *big.Int {
	return info.baseFee
}

func (info *HeaderInfo) ID() eth.BlockID {
	return eth.BlockID{Hash: info.hash, Number: info.number}
}

func (info *HeaderInfo) ReceiptHash() common.Hash {
	return info.receiptHash
}

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
type rpcHeader struct {
	ParentHash  common.Hash      `json:"parentHash"`
	UncleHash   common.Hash      `json:"sha3Uncles"`
	Coinbase    common.Address   `json:"miner"`
	Root        common.Hash      `json:"stateRoot"`
	TxHash      common.Hash      `json:"transactionsRoot"`
	ReceiptHash common.Hash      `json:"receiptsRoot"`
	Bloom       eth.Bytes256     `json:"logsBloom"`
	Difficulty  hexutil.Big      `json:"difficulty"`
	Number      hexutil.Uint64   `json:"number"`
	GasLimit    hexutil.Uint64   `json:"gasLimit"`
	GasUsed     hexutil.Uint64   `json:"gasUsed"`
	Time        hexutil.Uint64   `json:"timestamp"`
	Extra       hexutil.Bytes    `json:"extraData"`
	MixDigest   common.Hash      `json:"mixHash"`
	Nonce       types.BlockNonce `json:"nonce"`

	// BaseFee was added by EIP-1559 and is ignored in legacy headers.
	BaseFee *hexutil.Big `json:"baseFeePerGas" rlp:"optional"`

	// untrusted info included by RPC, may have to be checked
111 112 113
	Hash common.Hash `json:"hash"`
}

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
// checkPostMerge checks that the block header meets all criteria to be a valid ExecutionPayloadHeader,
// see EIP-3675 (block header changes) and EIP-4399 (mixHash usage for prev-randao)
func (hdr *rpcHeader) checkPostMerge() error {
	// TODO: the genesis block has a non-zero difficulty number value.
	// Either this block needs to change, or we special case it. This is not valid w.r.t. EIP-3675.
	if hdr.Number != 0 && (*big.Int)(&hdr.Difficulty).Cmp(common.Big0) != 0 {
		return fmt.Errorf("post-merge block header requires zeroed difficulty field, but got: %s", &hdr.Difficulty)
	}
	if hdr.Nonce != (types.BlockNonce{}) {
		return fmt.Errorf("post-merge block header requires zeroed block nonce field, but got: %s", hdr.Nonce)
	}
	if hdr.BaseFee == nil {
		return fmt.Errorf("post-merge block header requires EIP-1559 basefee field, but got %s", hdr.BaseFee)
	}
	if len(hdr.Extra) > 32 {
		return fmt.Errorf("post-merge block header requires 32 or less bytes of extra data, but got %d", len(hdr.Extra))
	}
	if hdr.UncleHash != types.EmptyUncleHash {
		return fmt.Errorf("post-merge block header requires uncle hash to be of empty uncle list, but got %s", hdr.UncleHash)
	}
	return nil
135 136
}

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
func (hdr *rpcHeader) computeBlockHash() common.Hash {
	gethHeader := types.Header{
		ParentHash:  hdr.ParentHash,
		UncleHash:   hdr.UncleHash,
		Coinbase:    hdr.Coinbase,
		Root:        hdr.Root,
		TxHash:      hdr.TxHash,
		ReceiptHash: hdr.ReceiptHash,
		Bloom:       types.Bloom(hdr.Bloom),
		Difficulty:  (*big.Int)(&hdr.Difficulty),
		Number:      new(big.Int).SetUint64(uint64(hdr.Number)),
		GasLimit:    uint64(hdr.GasLimit),
		GasUsed:     uint64(hdr.GasUsed),
		Time:        uint64(hdr.Time),
		Extra:       hdr.Extra,
		MixDigest:   hdr.MixDigest,
		Nonce:       hdr.Nonce,
		BaseFee:     (*big.Int)(hdr.BaseFee),
155
	}
156
	return gethHeader.Hash()
157 158
}

159 160 161 162 163
func (hdr *rpcHeader) Info(trustCache bool, mustBePostMerge bool) (*HeaderInfo, error) {
	if mustBePostMerge {
		if err := hdr.checkPostMerge(); err != nil {
			return nil, err
		}
164 165
	}
	if !trustCache {
166 167
		if computed := hdr.computeBlockHash(); computed != hdr.Hash {
			return nil, fmt.Errorf("failed to verify block hash: computed %s but RPC said %s", computed, hdr.Hash)
168 169
		}
	}
170 171 172 173 174 175 176 177 178 179 180 181 182

	info := HeaderInfo{
		hash:        hdr.Hash,
		parentHash:  hdr.ParentHash,
		coinbase:    hdr.Coinbase,
		root:        hdr.Root,
		number:      uint64(hdr.Number),
		time:        uint64(hdr.Time),
		mixDigest:   hdr.MixDigest,
		baseFee:     (*big.Int)(hdr.BaseFee),
		txHash:      hdr.TxHash,
		receiptHash: hdr.ReceiptHash,
	}
183 184 185
	return &info, nil
}

186 187
type rpcBlock struct {
	rpcHeader
188 189 190
	Transactions []*types.Transaction `json:"transactions"`
}

191 192 193 194 195 196 197 198
func (block *rpcBlock) verify() error {
	if computed := block.computeBlockHash(); computed != block.Hash {
		return fmt.Errorf("failed to verify block hash: computed %s but RPC said %s", computed, block.Hash)
	}
	if computed := types.DeriveSha(types.Transactions(block.Transactions), trie.NewStackTrie(nil)); block.TxHash != computed {
		return fmt.Errorf("failed to verify transactions list: computed %s but RPC said %s", computed, block.TxHash)
	}
	return nil
199 200
}

201 202 203 204 205 206 207 208 209 210
func (block *rpcBlock) Info(trustCache bool, mustBePostMerge bool) (*HeaderInfo, types.Transactions, error) {
	if mustBePostMerge {
		if err := block.checkPostMerge(); err != nil {
			return nil, nil, err
		}
	}
	if !trustCache {
		if err := block.verify(); err != nil {
			return nil, nil, err
		}
211 212 213
	}

	// verify the header data
214
	info, err := block.rpcHeader.Info(trustCache, mustBePostMerge)
215
	if err != nil {
216
		return nil, nil, fmt.Errorf("failed to verify block from RPC: %w", err)
217 218
	}

219 220 221 222 223 224 225 226 227 228
	return info, block.Transactions, nil
}

func (block *rpcBlock) ExecutionPayload(trustCache bool) (*eth.ExecutionPayload, error) {
	if err := block.checkPostMerge(); err != nil {
		return nil, err
	}
	if !trustCache {
		if err := block.verify(); err != nil {
			return nil, err
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
	var baseFee uint256.Int
	baseFee.SetFromBig((*big.Int)(block.BaseFee))

	// Unfortunately eth_getBlockByNumber either returns full transactions, or only tx-hashes.
	// There is no option for encoded transactions.
	opaqueTxs := make([]hexutil.Bytes, len(block.Transactions))
	for i, tx := range block.Transactions {
		data, err := tx.MarshalBinary()
		if err != nil {
			return nil, fmt.Errorf("failed to encode tx %d from RPC: %w", i, err)
		}
		opaqueTxs[i] = data
	}

	return &eth.ExecutionPayload{
		ParentHash:    block.ParentHash,
		FeeRecipient:  block.Coinbase,
		StateRoot:     eth.Bytes32(block.Root),
		ReceiptsRoot:  eth.Bytes32(block.ReceiptHash),
		LogsBloom:     block.Bloom,
		PrevRandao:    eth.Bytes32(block.MixDigest), // mix-digest field is used for prevRandao post-merge
		BlockNumber:   block.Number,
		GasLimit:      block.GasLimit,
		GasUsed:       block.GasUsed,
		Timestamp:     block.Time,
		ExtraData:     eth.BytesMax32(block.Extra),
		BaseFeePerGas: baseFee,
		BlockHash:     block.Hash,
		Transactions:  opaqueTxs,
	}, nil
261
}