source.go 10.2 KB
Newer Older
1 2 3 4 5 6 7 8
package l2

import (
	"context"
	"fmt"
	"math/big"
	"time"

9 10
	"github.com/ethereum-optimism/optimism/op-node/client"

11 12 13 14 15 16 17 18 19 20 21 22
	"github.com/ethereum/go-ethereum"

	"github.com/ethereum-optimism/optimism/op-node/eth"
	"github.com/ethereum-optimism/optimism/op-node/rollup"
	"github.com/ethereum-optimism/optimism/op-node/rollup/derive"
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/log"
	"github.com/ethereum/go-ethereum/rpc"
)

type Source struct {
23 24
	rpc     client.RPC    // raw RPC client. Used for the consensus namespace
	client  client.Client // go-ethereum's wrapper around the rpc client for the eth namespace
25 26 27 28
	genesis *rollup.Genesis
	log     log.Logger
}

29
func NewSource(l2Node client.RPC, l2Client client.Client, genesis *rollup.Genesis, log log.Logger) (*Source, error) {
30 31
	return &Source{
		rpc:     l2Node,
32
		client:  l2Client,
33 34 35 36 37 38 39 40 41
		genesis: genesis,
		log:     log,
	}, nil
}

func (s *Source) Close() {
	s.rpc.Close()
}

42
func (s *Source) PayloadByHash(ctx context.Context, hash common.Hash) (*eth.ExecutionPayload, error) {
43 44 45 46 47
	// TODO: we really do not need to parse every single tx and block detail, keeping transactions encoded is faster.
	block, err := s.client.BlockByHash(ctx, hash)
	if err != nil {
		return nil, fmt.Errorf("failed to retrieve L2 block by hash: %v", err)
	}
48
	payload, err := eth.BlockAsPayload(block)
49 50 51 52 53 54
	if err != nil {
		return nil, fmt.Errorf("failed to read L2 block as payload: %w", err)
	}
	return payload, nil
}

55
func (s *Source) PayloadByNumber(ctx context.Context, number uint64) (*eth.ExecutionPayload, error) {
56
	// TODO: we really do not need to parse every single tx and block detail, keeping transactions encoded is faster.
57
	block, err := s.client.BlockByNumber(ctx, big.NewInt(int64(number)))
58 59 60
	if err != nil {
		return nil, fmt.Errorf("failed to retrieve L2 block by number: %v", err)
	}
61
	payload, err := eth.BlockAsPayload(block)
62 63 64 65 66 67 68 69 70
	if err != nil {
		return nil, fmt.Errorf("failed to read L2 block as payload: %w", err)
	}
	return payload, nil
}

// ForkchoiceUpdate updates the forkchoice on the execution client. If attributes is not nil, the engine client will also begin building a block
// based on attributes after the new head block and return the payload ID.
// May return an error in ForkChoiceResult, but the error is marshalled into the error return
71
func (s *Source) ForkchoiceUpdate(ctx context.Context, fc *eth.ForkchoiceState, attributes *eth.PayloadAttributes) (*eth.ForkchoiceUpdatedResult, error) {
72
	e := s.log.New("state", fc, "attr", attributes)
73
	e.Trace("Sharing forkchoice-updated signal")
74 75
	fcCtx, cancel := context.WithTimeout(ctx, time.Second*5)
	defer cancel()
76
	var result eth.ForkchoiceUpdatedResult
77 78
	err := s.rpc.CallContext(fcCtx, &result, "engine_forkchoiceUpdatedV1", fc, attributes)
	if err == nil {
79
		e.Trace("Shared forkchoice-updated signal")
80
		if attributes != nil {
81
			e.Trace("Received payload id", "payloadId", result.PayloadID)
82
		}
83
		return &result, nil
84 85 86
	} else {
		e = e.New("err", err)
		if rpcErr, ok := err.(rpc.Error); ok {
87
			code := eth.ErrorCode(rpcErr.ErrorCode())
88 89 90 91
			e.Warn("Unexpected error code in forkchoice-updated response", "code", code)
		} else {
			e.Error("Failed to share forkchoice-updated signal")
		}
92
		return nil, err
93 94 95 96
	}
}

// ExecutePayload executes a built block on the execution engine and returns an error if it was not successful.
97
func (s *Source) NewPayload(ctx context.Context, payload *eth.ExecutionPayload) (*eth.PayloadStatusV1, error) {
98
	e := s.log.New("block_hash", payload.BlockHash)
99
	e.Trace("sending payload for execution")
100 101 102

	execCtx, cancel := context.WithTimeout(ctx, time.Second*5)
	defer cancel()
103
	var result eth.PayloadStatusV1
104
	err := s.rpc.CallContext(execCtx, &result, "engine_newPayloadV1", payload)
105
	e.Trace("Received payload execution result", "status", result.Status, "latestValidHash", result.LatestValidHash, "message", result.ValidationError)
106 107
	if err != nil {
		e.Error("Payload execution failed", "err", err)
108
		return nil, fmt.Errorf("failed to execute payload: %v", err)
109
	}
110
	return &result, nil
111 112 113
}

// GetPayload gets the execution payload associated with the PayloadId
114
func (s *Source) GetPayload(ctx context.Context, payloadId eth.PayloadID) (*eth.ExecutionPayload, error) {
115
	e := s.log.New("payload_id", payloadId)
116
	e.Trace("getting payload")
117
	var result eth.ExecutionPayload
118 119
	err := s.rpc.CallContext(ctx, &result, "engine_getPayloadV1", payloadId)
	if err != nil {
120
		e = e.New("payload_id", payloadId, "err", err)
121
		if rpcErr, ok := err.(rpc.Error); ok {
122 123
			code := eth.ErrorCode(rpcErr.ErrorCode())
			if code != eth.UnavailablePayload {
124 125 126 127 128 129 130 131 132
				e.Warn("unexpected error code in get-payload response", "code", code)
			} else {
				e.Warn("unavailable payload in get-payload request")
			}
		} else {
			e.Error("failed to get payload")
		}
		return nil, err
	}
133
	e.Trace("Received payload")
134 135 136
	return &result, nil
}

137 138 139 140 141 142 143 144 145 146
// L2BlockRefHead returns the canonical block and parent ids.
func (s *Source) L2BlockRefHead(ctx context.Context) (eth.L2BlockRef, error) {
	block, err := s.client.BlockByNumber(ctx, nil)
	if err != nil {
		// w%: wrap the error, we still need to detect if a canonical block is not found, a.k.a. end of chain.
		return eth.L2BlockRef{}, fmt.Errorf("failed to determine block-hash of head, could not get header: %w", err)
	}
	return blockToBlockRef(block, s.genesis)
}

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
// L2BlockRefByNumber returns the canonical block and parent ids.
func (s *Source) L2BlockRefByNumber(ctx context.Context, l2Num *big.Int) (eth.L2BlockRef, error) {
	block, err := s.client.BlockByNumber(ctx, l2Num)
	if err != nil {
		// w%: wrap the error, we still need to detect if a canonical block is not found, a.k.a. end of chain.
		return eth.L2BlockRef{}, fmt.Errorf("failed to determine block-hash of height %v, could not get header: %w", l2Num, err)
	}
	return blockToBlockRef(block, s.genesis)
}

// L2BlockRefByHash returns the block & parent ids based on the supplied hash. The returned BlockRef may not be in the canonical chain
func (s *Source) L2BlockRefByHash(ctx context.Context, l2Hash common.Hash) (eth.L2BlockRef, error) {
	block, err := s.client.BlockByHash(ctx, l2Hash)
	if err != nil {
		// w%: wrap the error, we still need to detect if a canonical block is not found, a.k.a. end of chain.
		return eth.L2BlockRef{}, fmt.Errorf("failed to determine block-hash of height %v, could not get header: %w", l2Hash, err)
	}
	return blockToBlockRef(block, s.genesis)
}

// blockToBlockRef extracts the essential L2BlockRef information from a block,
// falling back to genesis information if necessary.
func blockToBlockRef(block *types.Block, genesis *rollup.Genesis) (eth.L2BlockRef, error) {
	var l1Origin eth.BlockID
	var sequenceNumber uint64
	if block.NumberU64() == genesis.L2.Number {
		if block.Hash() != genesis.L2.Hash {
			return eth.L2BlockRef{}, fmt.Errorf("expected L2 genesis hash to match L2 block at genesis block number %d: %s <> %s", genesis.L2.Number, block.Hash(), genesis.L2.Hash)
		}
		l1Origin = genesis.L1
		sequenceNumber = 0
	} else {
		txs := block.Transactions()
		if len(txs) == 0 {
			return eth.L2BlockRef{}, fmt.Errorf("l2 block is missing L1 info deposit tx, block hash: %s", block.Hash())
		}
		tx := txs[0]
		if tx.Type() != types.DepositTxType {
			return eth.L2BlockRef{}, fmt.Errorf("first block tx has unexpected tx type: %d", tx.Type())
		}
		info, err := derive.L1InfoDepositTxData(tx.Data())
		if err != nil {
			return eth.L2BlockRef{}, fmt.Errorf("failed to parse L1 info deposit tx from L2 block: %v", err)
		}
		l1Origin = eth.BlockID{Hash: info.BlockHash, Number: info.Number}
		sequenceNumber = info.SequenceNumber
	}
	return eth.L2BlockRef{
		Hash:           block.Hash(),
		Number:         block.NumberU64(),
		ParentHash:     block.ParentHash(),
		Time:           block.Time(),
		L1Origin:       l1Origin,
		SequenceNumber: sequenceNumber,
	}, nil
}

type ReadOnlySource struct {
205 206
	rpc     client.RPC    // raw RPC client. Used for methods that do not already have bindings
	client  client.Client // go-ethereum's wrapper around the rpc client for the eth namespace
207 208 209 210
	genesis *rollup.Genesis
	log     log.Logger
}

211
func NewReadOnlySource(l2Node client.RPC, l2Client client.Client, genesis *rollup.Genesis, log log.Logger) (*ReadOnlySource, error) {
212 213
	return &ReadOnlySource{
		rpc:     l2Node,
214
		client:  l2Client,
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
		genesis: genesis,
		log:     log,
	}, nil
}

// TODO: de-duplicate Source and ReadOnlySource.
// We should really have a L1-downloader like binding that is more configurable and has caching.

// L2BlockRefByNumber returns the canonical block and parent ids.
func (s *ReadOnlySource) L2BlockRefByNumber(ctx context.Context, l2Num *big.Int) (eth.L2BlockRef, error) {
	block, err := s.client.BlockByNumber(ctx, l2Num)
	if err != nil {
		// w%: wrap the error, we still need to detect if a canonical block is not found, a.k.a. end of chain.
		return eth.L2BlockRef{}, fmt.Errorf("failed to determine block-hash of height %v, could not get header: %w", l2Num, err)
	}
	return blockToBlockRef(block, s.genesis)
}

// L2BlockRefByHash returns the block & parent ids based on the supplied hash. The returned BlockRef may not be in the canonical chain
func (s *ReadOnlySource) L2BlockRefByHash(ctx context.Context, l2Hash common.Hash) (eth.L2BlockRef, error) {
	block, err := s.client.BlockByHash(ctx, l2Hash)
	if err != nil {
		// w%: wrap the error, we still need to detect if a canonical block is not found, a.k.a. end of chain.
		return eth.L2BlockRef{}, fmt.Errorf("failed to determine block-hash of height %v, could not get header: %w", l2Hash, err)
	}
	return blockToBlockRef(block, s.genesis)
}

func (s *ReadOnlySource) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) {
	return s.client.BlockByNumber(ctx, number)
}

func (s *ReadOnlySource) GetBlockHeader(ctx context.Context, blockTag string) (*types.Header, error) {
	var head *types.Header
	err := s.rpc.CallContext(ctx, &head, "eth_getBlockByNumber", blockTag, false)
	return head, err
}

253 254
func (s *ReadOnlySource) GetProof(ctx context.Context, address common.Address, blockTag string) (*eth.AccountResult, error) {
	var getProofResponse *eth.AccountResult
255 256 257 258 259 260
	err := s.rpc.CallContext(ctx, &getProofResponse, "eth_getProof", address, []common.Hash{}, blockTag)
	if err == nil && getProofResponse == nil {
		err = ethereum.NotFound
	}
	return getProofResponse, err
}