types.go 13.6 KB
Newer Older
1 2 3
package rollup

import (
4
	"context"
5 6 7
	"errors"
	"fmt"
	"math/big"
8
	"time"
9 10 11

	"github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/core/types"
12
	"github.com/ethereum/go-ethereum/log"
13
	"github.com/ethereum/go-ethereum/params"
14

15
	"github.com/ethereum-optimism/optimism/op-service/eth"
16 17
)

18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
var (
	ErrBlockTimeZero                 = errors.New("block time cannot be 0")
	ErrMissingChannelTimeout         = errors.New("channel timeout must be set, this should cover at least a L1 block time")
	ErrInvalidSeqWindowSize          = errors.New("sequencing window size must at least be 2")
	ErrMissingGenesisL1Hash          = errors.New("genesis L1 hash cannot be empty")
	ErrMissingGenesisL2Hash          = errors.New("genesis L2 hash cannot be empty")
	ErrGenesisHashesSame             = errors.New("achievement get! rollup inception: L1 and L2 genesis cannot be the same")
	ErrMissingGenesisL2Time          = errors.New("missing L2 genesis time")
	ErrMissingBatcherAddr            = errors.New("missing genesis system config batcher address")
	ErrMissingOverhead               = errors.New("missing genesis system config overhead")
	ErrMissingScalar                 = errors.New("missing genesis system config scalar")
	ErrMissingGasLimit               = errors.New("missing genesis system config gas limit")
	ErrMissingBatchInboxAddress      = errors.New("missing batch inbox address")
	ErrMissingDepositContractAddress = errors.New("missing deposit contract address")
	ErrMissingL1ChainID              = errors.New("L1 chain ID must not be nil")
	ErrMissingL2ChainID              = errors.New("L2 chain ID must not be nil")
	ErrChainIDsSame                  = errors.New("L1 and L2 chain IDs must be different")
	ErrL1ChainIDNotPositive          = errors.New("L1 chain ID must be non-zero and positive")
	ErrL2ChainIDNotPositive          = errors.New("L2 chain ID must be non-zero and positive")
)

39 40 41 42 43 44 45
type Genesis struct {
	// The L1 block that the rollup starts *after* (no derived transactions)
	L1 eth.BlockID `json:"l1"`
	// The L2 block the rollup starts from (no transactions, pre-configured state)
	L2 eth.BlockID `json:"l2"`
	// Timestamp of L2 block
	L2Time uint64 `json:"l2_time"`
46 47 48 49
	// Initial system configuration values.
	// The L2 genesis block may not include transactions, and thus cannot encode the config values,
	// unlike later L2 blocks.
	SystemConfig eth.SystemConfig `json:"system_config"`
50 51 52 53 54 55 56 57 58 59 60 61 62
}

type Config struct {
	// Genesis anchor point of the rollup
	Genesis Genesis `json:"genesis"`
	// Seconds per L2 block
	BlockTime uint64 `json:"block_time"`
	// Sequencer batches may not be more than MaxSequencerDrift seconds after
	// the L1 timestamp of the sequencing window end.
	//
	// Note: When L1 has many 1 second consecutive blocks, and L2 grows at fixed 2 seconds,
	// the L2 time may still grow beyond this difference.
	MaxSequencerDrift uint64 `json:"max_sequencer_drift"`
63
	// Number of epochs (L1 blocks) per sequencing window, including the epoch L1 origin block itself
64
	SeqWindowSize uint64 `json:"seq_window_size"`
65
	// Number of L1 blocks between when a channel can be opened and when it must be closed by.
protolambda's avatar
protolambda committed
66
	ChannelTimeout uint64 `json:"channel_timeout"`
67 68 69 70 71
	// Required to verify L1 signatures
	L1ChainID *big.Int `json:"l1_chain_id"`
	// Required to identify the L2 network and create p2p signatures unique for this chain.
	L2ChainID *big.Int `json:"l2_chain_id"`

72 73 74 75 76 77
	// RegolithTime sets the activation time of the Regolith network-upgrade:
	// a pre-mainnet Bedrock change that addresses findings of the Sherlock contest related to deposit attributes.
	// "Regolith" is the loose deposited rock that sits on top of Bedrock.
	// Active if RegolithTime != nil && L2 block timestamp >= *RegolithTime, inactive otherwise.
	RegolithTime *uint64 `json:"regolith_time,omitempty"`

78 79 80 81
	// CanyonTime  sets the activation time of the next network upgrade.
	// Active if CanyonTime != nil && L2 block timestamp >= *CanyonTime, inactive otherwise.
	CanyonTime *uint64 `json:"canyon_time,omitempty"`

82 83
	SpanBatchTime *uint64 `json:"span_batch_time,omitempty"`

84 85 86
	// Note: below addresses are part of the block-derivation process,
	// and required to be the same network-wide to stay in consensus.

87
	// L1 address that batches are sent to.
88 89 90
	BatchInboxAddress common.Address `json:"batch_inbox_address"`
	// L1 Deposit Contract Address
	DepositContractAddress common.Address `json:"deposit_contract_address"`
91 92
	// L1 System Config Address
	L1SystemConfigAddress common.Address `json:"l1_system_config_address"`
93 94 95

	// L1 address that declares the protocol versions, optional (Beta feature)
	ProtocolVersionsAddress common.Address `json:"protocol_versions_address,omitempty"`
96 97
}

Andreas Bigger's avatar
Andreas Bigger committed
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
// ValidateL1Config checks L1 config variables for errors.
func (cfg *Config) ValidateL1Config(ctx context.Context, client L1Client) error {
	// Validate the L1 Client Chain ID
	if err := cfg.CheckL1ChainID(ctx, client); err != nil {
		return err
	}

	// Validate the Rollup L1 Genesis Blockhash
	if err := cfg.CheckL1GenesisBlockHash(ctx, client); err != nil {
		return err
	}

	return nil
}

// ValidateL2Config checks L2 config variables for errors.
func (cfg *Config) ValidateL2Config(ctx context.Context, client L2Client) error {
	// Validate the L2 Client Chain ID
	if err := cfg.CheckL2ChainID(ctx, client); err != nil {
		return err
	}

	// Validate the Rollup L2 Genesis Blockhash
	if err := cfg.CheckL2GenesisBlockHash(ctx, client); err != nil {
		return err
	}

	return nil
}

Danyal Prout's avatar
Danyal Prout committed
128 129 130 131
func (cfg *Config) TimestampForBlock(blockNumber uint64) uint64 {
	return cfg.Genesis.L2Time + ((blockNumber - cfg.Genesis.L2.Number) * cfg.BlockTime)
}

132 133 134 135 136 137 138 139 140 141 142 143 144 145
func (cfg *Config) TargetBlockNumber(timestamp uint64) (num uint64, err error) {
	// subtract genesis time from timestamp to get the time elapsed since genesis, and then divide that
	// difference by the block time to get the expected L2 block number at the current time. If the
	// unsafe head does not have this block number, then there is a gap in the queue.
	genesisTimestamp := cfg.Genesis.L2Time
	if timestamp < genesisTimestamp {
		return 0, fmt.Errorf("did not reach genesis time (%d) yet", genesisTimestamp)
	}
	wallClockGenesisDiff := timestamp - genesisTimestamp
	// Note: round down, we should not request blocks into the future.
	blocksSinceGenesis := wallClockGenesisDiff / cfg.BlockTime
	return cfg.Genesis.L2.Number + blocksSinceGenesis, nil
}

146
type L1Client interface {
Andreas Bigger's avatar
Andreas Bigger committed
147
	ChainID(context.Context) (*big.Int, error)
148 149 150 151 152
	L1BlockRefByNumber(context.Context, uint64) (eth.L1BlockRef, error)
}

// CheckL1ChainID checks that the configured L1 chain ID matches the client's chain ID.
func (cfg *Config) CheckL1ChainID(ctx context.Context, client L1Client) error {
Andreas Bigger's avatar
Andreas Bigger committed
153
	id, err := client.ChainID(ctx)
154
	if err != nil {
155
		return fmt.Errorf("failed to get L1 chain ID: %w", err)
156
	}
157
	if cfg.L1ChainID.Cmp(id) != 0 {
158
		return fmt.Errorf("incorrect L1 RPC chain id %d, expected %d", id, cfg.L1ChainID)
159 160 161 162 163 164 165 166
	}
	return nil
}

// CheckL1GenesisBlockHash checks that the configured L1 genesis block hash is valid for the given client.
func (cfg *Config) CheckL1GenesisBlockHash(ctx context.Context, client L1Client) error {
	l1GenesisBlockRef, err := client.L1BlockRefByNumber(ctx, cfg.Genesis.L1.Number)
	if err != nil {
167
		return fmt.Errorf("failed to get L1 genesis blockhash: %w", err)
168 169
	}
	if l1GenesisBlockRef.Hash != cfg.Genesis.L1.Hash {
170
		return fmt.Errorf("incorrect L1 genesis block hash %s, expected %s", l1GenesisBlockRef.Hash, cfg.Genesis.L1.Hash)
171 172 173 174 175
	}
	return nil
}

type L2Client interface {
Andreas Bigger's avatar
Andreas Bigger committed
176
	ChainID(context.Context) (*big.Int, error)
177 178 179 180 181
	L2BlockRefByNumber(context.Context, uint64) (eth.L2BlockRef, error)
}

// CheckL2ChainID checks that the configured L2 chain ID matches the client's chain ID.
func (cfg *Config) CheckL2ChainID(ctx context.Context, client L2Client) error {
Andreas Bigger's avatar
Andreas Bigger committed
182
	id, err := client.ChainID(ctx)
183
	if err != nil {
184
		return fmt.Errorf("failed to get L2 chain ID: %w", err)
185
	}
186
	if cfg.L2ChainID.Cmp(id) != 0 {
187
		return fmt.Errorf("incorrect L2 RPC chain id %d, expected %d", id, cfg.L2ChainID)
188 189 190 191 192 193 194 195
	}
	return nil
}

// CheckL2GenesisBlockHash checks that the configured L2 genesis block hash is valid for the given client.
func (cfg *Config) CheckL2GenesisBlockHash(ctx context.Context, client L2Client) error {
	l2GenesisBlockRef, err := client.L2BlockRefByNumber(ctx, cfg.Genesis.L2.Number)
	if err != nil {
196
		return fmt.Errorf("failed to get L2 genesis blockhash: %w", err)
197 198
	}
	if l2GenesisBlockRef.Hash != cfg.Genesis.L2.Hash {
199
		return fmt.Errorf("incorrect L2 genesis block hash %s, expected %s", l2GenesisBlockRef.Hash, cfg.Genesis.L2.Hash)
200 201 202 203
	}
	return nil
}

204 205 206
// Check verifies that the given configuration makes sense
func (cfg *Config) Check() error {
	if cfg.BlockTime == 0 {
207
		return ErrBlockTimeZero
208
	}
209
	if cfg.ChannelTimeout == 0 {
210
		return ErrMissingChannelTimeout
211
	}
212
	if cfg.SeqWindowSize < 2 {
213
		return ErrInvalidSeqWindowSize
214 215
	}
	if cfg.Genesis.L1.Hash == (common.Hash{}) {
216
		return ErrMissingGenesisL1Hash
217 218
	}
	if cfg.Genesis.L2.Hash == (common.Hash{}) {
219
		return ErrMissingGenesisL2Hash
220 221
	}
	if cfg.Genesis.L2.Hash == cfg.Genesis.L1.Hash {
222
		return ErrGenesisHashesSame
223
	}
224
	if cfg.Genesis.L2Time == 0 {
225
		return ErrMissingGenesisL2Time
226
	}
227
	if cfg.Genesis.SystemConfig.BatcherAddr == (common.Address{}) {
228
		return ErrMissingBatcherAddr
229 230
	}
	if cfg.Genesis.SystemConfig.Overhead == (eth.Bytes32{}) {
231
		return ErrMissingOverhead
232 233
	}
	if cfg.Genesis.SystemConfig.Scalar == (eth.Bytes32{}) {
234
		return ErrMissingScalar
235 236
	}
	if cfg.Genesis.SystemConfig.GasLimit == 0 {
237
		return ErrMissingGasLimit
238
	}
239
	if cfg.BatchInboxAddress == (common.Address{}) {
240
		return ErrMissingBatchInboxAddress
241
	}
242
	if cfg.DepositContractAddress == (common.Address{}) {
243
		return ErrMissingDepositContractAddress
244 245
	}
	if cfg.L1ChainID == nil {
246
		return ErrMissingL1ChainID
247 248
	}
	if cfg.L2ChainID == nil {
249
		return ErrMissingL2ChainID
250 251
	}
	if cfg.L1ChainID.Cmp(cfg.L2ChainID) == 0 {
252
		return ErrChainIDsSame
253
	}
254
	if cfg.L1ChainID.Sign() < 1 {
255
		return ErrL1ChainIDNotPositive
256 257
	}
	if cfg.L2ChainID.Sign() < 1 {
258
		return ErrL2ChainIDNotPositive
259
	}
260 261 262 263 264 265 266
	return nil
}

func (c *Config) L1Signer() types.Signer {
	return types.NewLondonSigner(c.L1ChainID)
}

267 268 269 270 271
// IsRegolith returns true if the Regolith hardfork is active at or past the given timestamp.
func (c *Config) IsRegolith(timestamp uint64) bool {
	return c.RegolithTime != nil && timestamp >= *c.RegolithTime
}

272 273 274 275 276
// IsCanyon returns true if the Canyon hardfork is active at or past the given timestamp.
func (c *Config) IsCanyon(timestamp uint64) bool {
	return c.CanyonTime != nil && timestamp >= *c.CanyonTime
}

277 278 279 280
func (c *Config) IsSpanBatch(timestamp uint64) bool {
	return c.SpanBatchTime != nil && timestamp >= *c.SpanBatchTime
}

281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
// Description outputs a banner describing the important parts of rollup configuration in a human-readable form.
// Optionally provide a mapping of L2 chain IDs to network names to label the L2 chain with if not unknown.
// The config should be config.Check()-ed before creating a description.
func (c *Config) Description(l2Chains map[string]string) string {
	// Find and report the network the user is running
	var banner string
	networkL2 := ""
	if l2Chains != nil {
		networkL2 = l2Chains[c.L2ChainID.String()]
	}
	if networkL2 == "" {
		networkL2 = "unknown L2"
	}
	networkL1 := params.NetworkNames[c.L1ChainID.String()]
	if networkL1 == "" {
		networkL1 = "unknown L1"
	}
	banner += fmt.Sprintf("L2 Chain ID: %v (%s)\n", c.L2ChainID, networkL2)
	banner += fmt.Sprintf("L1 Chain ID: %v (%s)\n", c.L1ChainID, networkL1)
	// Report the genesis configuration
	banner += "Bedrock starting point:\n"
	banner += fmt.Sprintf("  L2 starting time: %d ~ %s\n", c.Genesis.L2Time, fmtTime(c.Genesis.L2Time))
	banner += fmt.Sprintf("  L2 block: %s %d\n", c.Genesis.L2.Hash, c.Genesis.L2.Number)
	banner += fmt.Sprintf("  L1 block: %s %d\n", c.Genesis.L1.Hash, c.Genesis.L1.Number)
	// Report the upgrade configuration
	banner += "Post-Bedrock Network Upgrades (timestamp based):\n"
	banner += fmt.Sprintf("  - Regolith: %s\n", fmtForkTimeOrUnset(c.RegolithTime))
308
	banner += fmt.Sprintf("  - Canyon: %s\n", fmtForkTimeOrUnset(c.CanyonTime))
309
	banner += fmt.Sprintf("  - SpanBatch: %s\n", fmtForkTimeOrUnset(c.SpanBatchTime))
310 311
	// Report the protocol version
	banner += fmt.Sprintf("Node supports up to OP-Stack Protocol Version: %s\n", OPStackSupport)
312 313 314
	return banner
}

pengin7384's avatar
pengin7384 committed
315
// LogDescription outputs a banner describing the important parts of rollup configuration in a log format.
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
// Optionally provide a mapping of L2 chain IDs to network names to label the L2 chain with if not unknown.
// The config should be config.Check()-ed before creating a description.
func (c *Config) LogDescription(log log.Logger, l2Chains map[string]string) {
	// Find and report the network the user is running
	networkL2 := ""
	if l2Chains != nil {
		networkL2 = l2Chains[c.L2ChainID.String()]
	}
	if networkL2 == "" {
		networkL2 = "unknown L2"
	}
	networkL1 := params.NetworkNames[c.L1ChainID.String()]
	if networkL1 == "" {
		networkL1 = "unknown L1"
	}
	log.Info("Rollup Config", "l2_chain_id", c.L2ChainID, "l2_network", networkL2, "l1_chain_id", c.L1ChainID,
		"l1_network", networkL1, "l2_start_time", c.Genesis.L2Time, "l2_block_hash", c.Genesis.L2.Hash.String(),
		"l2_block_number", c.Genesis.L2.Number, "l1_block_hash", c.Genesis.L1.Hash.String(),
334
		"l1_block_number", c.Genesis.L1.Number, "regolith_time", fmtForkTimeOrUnset(c.RegolithTime),
335 336 337
		"canyon_time", fmtForkTimeOrUnset(c.CanyonTime),
		"span_batch_time", fmtForkTimeOrUnset(c.SpanBatchTime),
	)
338 339
}

340 341 342 343 344 345 346 347 348 349 350 351 352 353
func fmtForkTimeOrUnset(v *uint64) string {
	if v == nil {
		return "(not configured)"
	}
	if *v == 0 { // don't output the unix epoch time if it's really just activated at genesis.
		return "@ genesis"
	}
	return fmt.Sprintf("@ %-10v ~ %s", *v, fmtTime(*v))
}

func fmtTime(v uint64) string {
	return time.Unix(int64(v), 0).Format(time.UnixDate)
}

354
type Epoch uint64