engine.go 14.1 KB
Newer Older
1 2 3 4
package engine

import (
	"context"
5
	"encoding/json"
6
	"errors"
7
	"fmt"
8
	"io"
9
	"math/big"
10
	"strings"
11 12
	"time"

13
	"github.com/ethereum/go-ethereum/beacon/engine"
14 15 16 17 18 19 20
	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/common/hexutil"
	"github.com/ethereum/go-ethereum/core/types"
	"github.com/ethereum/go-ethereum/log"
	"github.com/ethereum/go-ethereum/node"
	"github.com/ethereum/go-ethereum/rpc"

Sabnock01's avatar
Sabnock01 committed
21
	"github.com/ethereum-optimism/optimism/op-service/client"
22
	"github.com/ethereum-optimism/optimism/op-service/eth"
23 24
)

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
type PayloadAttributesV2 struct {
	Timestamp             uint64              `json:"timestamp"`
	Random                common.Hash         `json:"prevRandao"`
	SuggestedFeeRecipient common.Address      `json:"suggestedFeeRecipient"`
	Withdrawals           []*types.Withdrawal `json:"withdrawals"`
}

func (p PayloadAttributesV2) MarshalJSON() ([]byte, error) {
	type PayloadAttributes struct {
		Timestamp             hexutil.Uint64      `json:"timestamp"             gencodec:"required"`
		Random                common.Hash         `json:"prevRandao"            gencodec:"required"`
		SuggestedFeeRecipient common.Address      `json:"suggestedFeeRecipient" gencodec:"required"`
		Withdrawals           []*types.Withdrawal `json:"withdrawals"`
	}
	var enc PayloadAttributes
	enc.Timestamp = hexutil.Uint64(p.Timestamp)
	enc.Random = p.Random
	enc.SuggestedFeeRecipient = p.SuggestedFeeRecipient
	enc.Withdrawals = make([]*types.Withdrawal, 0)
	return json.Marshal(&enc)
}

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
func DialClient(ctx context.Context, endpoint string, jwtSecret [32]byte) (client.RPC, error) {
	auth := node.NewJWTAuth(jwtSecret)

	rpcClient, err := rpc.DialOptions(ctx, endpoint, rpc.WithHTTPAuth(auth))
	if err != nil {
		return nil, fmt.Errorf("failed to dial engine endpoint: %w", err)
	}
	return client.NewBaseRPCClient(rpcClient), nil
}

type RPCBlock struct {
	types.Header
	Transactions []*types.Transaction `json:"transactions"`
}

func getBlock(ctx context.Context, client client.RPC, method string, tag string) (*types.Block, error) {
	var bl *RPCBlock
	err := client.CallContext(ctx, &bl, method, tag, true)
	if err != nil {
		return nil, err
	}
	return types.NewBlockWithHeader(&bl.Header).WithBody(bl.Transactions, nil), nil
}

func getHeader(ctx context.Context, client client.RPC, method string, tag string) (*types.Header, error) {
	var header *types.Header
	err := client.CallContext(ctx, &header, method, tag, false)
	if err != nil {
		return nil, err
	}
	return header, nil
}

func headSafeFinalized(ctx context.Context, client client.RPC) (head *types.Block, safe, finalized *types.Header, err error) {
	head, err = getBlock(ctx, client, "eth_getBlockByNumber", "latest")
	if err != nil {
		return nil, nil, nil, fmt.Errorf("failed to get block: %w", err)
	}
	safe, err = getHeader(ctx, client, "eth_getBlockByNumber", "safe")
	if err != nil {
		return head, nil, nil, fmt.Errorf("failed to get safe block: %w", err)
	}
	finalized, err = getHeader(ctx, client, "eth_getBlockByNumber", "finalized")
	if err != nil {
		return head, safe, nil, fmt.Errorf("failed to get finalized block: %w", err)
	}
	return head, safe, finalized, nil
}

96 97
func insertBlock(ctx context.Context, client client.RPC, payload *engine.ExecutableData) error {
	var payloadResult *engine.PayloadStatusV1
98
	if err := client.CallContext(ctx, &payloadResult, "engine_newPayloadV2", payload); err != nil {
99 100 101 102 103 104 105 106 107
		return fmt.Errorf("failed to insert block %d: %w", payload.Number, err)
	}
	if payloadResult.Status != string(eth.ExecutionValid) {
		return fmt.Errorf("block insertion was not valid: %v", payloadResult.ValidationError)
	}
	return nil
}

func updateForkchoice(ctx context.Context, client client.RPC, head, safe, finalized common.Hash) error {
108
	var post engine.ForkChoiceResponse
109
	if err := client.CallContext(ctx, &post, "engine_forkchoiceUpdatedV2",
110
		engine.ForkchoiceStateV1{
111 112 113 114 115 116 117 118 119 120 121 122 123
			HeadBlockHash:      head,
			SafeBlockHash:      safe,
			FinalizedBlockHash: finalized,
		}, nil); err != nil {
		return fmt.Errorf("failed to set forkchoice with new block %s: %w", head, err)
	}
	if post.PayloadStatus.Status != string(eth.ExecutionValid) {
		return fmt.Errorf("post-block forkchoice update was not valid: %v", post.PayloadStatus.ValidationError)
	}
	return nil
}

type BlockBuildingSettings struct {
124 125 126
	BlockTime uint64
	// skip a block; timestamps will still increase in multiples of BlockTime like L1, but there may be gaps.
	AllowGaps    bool
127 128 129 130 131
	Random       common.Hash
	FeeRecipient common.Address
	BuildTime    time.Duration
}

132
func BuildBlock(ctx context.Context, client client.RPC, status *StatusData, settings *BlockBuildingSettings) (*engine.ExecutableData, error) {
133 134 135 136 137 138 139
	timestamp := status.Head.Time + settings.BlockTime
	if settings.AllowGaps {
		now := uint64(time.Now().Unix())
		if now > timestamp {
			timestamp = now - ((now - timestamp) % settings.BlockTime)
		}
	}
140
	var pre engine.ForkChoiceResponse
141
	if err := client.CallContext(ctx, &pre, "engine_forkchoiceUpdatedV2",
142
		engine.ForkchoiceStateV1{
143 144 145
			HeadBlockHash:      status.Head.Hash,
			SafeBlockHash:      status.Safe.Hash,
			FinalizedBlockHash: status.Finalized.Hash,
146
		}, PayloadAttributesV2{
147
			Timestamp:             timestamp,
148 149 150
			Random:                settings.Random,
			SuggestedFeeRecipient: settings.FeeRecipient,
		}); err != nil {
151
		return nil, fmt.Errorf("failed to set forkchoice when building new block: %w", err)
152 153 154 155 156 157 158 159 160 161 162 163
	}
	if pre.PayloadStatus.Status != string(eth.ExecutionValid) {
		return nil, fmt.Errorf("pre-block forkchoice update was not valid: %v", pre.PayloadStatus.ValidationError)
	}

	// wait some time for the block to get built
	select {
	case <-ctx.Done():
		return nil, ctx.Err()
	case <-time.After(settings.BuildTime):
	}

164 165
	var payload *engine.ExecutionPayloadEnvelope
	if err := client.CallContext(ctx, &payload, "engine_getPayloadV2", pre.PayloadID); err != nil {
166 167 168
		return nil, fmt.Errorf("failed to get payload %v, %d time after instructing engine to build it: %w", pre.PayloadID, settings.BuildTime, err)
	}

169
	if err := insertBlock(ctx, client, payload.ExecutionPayload); err != nil {
170 171
		return nil, err
	}
172
	if err := updateForkchoice(ctx, client, payload.ExecutionPayload.BlockHash, status.Safe.Hash, status.Finalized.Hash); err != nil {
173 174 175
		return nil, err
	}

176
	return payload.ExecutionPayload, nil
177 178 179 180 181 182
}

func Auto(ctx context.Context, metrics Metricer, client client.RPC, log log.Logger, shutdown <-chan struct{}, settings *BlockBuildingSettings) error {
	ticker := time.NewTicker(time.Millisecond * 100)
	defer ticker.Stop()

183
	var lastPayload *engine.ExecutableData
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
	var buildErr error
	for {
		select {
		case <-shutdown:
			log.Info("shutting down")
			return nil
		case <-ctx.Done():
			log.Info("context closed", "err", ctx.Err())
			return ctx.Err()
		case now := <-ticker.C:
			blockTime := time.Duration(settings.BlockTime) * time.Second
			lastTime := uint64(0)
			if lastPayload != nil {
				lastTime = lastPayload.Timestamp
			}
			buildTriggerTime := time.Unix(int64(lastTime), 0).Add(blockTime - settings.BuildTime)

			if lastPayload == nil || now.After(buildTriggerTime) {
				buildTime := settings.BuildTime
				// don't waste time on trying to include txs if we are lagging behind at least a block,
				// but don't go ham if we are failing to build blocks already.
				if buildErr == nil && now.After(buildTriggerTime.Add(blockTime)) {
					buildTime = 10 * time.Millisecond
				}
				buildErr = nil
				status, err := Status(ctx, client)
				if err != nil {
					log.Error("failed to get pre-block engine status", "err", err)
					metrics.RecordBlockFail()
					buildErr = err
					continue
				}
				log.Info("status", "head", status.Head, "safe", status.Safe, "finalized", status.Finalized,
					"head_time", status.Head.Time, "txs", status.Txs, "gas", status.Gas, "basefee", status.Gas)

				// On a mocked "beacon epoch transition", update finalization and justification checkpoints.
				// There are no gap slots, so we just go back 32 blocks.
				if status.Head.Number%32 == 0 {
					if status.Safe.Number+32 <= status.Head.Number {
						safe, err := getHeader(ctx, client, "eth_getBlockByNumber", hexutil.Uint64(status.Head.Number-32).String())
						if err != nil {
							buildErr = err
							log.Error("failed to find block for new safe block progress", "err", err)
							continue
						}
						status.Safe = eth.L1BlockRef{Hash: safe.Hash(), Number: safe.Number.Uint64(), Time: safe.Time, ParentHash: safe.ParentHash}
					}
					if status.Finalized.Number+32 <= status.Safe.Number {
						finalized, err := getHeader(ctx, client, "eth_getBlockByNumber", hexutil.Uint64(status.Safe.Number-32).String())
						if err != nil {
							buildErr = err
							log.Error("failed to find block for new finalized block progress", "err", err)
							continue
						}
						status.Finalized = eth.L1BlockRef{Hash: finalized.Hash(), Number: finalized.Number.Uint64(), Time: finalized.Time, ParentHash: finalized.ParentHash}
					}
				}

				payload, err := BuildBlock(ctx, client, status, &BlockBuildingSettings{
					BlockTime:    settings.BlockTime,
244
					AllowGaps:    settings.AllowGaps,
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
					Random:       settings.Random,
					FeeRecipient: settings.FeeRecipient,
					BuildTime:    buildTime,
				})
				if err != nil {
					buildErr = err
					log.Error("failed to produce block", "err", err)
					metrics.RecordBlockFail()
				} else {
					lastPayload = payload
					log.Info("created block", "hash", payload.BlockHash, "number", payload.Number,
						"timestamp", payload.Timestamp, "txs", len(payload.Transactions),
						"gas", payload.GasUsed, "basefee", payload.BaseFeePerGas)
					basefee, _ := new(big.Float).SetInt(payload.BaseFeePerGas).Float64()
					metrics.RecordBlockStats(payload.BlockHash, payload.Number, payload.Timestamp, uint64(len(payload.Transactions)), payload.GasUsed, basefee)
				}
			}
		}
	}
}

type StatusData struct {
	Head      eth.L1BlockRef `json:"head"`
	Safe      eth.L1BlockRef `json:"safe"`
	Finalized eth.L1BlockRef `json:"finalized"`
	Txs       uint64         `json:"txs"`
	Gas       uint64         `json:"gas"`
	StateRoot common.Hash    `json:"stateRoot"`
	BaseFee   *big.Int       `json:"baseFee"`
}

func Status(ctx context.Context, client client.RPC) (*StatusData, error) {
	head, safe, finalized, err := headSafeFinalized(ctx, client)
	if err != nil {
		return nil, err
	}
	return &StatusData{
		Head:      eth.L1BlockRef{Hash: head.Hash(), Number: head.NumberU64(), Time: head.Time(), ParentHash: head.ParentHash()},
		Safe:      eth.L1BlockRef{Hash: safe.Hash(), Number: safe.Number.Uint64(), Time: safe.Time, ParentHash: safe.ParentHash},
		Finalized: eth.L1BlockRef{Hash: finalized.Hash(), Number: finalized.Number.Uint64(), Time: finalized.Time, ParentHash: finalized.ParentHash},
		Txs:       uint64(len(head.Transactions())),
		Gas:       head.GasUsed(),
		StateRoot: head.Root(),
		BaseFee:   head.BaseFee(),
	}, nil
}

// Copy takes the forkchoice state of copyFrom, and applies it to copyTo, and inserts the head-block.
// The destination engine should then start syncing to this new chain if it has peers to do so.
func Copy(ctx context.Context, copyFrom client.RPC, copyTo client.RPC) error {
	copyHead, copySafe, copyFinalized, err := headSafeFinalized(ctx, copyFrom)
	if err != nil {
		return err
	}
299
	payloadEnv := engine.BlockToExecutableData(copyHead, nil, nil)
300 301 302
	if err := updateForkchoice(ctx, copyTo, copyHead.ParentHash(), copySafe.Hash(), copyFinalized.Hash()); err != nil {
		return err
	}
303
	payload := payloadEnv.ExecutionPayload
304 305 306 307 308 309 310 311
	if err := insertBlock(ctx, copyTo, payload); err != nil {
		return err
	}
	if err := updateForkchoice(ctx, copyTo, payload.BlockHash, copySafe.Hash(), copyFinalized.Hash()); err != nil {
		return err
	}
	return nil
}
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

func SetForkchoice(ctx context.Context, client client.RPC, finalizedNum, safeNum, unsafeNum uint64) error {
	if unsafeNum < safeNum {
		return fmt.Errorf("cannot set unsafe (%d) < safe (%d)", unsafeNum, safeNum)
	}
	if safeNum < finalizedNum {
		return fmt.Errorf("cannot set safe (%d) < finalized (%d)", safeNum, finalizedNum)
	}
	head, err := getHeader(ctx, client, "eth_getBlockByNumber", "latest")
	if err != nil {
		return fmt.Errorf("failed to get latest block: %w", err)
	}
	if unsafeNum > head.Number.Uint64() {
		return fmt.Errorf("cannot set unsafe (%d) > latest (%d)", unsafeNum, head.Number.Uint64())
	}
	finalizedHeader, err := getHeader(ctx, client, "eth_getBlockByNumber", hexutil.Uint64(finalizedNum).String())
	if err != nil {
		return fmt.Errorf("failed to get block %d to mark finalized: %w", finalizedNum, err)
	}
	safeHeader, err := getHeader(ctx, client, "eth_getBlockByNumber", hexutil.Uint64(safeNum).String())
	if err != nil {
		return fmt.Errorf("failed to get block %d to mark safe: %w", safeNum, err)
	}
	if err := updateForkchoice(ctx, client, head.Hash(), safeHeader.Hash(), finalizedHeader.Hash()); err != nil {
		return fmt.Errorf("failed to update forkchoice: %w", err)
	}
	return nil
}

func RawJSONInteraction(ctx context.Context, client client.RPC, method string, args []string, input io.Reader, output io.Writer) error {
	var params []any
	if input != nil {
		r := json.NewDecoder(input)
		for {
			var param json.RawMessage
			if err := r.Decode(&param); err != nil {
				if errors.Is(err, io.EOF) {
					break
				}
				return fmt.Errorf("unexpected error while reading json params: %w", err)
			}
			params = append(params, param)
		}
	} else {
		for _, arg := range args {
			// add quotes to unquoted strings, but not to other json data
			if isUnquotedJsonString(arg) {
				arg = fmt.Sprintf("%q", arg)
			}
			params = append(params, json.RawMessage(arg))
		}
	}
	var result json.RawMessage
	if err := client.CallContext(ctx, &result, method, params...); err != nil {
		return fmt.Errorf("failed RPC call: %w", err)
	}
	if _, err := output.Write(result); err != nil {
		return fmt.Errorf("failed to write RPC output: %w", err)
	}
	return nil
}

func isUnquotedJsonString(v string) bool {
	v = strings.TrimSpace(v)
	// check if empty string (must get quotes)
	if len(v) == 0 {
		return true
	}
	// check if special value
	switch v {
	case "null", "true", "false":
		return false
	}
	// check if it looks like a json structure
	switch v[0] {
	case '[', '{', '"':
		return false
	}
	// check if a number
	var n json.Number
	if err := json.Unmarshal([]byte(v), &n); err == nil {
		return false
	}
	return true
}