Commit db77e0b6 authored by Adrian Sutton's avatar Adrian Sutton Committed by GitHub

op-supervisor: Move ChainID and SuperRootResponse to op-service eth package (#13786)

parent ca4b1f68
...@@ -5,6 +5,7 @@ import ( ...@@ -5,6 +5,7 @@ import (
"os" "os"
"time" "time"
"github.com/ethereum-optimism/optimism/op-service/eth"
"github.com/ethereum/go-ethereum/core" "github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
...@@ -38,7 +39,7 @@ const ( ...@@ -38,7 +39,7 @@ const (
// Chain holds the most common per-chain action-test data and actors // Chain holds the most common per-chain action-test data and actors
type Chain struct { type Chain struct {
ChainID types.ChainID ChainID eth.ChainID
RollupCfg *rollup.Config RollupCfg *rollup.Config
L2Genesis *core.Genesis L2Genesis *core.Genesis
...@@ -148,9 +149,9 @@ func (sa *SupervisorActor) SignalFinalizedL1(t helpers.Testing) { ...@@ -148,9 +149,9 @@ func (sa *SupervisorActor) SignalFinalizedL1(t helpers.Testing) {
// worldToDepSet converts a set of chain configs into a dependency-set for the supervisor. // worldToDepSet converts a set of chain configs into a dependency-set for the supervisor.
func worldToDepSet(t helpers.Testing, worldOutput *interopgen.WorldOutput) *depset.StaticConfigDependencySet { func worldToDepSet(t helpers.Testing, worldOutput *interopgen.WorldOutput) *depset.StaticConfigDependencySet {
depSetCfg := make(map[types.ChainID]*depset.StaticConfigDependency) depSetCfg := make(map[eth.ChainID]*depset.StaticConfigDependency)
for _, out := range worldOutput.L2s { for _, out := range worldOutput.L2s {
depSetCfg[types.ChainIDFromBig(out.Genesis.Config.ChainID)] = &depset.StaticConfigDependency{ depSetCfg[eth.ChainIDFromBig(out.Genesis.Config.ChainID)] = &depset.StaticConfigDependency{
ChainIndex: types.ChainIndex(out.Genesis.Config.ChainID.Uint64()), ChainIndex: types.ChainIndex(out.Genesis.Config.ChainID.Uint64()),
ActivationTime: 0, ActivationTime: 0,
HistoryMinTime: 0, HistoryMinTime: 0,
...@@ -231,7 +232,7 @@ func createL2Services( ...@@ -231,7 +232,7 @@ func createL2Services(
eng.EthClient(), eng.EngineClient(t, output.RollupCfg)) eng.EthClient(), eng.EngineClient(t, output.RollupCfg))
return &Chain{ return &Chain{
ChainID: types.ChainIDFromBig(output.Genesis.Config.ChainID), ChainID: eth.ChainIDFromBig(output.Genesis.Config.ChainID),
RollupCfg: output.RollupCfg, RollupCfg: output.RollupCfg,
L2Genesis: output.Genesis, L2Genesis: output.Genesis,
BatcherAddr: crypto.PubkeyToAddress(batcherKey.PublicKey), BatcherAddr: crypto.PubkeyToAddress(batcherKey.PublicKey),
......
...@@ -8,6 +8,7 @@ import ( ...@@ -8,6 +8,7 @@ import (
"time" "time"
"github.com/ethereum-optimism/optimism/op-service/dial" "github.com/ethereum-optimism/optimism/op-service/dial"
"github.com/ethereum-optimism/optimism/op-service/eth"
oplog "github.com/ethereum-optimism/optimism/op-service/log" oplog "github.com/ethereum-optimism/optimism/op-service/log"
"github.com/ethereum-optimism/optimism/op-service/testlog" "github.com/ethereum-optimism/optimism/op-service/testlog"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
...@@ -198,7 +199,7 @@ func TestInterop_EmitLogs(t *testing.T) { ...@@ -198,7 +199,7 @@ func TestInterop_EmitLogs(t *testing.T) {
BlockNumber: log.BlockNumber, BlockNumber: log.BlockNumber,
LogIndex: uint32(log.Index), LogIndex: uint32(log.Index),
Timestamp: block.Time(), Timestamp: block.Time(),
ChainID: types.ChainIDFromBig(s2.ChainID(chainID)), ChainID: eth.ChainIDFromBig(s2.ChainID(chainID)),
} }
return identifier, expectedHash return identifier, expectedHash
} }
...@@ -290,7 +291,7 @@ func TestInteropBlockBuilding(t *testing.T) { ...@@ -290,7 +291,7 @@ func TestInteropBlockBuilding(t *testing.T) {
BlockNumber: ev.BlockNumber, BlockNumber: ev.BlockNumber,
LogIndex: uint32(ev.Index), LogIndex: uint32(ev.Index),
Timestamp: header.Time, Timestamp: header.Time,
ChainID: types.ChainIDFromBig(s2.ChainID(chainA)), ChainID: eth.ChainIDFromBig(s2.ChainID(chainA)),
} }
msgPayload := types.LogToMessagePayload(ev) msgPayload := types.LogToMessagePayload(ev)
......
...@@ -11,6 +11,7 @@ import ( ...@@ -11,6 +11,7 @@ import (
"testing" "testing"
"time" "time"
"github.com/ethereum-optimism/optimism/op-service/eth"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/accounts/abi/bind"
...@@ -485,11 +486,11 @@ func (s *interopE2ESystem) prepareSupervisor() *supervisor.SupervisorService { ...@@ -485,11 +486,11 @@ func (s *interopE2ESystem) prepareSupervisor() *supervisor.SupervisorService {
L1RPC: s.l1.UserRPC().RPC(), L1RPC: s.l1.UserRPC().RPC(),
Datadir: path.Join(s.t.TempDir(), "supervisor"), Datadir: path.Join(s.t.TempDir(), "supervisor"),
} }
depSet := make(map[supervisortypes.ChainID]*depset.StaticConfigDependency) depSet := make(map[eth.ChainID]*depset.StaticConfigDependency)
// Iterate over the L2 chain configs. The L2 nodes don't exist yet. // Iterate over the L2 chain configs. The L2 nodes don't exist yet.
for _, l2Out := range s.worldOutput.L2s { for _, l2Out := range s.worldOutput.L2s {
chainID := supervisortypes.ChainIDFromBig(l2Out.Genesis.Config.ChainID) chainID := eth.ChainIDFromBig(l2Out.Genesis.Config.ChainID)
index, err := chainID.ToUInt32() index, err := chainID.ToUInt32()
require.NoError(s.t, err) require.NoError(s.t, err)
depSet[chainID] = &depset.StaticConfigDependency{ depSet[chainID] = &depset.StaticConfigDependency{
......
...@@ -51,7 +51,7 @@ func (ib *InteropAPI) BlockRefByNumber(ctx context.Context, num uint64) (eth.Blo ...@@ -51,7 +51,7 @@ func (ib *InteropAPI) BlockRefByNumber(ctx context.Context, num uint64) (eth.Blo
return ib.backend.BlockRefByNumber(ctx, num) return ib.backend.BlockRefByNumber(ctx, num)
} }
func (ib *InteropAPI) ChainID(ctx context.Context) (supervisortypes.ChainID, error) { func (ib *InteropAPI) ChainID(ctx context.Context) (eth.ChainID, error) {
return ib.backend.ChainID(ctx) return ib.backend.ChainID(ctx)
} }
......
...@@ -276,8 +276,8 @@ func (m *ManagedMode) BlockRefByNumber(ctx context.Context, num uint64) (eth.Blo ...@@ -276,8 +276,8 @@ func (m *ManagedMode) BlockRefByNumber(ctx context.Context, num uint64) (eth.Blo
return m.l2.BlockRefByNumber(ctx, num) return m.l2.BlockRefByNumber(ctx, num)
} }
func (m *ManagedMode) ChainID(ctx context.Context) (supervisortypes.ChainID, error) { func (m *ManagedMode) ChainID(ctx context.Context) (eth.ChainID, error) {
return supervisortypes.ChainIDFromBig(m.cfg.L2ChainID), nil return eth.ChainIDFromBig(m.cfg.L2ChainID), nil
} }
func (m *ManagedMode) OutputV0AtTimestamp(ctx context.Context, timestamp uint64) (*eth.OutputV0, error) { func (m *ManagedMode) OutputV0AtTimestamp(ctx context.Context, timestamp uint64) (*eth.OutputV0, error) {
......
package eth
import (
"fmt"
"math"
"math/big"
"github.com/holiman/uint256"
)
type ChainID uint256.Int
func ChainIDFromBig(chainID *big.Int) ChainID {
return ChainID(*uint256.MustFromBig(chainID))
}
func ChainIDFromUInt64(i uint64) ChainID {
return ChainID(*uint256.NewInt(i))
}
func (id ChainID) String() string {
return ((*uint256.Int)(&id)).Dec()
}
func (id ChainID) ToUInt32() (uint32, error) {
v := (*uint256.Int)(&id)
if !v.IsUint64() {
return 0, fmt.Errorf("ChainID too large for uint32: %v", id)
}
v64 := v.Uint64()
if v64 > math.MaxUint32 {
return 0, fmt.Errorf("ChainID too large for uint32: %v", id)
}
return uint32(v64), nil
}
func (id *ChainID) ToBig() *big.Int {
return (*uint256.Int)(id).ToBig()
}
func (id ChainID) MarshalText() ([]byte, error) {
return []byte(id.String()), nil
}
func (id *ChainID) UnmarshalText(data []byte) error {
var x uint256.Int
err := x.UnmarshalText(data)
if err != nil {
return err
}
*id = ChainID(x)
return nil
}
func (id ChainID) Cmp(other ChainID) int {
return (*uint256.Int)(&id).Cmp((*uint256.Int)(&other))
}
package eth
import (
"math"
"testing"
"github.com/holiman/uint256"
"github.com/stretchr/testify/require"
)
func TestChainID_String(t *testing.T) {
tests := []struct {
input ChainID
expected string
}{
{ChainIDFromUInt64(0), "0"},
{ChainIDFromUInt64(1), "1"},
{ChainIDFromUInt64(871975192374), "871975192374"},
{ChainIDFromUInt64(math.MaxInt64), "9223372036854775807"},
{ChainID(*uint256.NewInt(math.MaxUint64)), "18446744073709551615"},
{ChainID(*uint256.MustFromDecimal("1844674407370955161618446744073709551616")), "1844674407370955161618446744073709551616"},
}
for _, test := range tests {
test := test
t.Run(test.expected, func(t *testing.T) {
t.Run("String", func(t *testing.T) {
require.Equal(t, test.expected, test.input.String())
})
t.Run("MarshalText", func(t *testing.T) {
data, err := test.input.MarshalText()
require.NoError(t, err)
require.Equal(t, test.expected, string(data))
})
t.Run("UnmarshalText", func(t *testing.T) {
var id ChainID
require.NoError(t, id.UnmarshalText([]byte(test.expected)))
require.Equal(t, test.input, id)
})
})
}
}
...@@ -2,8 +2,11 @@ package eth ...@@ -2,8 +2,11 @@ package eth
import ( import (
"encoding/binary" "encoding/binary"
"encoding/json"
"errors" "errors"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
) )
...@@ -95,3 +98,72 @@ func unmarshalSuperRootV1(data []byte) (*SuperV1, error) { ...@@ -95,3 +98,72 @@ func unmarshalSuperRootV1(data []byte) (*SuperV1, error) {
} }
return &output, nil return &output, nil
} }
type ChainRootInfo struct {
ChainID ChainID `json:"chainID"`
// Canonical is the output root of the latest canonical block at a particular Timestamp.
Canonical Bytes32 `json:"canonical"`
// Pending is the output root preimage for the latest block at a particular Timestamp prior to validation of
// executing messages. If the original block was valid, this will be the preimage of the
// output root from the Canonical array. If it was invalid, it will be the output root preimage from the
// Optimistic Block Deposited Transaction added to the deposit-only block.
Pending []byte `json:"pending"`
}
type chainRootInfoMarshalling struct {
ChainID ChainID `json:"chainID"`
Canonical common.Hash `json:"canonical"`
Pending hexutil.Bytes `json:"pending"`
}
func (i ChainRootInfo) MarshalJSON() ([]byte, error) {
return json.Marshal(&chainRootInfoMarshalling{
ChainID: i.ChainID,
Canonical: common.Hash(i.Canonical),
Pending: i.Pending,
})
}
func (i *ChainRootInfo) UnmarshalJSON(input []byte) error {
var dec chainRootInfoMarshalling
if err := json.Unmarshal(input, &dec); err != nil {
return err
}
i.ChainID = dec.ChainID
i.Canonical = Bytes32(dec.Canonical)
i.Pending = dec.Pending
return nil
}
type SuperRootResponse struct {
Timestamp uint64 `json:"timestamp"`
SuperRoot Bytes32 `json:"superRoot"`
// Chains is the list of ChainRootInfo for each chain in the dependency set.
// It represents the state of the chain at or before the Timestamp.
Chains []ChainRootInfo `json:"chains"`
}
type superRootResponseMarshalling struct {
Timestamp hexutil.Uint64 `json:"timestamp"`
SuperRoot common.Hash `json:"superRoot"`
Chains []ChainRootInfo `json:"chains"`
}
func (r SuperRootResponse) MarshalJSON() ([]byte, error) {
return json.Marshal(&superRootResponseMarshalling{
Timestamp: hexutil.Uint64(r.Timestamp),
SuperRoot: common.Hash(r.SuperRoot),
Chains: r.Chains,
})
}
func (r *SuperRootResponse) UnmarshalJSON(input []byte) error {
var dec superRootResponseMarshalling
if err := json.Unmarshal(input, &dec); err != nil {
return err
}
r.Timestamp = uint64(dec.Timestamp)
r.SuperRoot = Bytes32(dec.SuperRoot)
r.Chains = dec.Chains
return nil
}
...@@ -77,7 +77,7 @@ func (cl *SupervisorClient) CheckMessage(ctx context.Context, identifier types.I ...@@ -77,7 +77,7 @@ func (cl *SupervisorClient) CheckMessage(ctx context.Context, identifier types.I
return result, nil return result, nil
} }
func (cl *SupervisorClient) UnsafeView(ctx context.Context, chainID types.ChainID, unsafe types.ReferenceView) (types.ReferenceView, error) { func (cl *SupervisorClient) UnsafeView(ctx context.Context, chainID eth.ChainID, unsafe types.ReferenceView) (types.ReferenceView, error) {
var result types.ReferenceView var result types.ReferenceView
err := cl.client.CallContext( err := cl.client.CallContext(
ctx, ctx,
...@@ -91,7 +91,7 @@ func (cl *SupervisorClient) UnsafeView(ctx context.Context, chainID types.ChainI ...@@ -91,7 +91,7 @@ func (cl *SupervisorClient) UnsafeView(ctx context.Context, chainID types.ChainI
return result, nil return result, nil
} }
func (cl *SupervisorClient) SafeView(ctx context.Context, chainID types.ChainID, safe types.ReferenceView) (types.ReferenceView, error) { func (cl *SupervisorClient) SafeView(ctx context.Context, chainID eth.ChainID, safe types.ReferenceView) (types.ReferenceView, error) {
var result types.ReferenceView var result types.ReferenceView
err := cl.client.CallContext( err := cl.client.CallContext(
ctx, ctx,
...@@ -105,7 +105,7 @@ func (cl *SupervisorClient) SafeView(ctx context.Context, chainID types.ChainID, ...@@ -105,7 +105,7 @@ func (cl *SupervisorClient) SafeView(ctx context.Context, chainID types.ChainID,
return result, nil return result, nil
} }
func (cl *SupervisorClient) Finalized(ctx context.Context, chainID types.ChainID) (eth.BlockID, error) { func (cl *SupervisorClient) Finalized(ctx context.Context, chainID eth.ChainID) (eth.BlockID, error) {
var result eth.BlockID var result eth.BlockID
err := cl.client.CallContext( err := cl.client.CallContext(
ctx, ctx,
...@@ -124,7 +124,7 @@ func (cl *SupervisorClient) FinalizedL1(ctx context.Context) (eth.BlockRef, erro ...@@ -124,7 +124,7 @@ func (cl *SupervisorClient) FinalizedL1(ctx context.Context) (eth.BlockRef, erro
return result, err return result, err
} }
func (cl *SupervisorClient) CrossDerivedFrom(ctx context.Context, chainID types.ChainID, derived eth.BlockID) (eth.BlockRef, error) { func (cl *SupervisorClient) CrossDerivedFrom(ctx context.Context, chainID eth.ChainID, derived eth.BlockID) (eth.BlockRef, error) {
var result eth.BlockRef var result eth.BlockRef
err := cl.client.CallContext( err := cl.client.CallContext(
ctx, ctx,
...@@ -135,7 +135,7 @@ func (cl *SupervisorClient) CrossDerivedFrom(ctx context.Context, chainID types. ...@@ -135,7 +135,7 @@ func (cl *SupervisorClient) CrossDerivedFrom(ctx context.Context, chainID types.
return result, err return result, err
} }
func (cl *SupervisorClient) UpdateLocalUnsafe(ctx context.Context, chainID types.ChainID, head eth.BlockRef) error { func (cl *SupervisorClient) UpdateLocalUnsafe(ctx context.Context, chainID eth.ChainID, head eth.BlockRef) error {
return cl.client.CallContext( return cl.client.CallContext(
ctx, ctx,
nil, nil,
...@@ -144,7 +144,7 @@ func (cl *SupervisorClient) UpdateLocalUnsafe(ctx context.Context, chainID types ...@@ -144,7 +144,7 @@ func (cl *SupervisorClient) UpdateLocalUnsafe(ctx context.Context, chainID types
head) head)
} }
func (cl *SupervisorClient) UpdateLocalSafe(ctx context.Context, chainID types.ChainID, derivedFrom eth.L1BlockRef, lastDerived eth.BlockRef) error { func (cl *SupervisorClient) UpdateLocalSafe(ctx context.Context, chainID eth.ChainID, derivedFrom eth.L1BlockRef, lastDerived eth.BlockRef) error {
return cl.client.CallContext( return cl.client.CallContext(
ctx, ctx,
nil, nil,
...@@ -154,8 +154,8 @@ func (cl *SupervisorClient) UpdateLocalSafe(ctx context.Context, chainID types.C ...@@ -154,8 +154,8 @@ func (cl *SupervisorClient) UpdateLocalSafe(ctx context.Context, chainID types.C
lastDerived) lastDerived)
} }
func (cl *SupervisorClient) SuperRootAtTimestamp(ctx context.Context, timestamp hexutil.Uint64) (types.SuperRootResponse, error) { func (cl *SupervisorClient) SuperRootAtTimestamp(ctx context.Context, timestamp hexutil.Uint64) (eth.SuperRootResponse, error) {
var result types.SuperRootResponse var result eth.SuperRootResponse
err := cl.client.CallContext( err := cl.client.CallContext(
ctx, ctx,
&result, &result,
......
...@@ -8,39 +8,39 @@ import ( ...@@ -8,39 +8,39 @@ import (
) )
type FakeInteropBackend struct { type FakeInteropBackend struct {
UnsafeViewFn func(ctx context.Context, chainID types.ChainID, unsafe types.ReferenceView) (types.ReferenceView, error) UnsafeViewFn func(ctx context.Context, chainID eth.ChainID, unsafe types.ReferenceView) (types.ReferenceView, error)
SafeViewFn func(ctx context.Context, chainID types.ChainID, safe types.ReferenceView) (types.ReferenceView, error) SafeViewFn func(ctx context.Context, chainID eth.ChainID, safe types.ReferenceView) (types.ReferenceView, error)
FinalizedFn func(ctx context.Context, chainID types.ChainID) (eth.BlockID, error) FinalizedFn func(ctx context.Context, chainID eth.ChainID) (eth.BlockID, error)
DerivedFromFn func(ctx context.Context, chainID types.ChainID, derived eth.BlockID) (eth.L1BlockRef, error) DerivedFromFn func(ctx context.Context, chainID eth.ChainID, derived eth.BlockID) (eth.L1BlockRef, error)
UpdateLocalUnsafeFn func(ctx context.Context, chainID types.ChainID, head eth.BlockRef) error UpdateLocalUnsafeFn func(ctx context.Context, chainID eth.ChainID, head eth.BlockRef) error
UpdateLocalSafeFn func(ctx context.Context, chainID types.ChainID, derivedFrom eth.L1BlockRef, lastDerived eth.BlockRef) error UpdateLocalSafeFn func(ctx context.Context, chainID eth.ChainID, derivedFrom eth.L1BlockRef, lastDerived eth.BlockRef) error
UpdateFinalizedL1Fn func(ctx context.Context, chainID types.ChainID, finalized eth.L1BlockRef) error UpdateFinalizedL1Fn func(ctx context.Context, chainID eth.ChainID, finalized eth.L1BlockRef) error
} }
func (m *FakeInteropBackend) UnsafeView(ctx context.Context, chainID types.ChainID, unsafe types.ReferenceView) (types.ReferenceView, error) { func (m *FakeInteropBackend) UnsafeView(ctx context.Context, chainID eth.ChainID, unsafe types.ReferenceView) (types.ReferenceView, error) {
return m.UnsafeViewFn(ctx, chainID, unsafe) return m.UnsafeViewFn(ctx, chainID, unsafe)
} }
func (m *FakeInteropBackend) SafeView(ctx context.Context, chainID types.ChainID, safe types.ReferenceView) (types.ReferenceView, error) { func (m *FakeInteropBackend) SafeView(ctx context.Context, chainID eth.ChainID, safe types.ReferenceView) (types.ReferenceView, error) {
return m.SafeViewFn(ctx, chainID, safe) return m.SafeViewFn(ctx, chainID, safe)
} }
func (m *FakeInteropBackend) Finalized(ctx context.Context, chainID types.ChainID) (eth.BlockID, error) { func (m *FakeInteropBackend) Finalized(ctx context.Context, chainID eth.ChainID) (eth.BlockID, error) {
return m.FinalizedFn(ctx, chainID) return m.FinalizedFn(ctx, chainID)
} }
func (m *FakeInteropBackend) CrossDerivedFrom(ctx context.Context, chainID types.ChainID, derived eth.BlockID) (eth.L1BlockRef, error) { func (m *FakeInteropBackend) CrossDerivedFrom(ctx context.Context, chainID eth.ChainID, derived eth.BlockID) (eth.L1BlockRef, error) {
return m.DerivedFromFn(ctx, chainID, derived) return m.DerivedFromFn(ctx, chainID, derived)
} }
func (m *FakeInteropBackend) UpdateLocalUnsafe(ctx context.Context, chainID types.ChainID, head eth.BlockRef) error { func (m *FakeInteropBackend) UpdateLocalUnsafe(ctx context.Context, chainID eth.ChainID, head eth.BlockRef) error {
return m.UpdateLocalUnsafeFn(ctx, chainID, head) return m.UpdateLocalUnsafeFn(ctx, chainID, head)
} }
func (m *FakeInteropBackend) UpdateLocalSafe(ctx context.Context, chainID types.ChainID, derivedFrom eth.L1BlockRef, lastDerived eth.BlockRef) error { func (m *FakeInteropBackend) UpdateLocalSafe(ctx context.Context, chainID eth.ChainID, derivedFrom eth.L1BlockRef, lastDerived eth.BlockRef) error {
return m.UpdateLocalSafeFn(ctx, chainID, derivedFrom, lastDerived) return m.UpdateLocalSafeFn(ctx, chainID, derivedFrom, lastDerived)
} }
func (m *FakeInteropBackend) UpdateFinalizedL1(ctx context.Context, chainID types.ChainID, finalized eth.L1BlockRef) error { func (m *FakeInteropBackend) UpdateFinalizedL1(ctx context.Context, chainID eth.ChainID, finalized eth.L1BlockRef) error {
return m.UpdateFinalizedL1Fn(ctx, chainID, finalized) return m.UpdateFinalizedL1Fn(ctx, chainID, finalized)
} }
...@@ -13,16 +13,16 @@ type MockInteropBackend struct { ...@@ -13,16 +13,16 @@ type MockInteropBackend struct {
Mock mock.Mock Mock mock.Mock
} }
func (m *MockInteropBackend) UnsafeView(ctx context.Context, chainID types.ChainID, unsafe types.ReferenceView) (types.ReferenceView, error) { func (m *MockInteropBackend) UnsafeView(ctx context.Context, chainID eth.ChainID, unsafe types.ReferenceView) (types.ReferenceView, error) {
result := m.Mock.MethodCalled("UnsafeView", chainID, unsafe) result := m.Mock.MethodCalled("UnsafeView", chainID, unsafe)
return result.Get(0).(types.ReferenceView), *result.Get(1).(*error) return result.Get(0).(types.ReferenceView), *result.Get(1).(*error)
} }
func (m *MockInteropBackend) ExpectUnsafeView(chainID types.ChainID, unsafe types.ReferenceView, result types.ReferenceView, err error) { func (m *MockInteropBackend) ExpectUnsafeView(chainID eth.ChainID, unsafe types.ReferenceView, result types.ReferenceView, err error) {
m.Mock.On("UnsafeView", chainID, unsafe).Once().Return(result, &err) m.Mock.On("UnsafeView", chainID, unsafe).Once().Return(result, &err)
} }
func (m *MockInteropBackend) OnUnsafeView(chainID types.ChainID, fn func(request types.ReferenceView) (result types.ReferenceView, err error)) { func (m *MockInteropBackend) OnUnsafeView(chainID eth.ChainID, fn func(request types.ReferenceView) (result types.ReferenceView, err error)) {
var result types.ReferenceView var result types.ReferenceView
var err error var err error
m.Mock.On("UnsafeView", chainID, mock.Anything).Run(func(args mock.Arguments) { m.Mock.On("UnsafeView", chainID, mock.Anything).Run(func(args mock.Arguments) {
...@@ -31,16 +31,16 @@ func (m *MockInteropBackend) OnUnsafeView(chainID types.ChainID, fn func(request ...@@ -31,16 +31,16 @@ func (m *MockInteropBackend) OnUnsafeView(chainID types.ChainID, fn func(request
}).Return(result, &err) }).Return(result, &err)
} }
func (m *MockInteropBackend) SafeView(ctx context.Context, chainID types.ChainID, safe types.ReferenceView) (types.ReferenceView, error) { func (m *MockInteropBackend) SafeView(ctx context.Context, chainID eth.ChainID, safe types.ReferenceView) (types.ReferenceView, error) {
result := m.Mock.MethodCalled("SafeView", chainID, safe) result := m.Mock.MethodCalled("SafeView", chainID, safe)
return result.Get(0).(types.ReferenceView), *result.Get(1).(*error) return result.Get(0).(types.ReferenceView), *result.Get(1).(*error)
} }
func (m *MockInteropBackend) ExpectSafeView(chainID types.ChainID, safe types.ReferenceView, result types.ReferenceView, err error) { func (m *MockInteropBackend) ExpectSafeView(chainID eth.ChainID, safe types.ReferenceView, result types.ReferenceView, err error) {
m.Mock.On("SafeView", chainID, safe).Once().Return(result, &err) m.Mock.On("SafeView", chainID, safe).Once().Return(result, &err)
} }
func (m *MockInteropBackend) OnSafeView(chainID types.ChainID, fn func(request types.ReferenceView) (result types.ReferenceView, err error)) { func (m *MockInteropBackend) OnSafeView(chainID eth.ChainID, fn func(request types.ReferenceView) (result types.ReferenceView, err error)) {
var result types.ReferenceView var result types.ReferenceView
var err error var err error
m.Mock.On("SafeView", chainID, mock.Anything).Run(func(args mock.Arguments) { m.Mock.On("SafeView", chainID, mock.Anything).Run(func(args mock.Arguments) {
...@@ -49,47 +49,47 @@ func (m *MockInteropBackend) OnSafeView(chainID types.ChainID, fn func(request t ...@@ -49,47 +49,47 @@ func (m *MockInteropBackend) OnSafeView(chainID types.ChainID, fn func(request t
}).Return(result, &err) }).Return(result, &err)
} }
func (m *MockInteropBackend) Finalized(ctx context.Context, chainID types.ChainID) (eth.BlockID, error) { func (m *MockInteropBackend) Finalized(ctx context.Context, chainID eth.ChainID) (eth.BlockID, error) {
result := m.Mock.MethodCalled("Finalized", chainID) result := m.Mock.MethodCalled("Finalized", chainID)
return result.Get(0).(eth.BlockID), *result.Get(1).(*error) return result.Get(0).(eth.BlockID), *result.Get(1).(*error)
} }
func (m *MockInteropBackend) ExpectFinalized(chainID types.ChainID, result eth.BlockID, err error) { func (m *MockInteropBackend) ExpectFinalized(chainID eth.ChainID, result eth.BlockID, err error) {
m.Mock.On("Finalized", chainID).Once().Return(result, &err) m.Mock.On("Finalized", chainID).Once().Return(result, &err)
} }
func (m *MockInteropBackend) CrossDerivedFrom(ctx context.Context, chainID types.ChainID, derived eth.BlockID) (eth.L1BlockRef, error) { func (m *MockInteropBackend) CrossDerivedFrom(ctx context.Context, chainID eth.ChainID, derived eth.BlockID) (eth.L1BlockRef, error) {
result := m.Mock.MethodCalled("CrossDerivedFrom", chainID, derived) result := m.Mock.MethodCalled("CrossDerivedFrom", chainID, derived)
return result.Get(0).(eth.L1BlockRef), *result.Get(1).(*error) return result.Get(0).(eth.L1BlockRef), *result.Get(1).(*error)
} }
func (m *MockInteropBackend) ExpectDerivedFrom(chainID types.ChainID, derived eth.BlockID, result eth.L1BlockRef, err error) { func (m *MockInteropBackend) ExpectDerivedFrom(chainID eth.ChainID, derived eth.BlockID, result eth.L1BlockRef, err error) {
m.Mock.On("CrossDerivedFrom", chainID, derived).Once().Return(result, &err) m.Mock.On("CrossDerivedFrom", chainID, derived).Once().Return(result, &err)
} }
func (m *MockInteropBackend) UpdateLocalUnsafe(ctx context.Context, chainID types.ChainID, head eth.BlockRef) error { func (m *MockInteropBackend) UpdateLocalUnsafe(ctx context.Context, chainID eth.ChainID, head eth.BlockRef) error {
result := m.Mock.MethodCalled("UpdateLocalUnsafe", chainID, head) result := m.Mock.MethodCalled("UpdateLocalUnsafe", chainID, head)
return *result.Get(0).(*error) return *result.Get(0).(*error)
} }
func (m *MockInteropBackend) ExpectUpdateLocalUnsafe(chainID types.ChainID, head eth.BlockRef, err error) { func (m *MockInteropBackend) ExpectUpdateLocalUnsafe(chainID eth.ChainID, head eth.BlockRef, err error) {
m.Mock.On("UpdateLocalUnsafe", chainID, head).Once().Return(&err) m.Mock.On("UpdateLocalUnsafe", chainID, head).Once().Return(&err)
} }
func (m *MockInteropBackend) ExpectAnyUpdateLocalUnsafe(chainID types.ChainID, err error) { func (m *MockInteropBackend) ExpectAnyUpdateLocalUnsafe(chainID eth.ChainID, err error) {
m.Mock.On("UpdateLocalUnsafe", chainID, mock.Anything).Once().Return(&err) m.Mock.On("UpdateLocalUnsafe", chainID, mock.Anything).Once().Return(&err)
} }
func (m *MockInteropBackend) UpdateLocalSafe(ctx context.Context, chainID types.ChainID, derivedFrom eth.L1BlockRef, lastDerived eth.BlockRef) error { func (m *MockInteropBackend) UpdateLocalSafe(ctx context.Context, chainID eth.ChainID, derivedFrom eth.L1BlockRef, lastDerived eth.BlockRef) error {
result := m.Mock.MethodCalled("UpdateLocalSafe", chainID, derivedFrom, lastDerived) result := m.Mock.MethodCalled("UpdateLocalSafe", chainID, derivedFrom, lastDerived)
return *result.Get(0).(*error) return *result.Get(0).(*error)
} }
func (m *MockInteropBackend) ExpectUpdateLocalSafe(chainID types.ChainID, derivedFrom eth.L1BlockRef, lastDerived eth.BlockRef, err error) { func (m *MockInteropBackend) ExpectUpdateLocalSafe(chainID eth.ChainID, derivedFrom eth.L1BlockRef, lastDerived eth.BlockRef, err error) {
m.Mock.On("UpdateLocalSafe", chainID, derivedFrom, lastDerived).Once().Return(&err) m.Mock.On("UpdateLocalSafe", chainID, derivedFrom, lastDerived).Once().Return(&err)
} }
func (m *MockInteropBackend) UpdateFinalizedL1(ctx context.Context, chainID types.ChainID, finalized eth.L1BlockRef) error { func (m *MockInteropBackend) UpdateFinalizedL1(ctx context.Context, chainID eth.ChainID, finalized eth.L1BlockRef) error {
result := m.Mock.MethodCalled("UpdateFinalizedL1", chainID, finalized) result := m.Mock.MethodCalled("UpdateFinalizedL1", chainID, finalized)
return *result.Get(0).(*error) return *result.Get(0).(*error)
} }
......
...@@ -3,6 +3,7 @@ package config ...@@ -3,6 +3,7 @@ package config
import ( import (
"testing" "testing"
"github.com/ethereum-optimism/optimism/op-service/eth"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/ethereum-optimism/optimism/op-service/metrics" "github.com/ethereum-optimism/optimism/op-service/metrics"
...@@ -10,7 +11,6 @@ import ( ...@@ -10,7 +11,6 @@ import (
"github.com/ethereum-optimism/optimism/op-service/rpc" "github.com/ethereum-optimism/optimism/op-service/rpc"
"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/backend/depset" "github.com/ethereum-optimism/optimism/op-supervisor/supervisor/backend/depset"
"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/backend/syncnode" "github.com/ethereum-optimism/optimism/op-supervisor/supervisor/backend/syncnode"
"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types"
) )
func TestDefaultConfigIsValid(t *testing.T) { func TestDefaultConfigIsValid(t *testing.T) {
...@@ -57,8 +57,8 @@ func TestValidateRPCConfig(t *testing.T) { ...@@ -57,8 +57,8 @@ func TestValidateRPCConfig(t *testing.T) {
} }
func validConfig() *Config { func validConfig() *Config {
depSet, err := depset.NewStaticConfigDependencySet(map[types.ChainID]*depset.StaticConfigDependency{ depSet, err := depset.NewStaticConfigDependencySet(map[eth.ChainID]*depset.StaticConfigDependency{
types.ChainIDFromUInt64(900): &depset.StaticConfigDependency{ eth.ChainIDFromUInt64(900): &depset.StaticConfigDependency{
ChainIndex: 900, ChainIndex: 900,
ActivationTime: 0, ActivationTime: 0,
HistoryMinTime: 0, HistoryMinTime: 0,
......
package metrics package metrics
import ( import (
"github.com/ethereum-optimism/optimism/op-service/eth"
"github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus"
opmetrics "github.com/ethereum-optimism/optimism/op-service/metrics" opmetrics "github.com/ethereum-optimism/optimism/op-service/metrics"
"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types"
) )
const Namespace = "op_supervisor" const Namespace = "op_supervisor"
...@@ -15,11 +15,11 @@ type Metricer interface { ...@@ -15,11 +15,11 @@ type Metricer interface {
opmetrics.RPCMetricer opmetrics.RPCMetricer
CacheAdd(chainID types.ChainID, label string, cacheSize int, evicted bool) CacheAdd(chainID eth.ChainID, label string, cacheSize int, evicted bool)
CacheGet(chainID types.ChainID, label string, hit bool) CacheGet(chainID eth.ChainID, label string, hit bool)
RecordDBEntryCount(chainID types.ChainID, kind string, count int64) RecordDBEntryCount(chainID eth.ChainID, kind string, count int64)
RecordDBSearchEntriesRead(chainID types.ChainID, count int64) RecordDBSearchEntriesRead(chainID eth.ChainID, count int64)
Document() []opmetrics.DocumentedMetric Document() []opmetrics.DocumentedMetric
} }
...@@ -141,7 +141,7 @@ func (m *Metrics) RecordUp() { ...@@ -141,7 +141,7 @@ func (m *Metrics) RecordUp() {
m.up.Set(1) m.up.Set(1)
} }
func (m *Metrics) CacheAdd(chainID types.ChainID, label string, cacheSize int, evicted bool) { func (m *Metrics) CacheAdd(chainID eth.ChainID, label string, cacheSize int, evicted bool) {
chain := chainIDLabel(chainID) chain := chainIDLabel(chainID)
m.CacheSizeVec.WithLabelValues(chain, label).Set(float64(cacheSize)) m.CacheSizeVec.WithLabelValues(chain, label).Set(float64(cacheSize))
if evicted { if evicted {
...@@ -151,7 +151,7 @@ func (m *Metrics) CacheAdd(chainID types.ChainID, label string, cacheSize int, e ...@@ -151,7 +151,7 @@ func (m *Metrics) CacheAdd(chainID types.ChainID, label string, cacheSize int, e
} }
} }
func (m *Metrics) CacheGet(chainID types.ChainID, label string, hit bool) { func (m *Metrics) CacheGet(chainID eth.ChainID, label string, hit bool) {
chain := chainIDLabel(chainID) chain := chainIDLabel(chainID)
if hit { if hit {
m.CacheGetVec.WithLabelValues(chain, label, "true").Inc() m.CacheGetVec.WithLabelValues(chain, label, "true").Inc()
...@@ -160,14 +160,14 @@ func (m *Metrics) CacheGet(chainID types.ChainID, label string, hit bool) { ...@@ -160,14 +160,14 @@ func (m *Metrics) CacheGet(chainID types.ChainID, label string, hit bool) {
} }
} }
func (m *Metrics) RecordDBEntryCount(chainID types.ChainID, kind string, count int64) { func (m *Metrics) RecordDBEntryCount(chainID eth.ChainID, kind string, count int64) {
m.DBEntryCountVec.WithLabelValues(chainIDLabel(chainID), kind).Set(float64(count)) m.DBEntryCountVec.WithLabelValues(chainIDLabel(chainID), kind).Set(float64(count))
} }
func (m *Metrics) RecordDBSearchEntriesRead(chainID types.ChainID, count int64) { func (m *Metrics) RecordDBSearchEntriesRead(chainID eth.ChainID, count int64) {
m.DBSearchEntriesReadVec.WithLabelValues(chainIDLabel(chainID)).Observe(float64(count)) m.DBSearchEntriesReadVec.WithLabelValues(chainIDLabel(chainID)).Observe(float64(count))
} }
func chainIDLabel(chainID types.ChainID) string { func chainIDLabel(chainID eth.ChainID) string {
return chainID.String() return chainID.String()
} }
package metrics package metrics
import ( import (
"github.com/ethereum-optimism/optimism/op-service/eth"
opmetrics "github.com/ethereum-optimism/optimism/op-service/metrics" opmetrics "github.com/ethereum-optimism/optimism/op-service/metrics"
"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types"
) )
type noopMetrics struct { type noopMetrics struct {
...@@ -16,8 +16,8 @@ func (*noopMetrics) Document() []opmetrics.DocumentedMetric { return nil } ...@@ -16,8 +16,8 @@ func (*noopMetrics) Document() []opmetrics.DocumentedMetric { return nil }
func (*noopMetrics) RecordInfo(version string) {} func (*noopMetrics) RecordInfo(version string) {}
func (*noopMetrics) RecordUp() {} func (*noopMetrics) RecordUp() {}
func (m *noopMetrics) CacheAdd(_ types.ChainID, _ string, _ int, _ bool) {} func (m *noopMetrics) CacheAdd(_ eth.ChainID, _ string, _ int, _ bool) {}
func (m *noopMetrics) CacheGet(_ types.ChainID, _ string, _ bool) {} func (m *noopMetrics) CacheGet(_ eth.ChainID, _ string, _ bool) {}
func (m *noopMetrics) RecordDBEntryCount(_ types.ChainID, _ string, _ int64) {} func (m *noopMetrics) RecordDBEntryCount(_ eth.ChainID, _ string, _ int64) {}
func (m *noopMetrics) RecordDBSearchEntriesRead(_ types.ChainID, _ int64) {} func (m *noopMetrics) RecordDBSearchEntriesRead(_ eth.ChainID, _ int64) {}
...@@ -50,9 +50,9 @@ type SupervisorBackend struct { ...@@ -50,9 +50,9 @@ type SupervisorBackend struct {
l1Accessor *l1access.L1Accessor l1Accessor *l1access.L1Accessor
// chainProcessors are notified of new unsafe blocks, and add the unsafe log events data into the events DB // chainProcessors are notified of new unsafe blocks, and add the unsafe log events data into the events DB
chainProcessors locks.RWMap[types.ChainID, *processors.ChainProcessor] chainProcessors locks.RWMap[eth.ChainID, *processors.ChainProcessor]
syncSources locks.RWMap[types.ChainID, syncnode.SyncSource] syncSources locks.RWMap[eth.ChainID, syncnode.SyncSource]
// syncNodesController controls the derivation or reset of the sync nodes // syncNodesController controls the derivation or reset of the sync nodes
syncNodesController *syncnode.SyncNodesController syncNodesController *syncnode.SyncNodesController
...@@ -63,7 +63,7 @@ type SupervisorBackend struct { ...@@ -63,7 +63,7 @@ type SupervisorBackend struct {
// chainMetrics are used to track metrics for each chain // chainMetrics are used to track metrics for each chain
// they are reused for processors and databases of the same chain // they are reused for processors and databases of the same chain
chainMetrics locks.RWMap[types.ChainID, *chainMetrics] chainMetrics locks.RWMap[eth.ChainID, *chainMetrics]
emitter event.Emitter emitter event.Emitter
} }
...@@ -229,7 +229,7 @@ func (su *SupervisorBackend) initResources(ctx context.Context, cfg *config.Conf ...@@ -229,7 +229,7 @@ func (su *SupervisorBackend) initResources(ctx context.Context, cfg *config.Conf
// openChainDBs initializes all the DB resources of a specific chain. // openChainDBs initializes all the DB resources of a specific chain.
// It is a sub-task of initResources. // It is a sub-task of initResources.
func (su *SupervisorBackend) openChainDBs(chainID types.ChainID) error { func (su *SupervisorBackend) openChainDBs(chainID eth.ChainID) error {
cm := newChainMetrics(chainID, su.m) cm := newChainMetrics(chainID, su.m)
// create metrics and a logdb for the chain // create metrics and a logdb for the chain
su.chainMetrics.Set(chainID, cm) su.chainMetrics.Set(chainID, cm)
...@@ -280,7 +280,7 @@ func (su *SupervisorBackend) AttachSyncNode(ctx context.Context, src syncnode.Sy ...@@ -280,7 +280,7 @@ func (su *SupervisorBackend) AttachSyncNode(ctx context.Context, src syncnode.Sy
return su.syncNodesController.AttachNodeController(chainID, src, noSubscribe) return su.syncNodesController.AttachNodeController(chainID, src, noSubscribe)
} }
func (su *SupervisorBackend) AttachProcessorSource(chainID types.ChainID, src processors.Source) error { func (su *SupervisorBackend) AttachProcessorSource(chainID eth.ChainID, src processors.Source) error {
proc, ok := su.chainProcessors.Get(chainID) proc, ok := su.chainProcessors.Get(chainID)
if !ok { if !ok {
return fmt.Errorf("unknown chain %s, cannot attach RPC to processor", chainID) return fmt.Errorf("unknown chain %s, cannot attach RPC to processor", chainID)
...@@ -289,7 +289,7 @@ func (su *SupervisorBackend) AttachProcessorSource(chainID types.ChainID, src pr ...@@ -289,7 +289,7 @@ func (su *SupervisorBackend) AttachProcessorSource(chainID types.ChainID, src pr
return nil return nil
} }
func (su *SupervisorBackend) AttachSyncSource(chainID types.ChainID, src syncnode.SyncSource) error { func (su *SupervisorBackend) AttachSyncSource(chainID eth.ChainID, src syncnode.SyncSource) error {
_, ok := su.syncSources.Get(chainID) _, ok := su.syncSources.Get(chainID)
if !ok { if !ok {
return fmt.Errorf("unknown chain %s, cannot attach RPC to sync source", chainID) return fmt.Errorf("unknown chain %s, cannot attach RPC to sync source", chainID)
...@@ -429,7 +429,7 @@ func (su *SupervisorBackend) CheckMessages( ...@@ -429,7 +429,7 @@ func (su *SupervisorBackend) CheckMessages(
return nil return nil
} }
func (su *SupervisorBackend) CrossSafe(ctx context.Context, chainID types.ChainID) (types.DerivedIDPair, error) { func (su *SupervisorBackend) CrossSafe(ctx context.Context, chainID eth.ChainID) (types.DerivedIDPair, error) {
p, err := su.chainDBs.CrossSafe(chainID) p, err := su.chainDBs.CrossSafe(chainID)
if err != nil { if err != nil {
return types.DerivedIDPair{}, err return types.DerivedIDPair{}, err
...@@ -440,7 +440,7 @@ func (su *SupervisorBackend) CrossSafe(ctx context.Context, chainID types.ChainI ...@@ -440,7 +440,7 @@ func (su *SupervisorBackend) CrossSafe(ctx context.Context, chainID types.ChainI
}, nil }, nil
} }
func (su *SupervisorBackend) LocalSafe(ctx context.Context, chainID types.ChainID) (types.DerivedIDPair, error) { func (su *SupervisorBackend) LocalSafe(ctx context.Context, chainID eth.ChainID) (types.DerivedIDPair, error) {
p, err := su.chainDBs.LocalSafe(chainID) p, err := su.chainDBs.LocalSafe(chainID)
if err != nil { if err != nil {
return types.DerivedIDPair{}, err return types.DerivedIDPair{}, err
...@@ -451,7 +451,7 @@ func (su *SupervisorBackend) LocalSafe(ctx context.Context, chainID types.ChainI ...@@ -451,7 +451,7 @@ func (su *SupervisorBackend) LocalSafe(ctx context.Context, chainID types.ChainI
}, nil }, nil
} }
func (su *SupervisorBackend) LocalUnsafe(ctx context.Context, chainID types.ChainID) (eth.BlockID, error) { func (su *SupervisorBackend) LocalUnsafe(ctx context.Context, chainID eth.ChainID) (eth.BlockID, error) {
v, err := su.chainDBs.LocalUnsafe(chainID) v, err := su.chainDBs.LocalUnsafe(chainID)
if err != nil { if err != nil {
return eth.BlockID{}, err return eth.BlockID{}, err
...@@ -459,7 +459,7 @@ func (su *SupervisorBackend) LocalUnsafe(ctx context.Context, chainID types.Chai ...@@ -459,7 +459,7 @@ func (su *SupervisorBackend) LocalUnsafe(ctx context.Context, chainID types.Chai
return v.ID(), nil return v.ID(), nil
} }
func (su *SupervisorBackend) CrossUnsafe(ctx context.Context, chainID types.ChainID) (eth.BlockID, error) { func (su *SupervisorBackend) CrossUnsafe(ctx context.Context, chainID eth.ChainID) (eth.BlockID, error) {
v, err := su.chainDBs.CrossUnsafe(chainID) v, err := su.chainDBs.CrossUnsafe(chainID)
if err != nil { if err != nil {
return eth.BlockID{}, err return eth.BlockID{}, err
...@@ -467,7 +467,7 @@ func (su *SupervisorBackend) CrossUnsafe(ctx context.Context, chainID types.Chai ...@@ -467,7 +467,7 @@ func (su *SupervisorBackend) CrossUnsafe(ctx context.Context, chainID types.Chai
return v.ID(), nil return v.ID(), nil
} }
func (su *SupervisorBackend) SafeDerivedAt(ctx context.Context, chainID types.ChainID, derivedFrom eth.BlockID) (eth.BlockID, error) { func (su *SupervisorBackend) SafeDerivedAt(ctx context.Context, chainID eth.ChainID, derivedFrom eth.BlockID) (eth.BlockID, error) {
v, err := su.chainDBs.SafeDerivedAt(chainID, derivedFrom) v, err := su.chainDBs.SafeDerivedAt(chainID, derivedFrom)
if err != nil { if err != nil {
return eth.BlockID{}, err return eth.BlockID{}, err
...@@ -475,7 +475,7 @@ func (su *SupervisorBackend) SafeDerivedAt(ctx context.Context, chainID types.Ch ...@@ -475,7 +475,7 @@ func (su *SupervisorBackend) SafeDerivedAt(ctx context.Context, chainID types.Ch
return v.ID(), nil return v.ID(), nil
} }
func (su *SupervisorBackend) Finalized(ctx context.Context, chainID types.ChainID) (eth.BlockID, error) { func (su *SupervisorBackend) Finalized(ctx context.Context, chainID eth.ChainID) (eth.BlockID, error) {
v, err := su.chainDBs.Finalized(chainID) v, err := su.chainDBs.Finalized(chainID)
if err != nil { if err != nil {
return eth.BlockID{}, err return eth.BlockID{}, err
...@@ -487,7 +487,7 @@ func (su *SupervisorBackend) FinalizedL1() eth.BlockRef { ...@@ -487,7 +487,7 @@ func (su *SupervisorBackend) FinalizedL1() eth.BlockRef {
return su.chainDBs.FinalizedL1() return su.chainDBs.FinalizedL1()
} }
func (su *SupervisorBackend) CrossDerivedFrom(ctx context.Context, chainID types.ChainID, derived eth.BlockID) (derivedFrom eth.BlockRef, err error) { func (su *SupervisorBackend) CrossDerivedFrom(ctx context.Context, chainID eth.ChainID, derived eth.BlockID) (derivedFrom eth.BlockRef, err error) {
v, err := su.chainDBs.CrossDerivedFromBlockRef(chainID, derived) v, err := su.chainDBs.CrossDerivedFromBlockRef(chainID, derived)
if err != nil { if err != nil {
return eth.BlockRef{}, err return eth.BlockRef{}, err
...@@ -499,29 +499,29 @@ func (su *SupervisorBackend) L1BlockRefByNumber(ctx context.Context, number uint ...@@ -499,29 +499,29 @@ func (su *SupervisorBackend) L1BlockRefByNumber(ctx context.Context, number uint
return su.l1Accessor.L1BlockRefByNumber(ctx, number) return su.l1Accessor.L1BlockRefByNumber(ctx, number)
} }
func (su *SupervisorBackend) SuperRootAtTimestamp(ctx context.Context, timestamp hexutil.Uint64) (types.SuperRootResponse, error) { func (su *SupervisorBackend) SuperRootAtTimestamp(ctx context.Context, timestamp hexutil.Uint64) (eth.SuperRootResponse, error) {
chains := su.depSet.Chains() chains := su.depSet.Chains()
slices.SortFunc(chains, func(a, b types.ChainID) int { slices.SortFunc(chains, func(a, b eth.ChainID) int {
return a.Cmp(b) return a.Cmp(b)
}) })
chainInfos := make([]types.ChainRootInfo, len(chains)) chainInfos := make([]eth.ChainRootInfo, len(chains))
superRootChains := make([]eth.ChainIDAndOutput, len(chains)) superRootChains := make([]eth.ChainIDAndOutput, len(chains))
for i, chainID := range chains { for i, chainID := range chains {
src, ok := su.syncSources.Get(chainID) src, ok := su.syncSources.Get(chainID)
if !ok { if !ok {
su.logger.Error("bug: unknown chain %s, cannot get sync source", chainID) su.logger.Error("bug: unknown chain %s, cannot get sync source", chainID)
return types.SuperRootResponse{}, fmt.Errorf("unknown chain %s, cannot get sync source", chainID) return eth.SuperRootResponse{}, fmt.Errorf("unknown chain %s, cannot get sync source", chainID)
} }
output, err := src.OutputV0AtTimestamp(ctx, uint64(timestamp)) output, err := src.OutputV0AtTimestamp(ctx, uint64(timestamp))
if err != nil { if err != nil {
return types.SuperRootResponse{}, err return eth.SuperRootResponse{}, err
} }
pending, err := src.PendingOutputV0AtTimestamp(ctx, uint64(timestamp)) pending, err := src.PendingOutputV0AtTimestamp(ctx, uint64(timestamp))
if err != nil { if err != nil {
return types.SuperRootResponse{}, err return eth.SuperRootResponse{}, err
} }
canonicalRoot := eth.OutputRoot(output) canonicalRoot := eth.OutputRoot(output)
chainInfos[i] = types.ChainRootInfo{ chainInfos[i] = eth.ChainRootInfo{
ChainID: chainID, ChainID: chainID,
Canonical: canonicalRoot, Canonical: canonicalRoot,
Pending: pending.Marshal(), Pending: pending.Marshal(),
...@@ -532,7 +532,7 @@ func (su *SupervisorBackend) SuperRootAtTimestamp(ctx context.Context, timestamp ...@@ -532,7 +532,7 @@ func (su *SupervisorBackend) SuperRootAtTimestamp(ctx context.Context, timestamp
Timestamp: uint64(timestamp), Timestamp: uint64(timestamp),
Chains: superRootChains, Chains: superRootChains,
}) })
return types.SuperRootResponse{ return eth.SuperRootResponse{
Timestamp: uint64(timestamp), Timestamp: uint64(timestamp),
SuperRoot: superRoot, SuperRoot: superRoot,
Chains: chainInfos, Chains: chainInfos,
......
...@@ -34,10 +34,10 @@ func TestBackendLifetime(t *testing.T) { ...@@ -34,10 +34,10 @@ func TestBackendLifetime(t *testing.T) {
logger := testlog.Logger(t, log.LvlInfo) logger := testlog.Logger(t, log.LvlInfo)
m := metrics.NoopMetrics m := metrics.NoopMetrics
dataDir := t.TempDir() dataDir := t.TempDir()
chainA := types.ChainIDFromUInt64(900) chainA := eth.ChainIDFromUInt64(900)
chainB := types.ChainIDFromUInt64(901) chainB := eth.ChainIDFromUInt64(901)
depSet, err := depset.NewStaticConfigDependencySet( depSet, err := depset.NewStaticConfigDependencySet(
map[types.ChainID]*depset.StaticConfigDependency{ map[eth.ChainID]*depset.StaticConfigDependency{
chainA: { chainA: {
ChainIndex: 900, ChainIndex: 900,
ActivationTime: 42, ActivationTime: 42,
......
package backend package backend
import ( import (
"github.com/ethereum-optimism/optimism/op-service/eth"
"github.com/ethereum-optimism/optimism/op-service/sources/caching" "github.com/ethereum-optimism/optimism/op-service/sources/caching"
"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/backend/db/logs" "github.com/ethereum-optimism/optimism/op-supervisor/supervisor/backend/db/logs"
"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types"
) )
type Metrics interface { type Metrics interface {
CacheAdd(chainID types.ChainID, label string, cacheSize int, evicted bool) CacheAdd(chainID eth.ChainID, label string, cacheSize int, evicted bool)
CacheGet(chainID types.ChainID, label string, hit bool) CacheGet(chainID eth.ChainID, label string, hit bool)
RecordDBEntryCount(chainID types.ChainID, kind string, count int64) RecordDBEntryCount(chainID eth.ChainID, kind string, count int64)
RecordDBSearchEntriesRead(chainID types.ChainID, count int64) RecordDBSearchEntriesRead(chainID eth.ChainID, count int64)
} }
// chainMetrics is an adapter between the metrics API expected by clients that assume there's only a single chain // chainMetrics is an adapter between the metrics API expected by clients that assume there's only a single chain
// and the actual metrics implementation which requires a chain ID to identify the source chain. // and the actual metrics implementation which requires a chain ID to identify the source chain.
type chainMetrics struct { type chainMetrics struct {
chainID types.ChainID chainID eth.ChainID
delegate Metrics delegate Metrics
} }
func newChainMetrics(chainID types.ChainID, delegate Metrics) *chainMetrics { func newChainMetrics(chainID eth.ChainID, delegate Metrics) *chainMetrics {
return &chainMetrics{ return &chainMetrics{
chainID: chainID, chainID: chainID,
delegate: delegate, delegate: delegate,
......
...@@ -19,7 +19,7 @@ var ( ...@@ -19,7 +19,7 @@ var (
// CycleCheckDeps is an interface for checking cyclical dependencies between logs. // CycleCheckDeps is an interface for checking cyclical dependencies between logs.
type CycleCheckDeps interface { type CycleCheckDeps interface {
// OpenBlock returns log data for the requested block, to be used for cycle checking. // OpenBlock returns log data for the requested block, to be used for cycle checking.
OpenBlock(chainID types.ChainID, blockNum uint64) (block eth.BlockRef, logCount uint32, execMsgs map[uint32]*types.ExecutingMessage, err error) OpenBlock(chainID eth.ChainID, blockNum uint64) (block eth.BlockRef, logCount uint32, execMsgs map[uint32]*types.ExecutingMessage, err error)
} }
// node represents a log entry in the dependency graph. // node represents a log entry in the dependency graph.
......
...@@ -14,13 +14,13 @@ import ( ...@@ -14,13 +14,13 @@ import (
) )
type testDepSet struct { type testDepSet struct {
mapping map[types.ChainIndex]types.ChainID mapping map[types.ChainIndex]eth.ChainID
} }
func (t testDepSet) ChainIDFromIndex(index types.ChainIndex) (types.ChainID, error) { func (t testDepSet) ChainIDFromIndex(index types.ChainIndex) (eth.ChainID, error) {
v, ok := t.mapping[index] v, ok := t.mapping[index]
if !ok { if !ok {
return types.ChainID{}, types.ErrUnknownChain return eth.ChainID{}, types.ErrUnknownChain
} }
return v, nil return v, nil
} }
...@@ -28,10 +28,10 @@ func (t testDepSet) ChainIDFromIndex(index types.ChainIndex) (types.ChainID, err ...@@ -28,10 +28,10 @@ func (t testDepSet) ChainIDFromIndex(index types.ChainIndex) (types.ChainID, err
var _ depset.ChainIDFromIndex = (*testDepSet)(nil) var _ depset.ChainIDFromIndex = (*testDepSet)(nil)
type mockCycleCheckDeps struct { type mockCycleCheckDeps struct {
openBlockFn func(chainID types.ChainID, blockNum uint64) (eth.BlockRef, uint32, map[uint32]*types.ExecutingMessage, error) openBlockFn func(chainID eth.ChainID, blockNum uint64) (eth.BlockRef, uint32, map[uint32]*types.ExecutingMessage, error)
} }
func (m *mockCycleCheckDeps) OpenBlock(chainID types.ChainID, blockNum uint64) (eth.BlockRef, uint32, map[uint32]*types.ExecutingMessage, error) { func (m *mockCycleCheckDeps) OpenBlock(chainID eth.ChainID, blockNum uint64) (eth.BlockRef, uint32, map[uint32]*types.ExecutingMessage, error) {
return m.openBlockFn(chainID, blockNum) return m.openBlockFn(chainID, blockNum)
} }
...@@ -49,7 +49,7 @@ type hazardCycleChecksTestCase struct { ...@@ -49,7 +49,7 @@ type hazardCycleChecksTestCase struct {
// Optional overrides // Optional overrides
hazards map[types.ChainIndex]types.BlockSeal hazards map[types.ChainIndex]types.BlockSeal
openBlockFn func(chainID types.ChainID, blockNum uint64) (eth.BlockRef, uint32, map[uint32]*types.ExecutingMessage, error) openBlockFn func(chainID eth.ChainID, blockNum uint64) (eth.BlockRef, uint32, map[uint32]*types.ExecutingMessage, error)
} }
func runHazardCycleChecksTestCaseGroup(t *testing.T, group string, tests []hazardCycleChecksTestCase) { func runHazardCycleChecksTestCaseGroup(t *testing.T, group string, tests []hazardCycleChecksTestCase) {
...@@ -63,7 +63,7 @@ func runHazardCycleChecksTestCaseGroup(t *testing.T, group string, tests []hazar ...@@ -63,7 +63,7 @@ func runHazardCycleChecksTestCaseGroup(t *testing.T, group string, tests []hazar
func runHazardCycleChecksTestCase(t *testing.T, tc hazardCycleChecksTestCase) { func runHazardCycleChecksTestCase(t *testing.T, tc hazardCycleChecksTestCase) {
// Create mocked dependencies // Create mocked dependencies
deps := &mockCycleCheckDeps{ deps := &mockCycleCheckDeps{
openBlockFn: func(chainID types.ChainID, blockNum uint64) (eth.BlockRef, uint32, map[uint32]*types.ExecutingMessage, error) { openBlockFn: func(chainID eth.ChainID, blockNum uint64) (eth.BlockRef, uint32, map[uint32]*types.ExecutingMessage, error) {
// Use override if provided // Use override if provided
if tc.openBlockFn != nil { if tc.openBlockFn != nil {
return tc.openBlockFn(chainID, blockNum) return tc.openBlockFn(chainID, blockNum)
...@@ -94,11 +94,11 @@ func runHazardCycleChecksTestCase(t *testing.T, tc hazardCycleChecksTestCase) { ...@@ -94,11 +94,11 @@ func runHazardCycleChecksTestCase(t *testing.T, tc hazardCycleChecksTestCase) {
} }
depSet := &testDepSet{ depSet := &testDepSet{
mapping: make(map[types.ChainIndex]types.ChainID), mapping: make(map[types.ChainIndex]eth.ChainID),
} }
for chainStr := range tc.chainBlocks { for chainStr := range tc.chainBlocks {
index := chainIndex(chainStr) index := chainIndex(chainStr)
depSet.mapping[index] = types.ChainIDFromUInt64(uint64(index)) depSet.mapping[index] = eth.ChainIDFromUInt64(uint64(index))
} }
// Run the test // Run the test
err := HazardCycleChecks(depSet, deps, 100, hazards) err := HazardCycleChecks(depSet, deps, 100, hazards)
...@@ -172,7 +172,7 @@ func TestHazardCycleChecksFailures(t *testing.T) { ...@@ -172,7 +172,7 @@ func TestHazardCycleChecksFailures(t *testing.T) {
{ {
name: "failed to open block error", name: "failed to open block error",
chainBlocks: emptyChainBlocks, chainBlocks: emptyChainBlocks,
openBlockFn: func(chainID types.ChainID, blockNum uint64) (eth.BlockRef, uint32, map[uint32]*types.ExecutingMessage, error) { openBlockFn: func(chainID eth.ChainID, blockNum uint64) (eth.BlockRef, uint32, map[uint32]*types.ExecutingMessage, error) {
return eth.BlockRef{}, 0, nil, testOpenBlockErr return eth.BlockRef{}, 0, nil, testOpenBlockErr
}, },
expectErr: errors.New("failed to open block"), expectErr: errors.New("failed to open block"),
...@@ -182,7 +182,7 @@ func TestHazardCycleChecksFailures(t *testing.T) { ...@@ -182,7 +182,7 @@ func TestHazardCycleChecksFailures(t *testing.T) {
name: "block mismatch error", name: "block mismatch error",
chainBlocks: emptyChainBlocks, chainBlocks: emptyChainBlocks,
// openBlockFn returns a block number that doesn't match the expected block number. // openBlockFn returns a block number that doesn't match the expected block number.
openBlockFn: func(chainID types.ChainID, blockNum uint64) (eth.BlockRef, uint32, map[uint32]*types.ExecutingMessage, error) { openBlockFn: func(chainID eth.ChainID, blockNum uint64) (eth.BlockRef, uint32, map[uint32]*types.ExecutingMessage, error) {
return eth.BlockRef{Number: blockNum + 1}, 0, make(map[uint32]*types.ExecutingMessage), nil return eth.BlockRef{Number: blockNum + 1}, 0, make(map[uint32]*types.ExecutingMessage), nil
}, },
expectErr: errors.New("tried to open block"), expectErr: errors.New("tried to open block"),
......
...@@ -10,9 +10,9 @@ import ( ...@@ -10,9 +10,9 @@ import (
) )
type SafeFrontierCheckDeps interface { type SafeFrontierCheckDeps interface {
CandidateCrossSafe(chain types.ChainID) (derivedFromScope, crossSafe eth.BlockRef, err error) CandidateCrossSafe(chain eth.ChainID) (derivedFromScope, crossSafe eth.BlockRef, err error)
CrossDerivedFrom(chainID types.ChainID, derived eth.BlockID) (derivedFrom types.BlockSeal, err error) CrossDerivedFrom(chainID eth.ChainID, derived eth.BlockID) (derivedFrom types.BlockSeal, err error)
DependencySet() depset.DependencySet DependencySet() depset.DependencySet
} }
......
...@@ -24,8 +24,8 @@ func TestHazardSafeFrontierChecks(t *testing.T) { ...@@ -24,8 +24,8 @@ func TestHazardSafeFrontierChecks(t *testing.T) {
t.Run("unknown chain", func(t *testing.T) { t.Run("unknown chain", func(t *testing.T) {
sfcd := &mockSafeFrontierCheckDeps{ sfcd := &mockSafeFrontierCheckDeps{
deps: mockDependencySet{ deps: mockDependencySet{
chainIDFromIndexfn: func() (types.ChainID, error) { chainIDFromIndexfn: func() (eth.ChainID, error) {
return types.ChainID{}, types.ErrUnknownChain return eth.ChainID{}, types.ErrUnknownChain
}, },
}, },
} }
...@@ -143,14 +143,14 @@ type mockSafeFrontierCheckDeps struct { ...@@ -143,14 +143,14 @@ type mockSafeFrontierCheckDeps struct {
crossDerivedFromFn func() (derivedFrom types.BlockSeal, err error) crossDerivedFromFn func() (derivedFrom types.BlockSeal, err error)
} }
func (m *mockSafeFrontierCheckDeps) CandidateCrossSafe(chain types.ChainID) (derivedFromScope, crossSafe eth.BlockRef, err error) { func (m *mockSafeFrontierCheckDeps) CandidateCrossSafe(chain eth.ChainID) (derivedFromScope, crossSafe eth.BlockRef, err error) {
if m.candidateCrossSafeFn != nil { if m.candidateCrossSafeFn != nil {
return m.candidateCrossSafeFn() return m.candidateCrossSafeFn()
} }
return eth.BlockRef{}, eth.BlockRef{}, nil return eth.BlockRef{}, eth.BlockRef{}, nil
} }
func (m *mockSafeFrontierCheckDeps) CrossDerivedFrom(chainID types.ChainID, derived eth.BlockID) (derivedFrom types.BlockSeal, err error) { func (m *mockSafeFrontierCheckDeps) CrossDerivedFrom(chainID eth.ChainID, derived eth.BlockID) (derivedFrom types.BlockSeal, err error) {
if m.crossDerivedFromFn != nil { if m.crossDerivedFromFn != nil {
return m.crossDerivedFromFn() return m.crossDerivedFromFn()
} }
...@@ -162,34 +162,34 @@ func (m *mockSafeFrontierCheckDeps) DependencySet() depset.DependencySet { ...@@ -162,34 +162,34 @@ func (m *mockSafeFrontierCheckDeps) DependencySet() depset.DependencySet {
} }
type mockDependencySet struct { type mockDependencySet struct {
chainIDFromIndexfn func() (types.ChainID, error) chainIDFromIndexfn func() (eth.ChainID, error)
canExecuteAtfn func() (bool, error) canExecuteAtfn func() (bool, error)
canInitiateAtfn func() (bool, error) canInitiateAtfn func() (bool, error)
} }
func (m mockDependencySet) CanExecuteAt(chain types.ChainID, timestamp uint64) (bool, error) { func (m mockDependencySet) CanExecuteAt(chain eth.ChainID, timestamp uint64) (bool, error) {
if m.canExecuteAtfn != nil { if m.canExecuteAtfn != nil {
return m.canExecuteAtfn() return m.canExecuteAtfn()
} }
return true, nil return true, nil
} }
func (m mockDependencySet) CanInitiateAt(chain types.ChainID, timestamp uint64) (bool, error) { func (m mockDependencySet) CanInitiateAt(chain eth.ChainID, timestamp uint64) (bool, error) {
if m.canInitiateAtfn != nil { if m.canInitiateAtfn != nil {
return m.canInitiateAtfn() return m.canInitiateAtfn()
} }
return true, nil return true, nil
} }
func (m mockDependencySet) ChainIDFromIndex(index types.ChainIndex) (types.ChainID, error) { func (m mockDependencySet) ChainIDFromIndex(index types.ChainIndex) (eth.ChainID, error) {
if m.chainIDFromIndexfn != nil { if m.chainIDFromIndexfn != nil {
return m.chainIDFromIndexfn() return m.chainIDFromIndexfn()
} }
id := types.ChainIDFromUInt64(uint64(index) - 1000) id := eth.ChainIDFromUInt64(uint64(index) - 1000)
return id, nil return id, nil
} }
func (m mockDependencySet) ChainIndexFromID(chain types.ChainID) (types.ChainIndex, error) { func (m mockDependencySet) ChainIndexFromID(chain eth.ChainID) (types.ChainIndex, error) {
v, err := chain.ToUInt32() v, err := chain.ToUInt32()
if err != nil { if err != nil {
return 0, err return 0, err
...@@ -198,10 +198,10 @@ func (m mockDependencySet) ChainIndexFromID(chain types.ChainID) (types.ChainInd ...@@ -198,10 +198,10 @@ func (m mockDependencySet) ChainIndexFromID(chain types.ChainID) (types.ChainInd
return types.ChainIndex(v + 1000), nil return types.ChainIndex(v + 1000), nil
} }
func (m mockDependencySet) Chains() []types.ChainID { func (m mockDependencySet) Chains() []eth.ChainID {
return nil return nil
} }
func (m mockDependencySet) HasChain(chain types.ChainID) bool { func (m mockDependencySet) HasChain(chain eth.ChainID) bool {
return true return true
} }
...@@ -12,9 +12,9 @@ import ( ...@@ -12,9 +12,9 @@ import (
) )
type SafeStartDeps interface { type SafeStartDeps interface {
Check(chain types.ChainID, blockNum uint64, timestamp uint64, logIdx uint32, logHash common.Hash) (includedIn types.BlockSeal, err error) Check(chain eth.ChainID, blockNum uint64, timestamp uint64, logIdx uint32, logHash common.Hash) (includedIn types.BlockSeal, err error)
CrossDerivedFrom(chainID types.ChainID, derived eth.BlockID) (derivedFrom types.BlockSeal, err error) CrossDerivedFrom(chainID eth.ChainID, derived eth.BlockID) (derivedFrom types.BlockSeal, err error)
DependencySet() depset.DependencySet DependencySet() depset.DependencySet
} }
...@@ -22,7 +22,7 @@ type SafeStartDeps interface { ...@@ -22,7 +22,7 @@ type SafeStartDeps interface {
// CrossSafeHazards checks if the given messages all exist and pass invariants. // CrossSafeHazards checks if the given messages all exist and pass invariants.
// It returns a hazard-set: if any intra-block messaging happened, // It returns a hazard-set: if any intra-block messaging happened,
// these hazard blocks have to be verified. // these hazard blocks have to be verified.
func CrossSafeHazards(d SafeStartDeps, chainID types.ChainID, inL1DerivedFrom eth.BlockID, func CrossSafeHazards(d SafeStartDeps, chainID eth.ChainID, inL1DerivedFrom eth.BlockID,
candidate types.BlockSeal, execMsgs []*types.ExecutingMessage) (hazards map[types.ChainIndex]types.BlockSeal, err error) { candidate types.BlockSeal, execMsgs []*types.ExecutingMessage) (hazards map[types.ChainIndex]types.BlockSeal, err error) {
hazards = make(map[types.ChainIndex]types.BlockSeal) hazards = make(map[types.ChainIndex]types.BlockSeal)
......
...@@ -14,7 +14,7 @@ import ( ...@@ -14,7 +14,7 @@ import (
func TestCrossSafeHazards(t *testing.T) { func TestCrossSafeHazards(t *testing.T) {
t.Run("empty execMsgs", func(t *testing.T) { t.Run("empty execMsgs", func(t *testing.T) {
ssd := &mockSafeStartDeps{} ssd := &mockSafeStartDeps{}
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
inL1DerivedFrom := eth.BlockID{} inL1DerivedFrom := eth.BlockID{}
candidate := types.BlockSeal{} candidate := types.BlockSeal{}
execMsgs := []*types.ExecutingMessage{} execMsgs := []*types.ExecutingMessage{}
...@@ -31,7 +31,7 @@ func TestCrossSafeHazards(t *testing.T) { ...@@ -31,7 +31,7 @@ func TestCrossSafeHazards(t *testing.T) {
return false, nil return false, nil
}, },
} }
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
inL1DerivedFrom := eth.BlockID{} inL1DerivedFrom := eth.BlockID{}
candidate := types.BlockSeal{} candidate := types.BlockSeal{}
execMsgs := []*types.ExecutingMessage{{}} execMsgs := []*types.ExecutingMessage{{}}
...@@ -48,7 +48,7 @@ func TestCrossSafeHazards(t *testing.T) { ...@@ -48,7 +48,7 @@ func TestCrossSafeHazards(t *testing.T) {
return false, errors.New("some error") return false, errors.New("some error")
}, },
} }
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
inL1DerivedFrom := eth.BlockID{} inL1DerivedFrom := eth.BlockID{}
candidate := types.BlockSeal{} candidate := types.BlockSeal{}
execMsgs := []*types.ExecutingMessage{{}} execMsgs := []*types.ExecutingMessage{{}}
...@@ -61,11 +61,11 @@ func TestCrossSafeHazards(t *testing.T) { ...@@ -61,11 +61,11 @@ func TestCrossSafeHazards(t *testing.T) {
t.Run("unknown chain", func(t *testing.T) { t.Run("unknown chain", func(t *testing.T) {
ssd := &mockSafeStartDeps{} ssd := &mockSafeStartDeps{}
ssd.deps = mockDependencySet{ ssd.deps = mockDependencySet{
chainIDFromIndexfn: func() (types.ChainID, error) { chainIDFromIndexfn: func() (eth.ChainID, error) {
return types.ChainID{}, types.ErrUnknownChain return eth.ChainID{}, types.ErrUnknownChain
}, },
} }
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
inL1DerivedFrom := eth.BlockID{} inL1DerivedFrom := eth.BlockID{}
candidate := types.BlockSeal{} candidate := types.BlockSeal{}
execMsgs := []*types.ExecutingMessage{{}} execMsgs := []*types.ExecutingMessage{{}}
...@@ -78,11 +78,11 @@ func TestCrossSafeHazards(t *testing.T) { ...@@ -78,11 +78,11 @@ func TestCrossSafeHazards(t *testing.T) {
t.Run("ChainIDFromUInt64 returns error", func(t *testing.T) { t.Run("ChainIDFromUInt64 returns error", func(t *testing.T) {
ssd := &mockSafeStartDeps{} ssd := &mockSafeStartDeps{}
ssd.deps = mockDependencySet{ ssd.deps = mockDependencySet{
chainIDFromIndexfn: func() (types.ChainID, error) { chainIDFromIndexfn: func() (eth.ChainID, error) {
return types.ChainID{}, errors.New("some error") return eth.ChainID{}, errors.New("some error")
}, },
} }
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
inL1DerivedFrom := eth.BlockID{} inL1DerivedFrom := eth.BlockID{}
candidate := types.BlockSeal{} candidate := types.BlockSeal{}
execMsgs := []*types.ExecutingMessage{{}} execMsgs := []*types.ExecutingMessage{{}}
...@@ -99,7 +99,7 @@ func TestCrossSafeHazards(t *testing.T) { ...@@ -99,7 +99,7 @@ func TestCrossSafeHazards(t *testing.T) {
return false, nil return false, nil
}, },
} }
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
inL1DerivedFrom := eth.BlockID{} inL1DerivedFrom := eth.BlockID{}
candidate := types.BlockSeal{} candidate := types.BlockSeal{}
execMsgs := []*types.ExecutingMessage{{}} execMsgs := []*types.ExecutingMessage{{}}
...@@ -116,7 +116,7 @@ func TestCrossSafeHazards(t *testing.T) { ...@@ -116,7 +116,7 @@ func TestCrossSafeHazards(t *testing.T) {
return false, errors.New("some error") return false, errors.New("some error")
}, },
} }
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
inL1DerivedFrom := eth.BlockID{} inL1DerivedFrom := eth.BlockID{}
candidate := types.BlockSeal{} candidate := types.BlockSeal{}
execMsgs := []*types.ExecutingMessage{{}} execMsgs := []*types.ExecutingMessage{{}}
...@@ -129,7 +129,7 @@ func TestCrossSafeHazards(t *testing.T) { ...@@ -129,7 +129,7 @@ func TestCrossSafeHazards(t *testing.T) {
t.Run("timestamp is greater than candidate", func(t *testing.T) { t.Run("timestamp is greater than candidate", func(t *testing.T) {
ssd := &mockSafeStartDeps{} ssd := &mockSafeStartDeps{}
ssd.deps = mockDependencySet{} ssd.deps = mockDependencySet{}
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
inL1DerivedFrom := eth.BlockID{} inL1DerivedFrom := eth.BlockID{}
candidate := types.BlockSeal{Timestamp: 2} candidate := types.BlockSeal{Timestamp: 2}
em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 10} em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 10}
...@@ -146,7 +146,7 @@ func TestCrossSafeHazards(t *testing.T) { ...@@ -146,7 +146,7 @@ func TestCrossSafeHazards(t *testing.T) {
return types.BlockSeal{}, errors.New("some error") return types.BlockSeal{}, errors.New("some error")
} }
ssd.deps = mockDependencySet{} ssd.deps = mockDependencySet{}
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
inL1DerivedFrom := eth.BlockID{} inL1DerivedFrom := eth.BlockID{}
candidate := types.BlockSeal{Timestamp: 2} candidate := types.BlockSeal{Timestamp: 2}
em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 2} em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 2}
...@@ -165,7 +165,7 @@ func TestCrossSafeHazards(t *testing.T) { ...@@ -165,7 +165,7 @@ func TestCrossSafeHazards(t *testing.T) {
return sampleBlockSeal, nil return sampleBlockSeal, nil
} }
ssd.deps = mockDependencySet{} ssd.deps = mockDependencySet{}
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
inL1DerivedFrom := eth.BlockID{} inL1DerivedFrom := eth.BlockID{}
candidate := types.BlockSeal{Timestamp: 2} candidate := types.BlockSeal{Timestamp: 2}
em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 2} em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 2}
...@@ -192,7 +192,7 @@ func TestCrossSafeHazards(t *testing.T) { ...@@ -192,7 +192,7 @@ func TestCrossSafeHazards(t *testing.T) {
return sampleBlockSeal2, nil return sampleBlockSeal2, nil
} }
ssd.deps = mockDependencySet{} ssd.deps = mockDependencySet{}
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
inL1DerivedFrom := eth.BlockID{} inL1DerivedFrom := eth.BlockID{}
candidate := types.BlockSeal{Timestamp: 2} candidate := types.BlockSeal{Timestamp: 2}
em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 2} em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 2}
...@@ -211,7 +211,7 @@ func TestCrossSafeHazards(t *testing.T) { ...@@ -211,7 +211,7 @@ func TestCrossSafeHazards(t *testing.T) {
return types.BlockSeal{}, errors.New("some error") return types.BlockSeal{}, errors.New("some error")
} }
ssd.deps = mockDependencySet{} ssd.deps = mockDependencySet{}
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
inL1DerivedFrom := eth.BlockID{} inL1DerivedFrom := eth.BlockID{}
candidate := types.BlockSeal{Timestamp: 2} candidate := types.BlockSeal{Timestamp: 2}
em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 1} em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 1}
...@@ -233,7 +233,7 @@ func TestCrossSafeHazards(t *testing.T) { ...@@ -233,7 +233,7 @@ func TestCrossSafeHazards(t *testing.T) {
return types.BlockSeal{}, errors.New("some error") return types.BlockSeal{}, errors.New("some error")
} }
ssd.deps = mockDependencySet{} ssd.deps = mockDependencySet{}
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
inL1DerivedFrom := eth.BlockID{} inL1DerivedFrom := eth.BlockID{}
candidate := types.BlockSeal{Timestamp: 2} candidate := types.BlockSeal{Timestamp: 2}
em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 1} em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 1}
...@@ -256,7 +256,7 @@ func TestCrossSafeHazards(t *testing.T) { ...@@ -256,7 +256,7 @@ func TestCrossSafeHazards(t *testing.T) {
return sampleDerivedFrom, nil return sampleDerivedFrom, nil
} }
ssd.deps = mockDependencySet{} ssd.deps = mockDependencySet{}
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
inL1DerivedFrom := eth.BlockID{} inL1DerivedFrom := eth.BlockID{}
candidate := types.BlockSeal{Timestamp: 2} candidate := types.BlockSeal{Timestamp: 2}
em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 1} em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 1}
...@@ -279,7 +279,7 @@ func TestCrossSafeHazards(t *testing.T) { ...@@ -279,7 +279,7 @@ func TestCrossSafeHazards(t *testing.T) {
return sampleDerivedFrom, nil return sampleDerivedFrom, nil
} }
ssd.deps = mockDependencySet{} ssd.deps = mockDependencySet{}
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
inL1DerivedFrom := eth.BlockID{Number: 10} inL1DerivedFrom := eth.BlockID{Number: 10}
candidate := types.BlockSeal{Timestamp: 2} candidate := types.BlockSeal{Timestamp: 2}
em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 1} em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 1}
...@@ -302,7 +302,7 @@ func TestCrossSafeHazards(t *testing.T) { ...@@ -302,7 +302,7 @@ func TestCrossSafeHazards(t *testing.T) {
return sampleDerivedFrom, nil return sampleDerivedFrom, nil
} }
ssd.deps = mockDependencySet{} ssd.deps = mockDependencySet{}
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
inL1DerivedFrom := eth.BlockID{Number: 1} inL1DerivedFrom := eth.BlockID{Number: 1}
candidate := types.BlockSeal{Timestamp: 2} candidate := types.BlockSeal{Timestamp: 2}
em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 1} em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 1}
...@@ -322,14 +322,14 @@ type mockSafeStartDeps struct { ...@@ -322,14 +322,14 @@ type mockSafeStartDeps struct {
derivedFromFn func() (derivedFrom types.BlockSeal, err error) derivedFromFn func() (derivedFrom types.BlockSeal, err error)
} }
func (m *mockSafeStartDeps) Check(chain types.ChainID, blockNum uint64, timestamp uint64, logIdx uint32, logHash common.Hash) (includedIn types.BlockSeal, err error) { func (m *mockSafeStartDeps) Check(chain eth.ChainID, blockNum uint64, timestamp uint64, logIdx uint32, logHash common.Hash) (includedIn types.BlockSeal, err error) {
if m.checkFn != nil { if m.checkFn != nil {
return m.checkFn() return m.checkFn()
} }
return types.BlockSeal{}, nil return types.BlockSeal{}, nil
} }
func (m *mockSafeStartDeps) CrossDerivedFrom(chainID types.ChainID, derived eth.BlockID) (derivedFrom types.BlockSeal, err error) { func (m *mockSafeStartDeps) CrossDerivedFrom(chainID eth.ChainID, derived eth.BlockID) (derivedFrom types.BlockSeal, err error) {
if m.derivedFromFn != nil { if m.derivedFromFn != nil {
return m.derivedFromFn() return m.derivedFromFn()
} }
......
...@@ -13,21 +13,21 @@ import ( ...@@ -13,21 +13,21 @@ import (
) )
type CrossSafeDeps interface { type CrossSafeDeps interface {
CrossSafe(chainID types.ChainID) (pair types.DerivedBlockSealPair, err error) CrossSafe(chainID eth.ChainID) (pair types.DerivedBlockSealPair, err error)
SafeFrontierCheckDeps SafeFrontierCheckDeps
SafeStartDeps SafeStartDeps
CandidateCrossSafe(chain types.ChainID) (derivedFromScope, crossSafe eth.BlockRef, err error) CandidateCrossSafe(chain eth.ChainID) (derivedFromScope, crossSafe eth.BlockRef, err error)
NextDerivedFrom(chain types.ChainID, derivedFrom eth.BlockID) (after eth.BlockRef, err error) NextDerivedFrom(chain eth.ChainID, derivedFrom eth.BlockID) (after eth.BlockRef, err error)
PreviousDerived(chain types.ChainID, derived eth.BlockID) (prevDerived types.BlockSeal, err error) PreviousDerived(chain eth.ChainID, derived eth.BlockID) (prevDerived types.BlockSeal, err error)
OpenBlock(chainID types.ChainID, blockNum uint64) (ref eth.BlockRef, logCount uint32, execMsgs map[uint32]*types.ExecutingMessage, err error) OpenBlock(chainID eth.ChainID, blockNum uint64) (ref eth.BlockRef, logCount uint32, execMsgs map[uint32]*types.ExecutingMessage, err error)
UpdateCrossSafe(chain types.ChainID, l1View eth.BlockRef, lastCrossDerived eth.BlockRef) error UpdateCrossSafe(chain eth.ChainID, l1View eth.BlockRef, lastCrossDerived eth.BlockRef) error
} }
func CrossSafeUpdate(logger log.Logger, chainID types.ChainID, d CrossSafeDeps) error { func CrossSafeUpdate(logger log.Logger, chainID eth.ChainID, d CrossSafeDeps) error {
logger.Debug("Cross-safe update call") logger.Debug("Cross-safe update call")
// TODO(#11693): establish L1 reorg-lock of scopeDerivedFrom // TODO(#11693): establish L1 reorg-lock of scopeDerivedFrom
// defer unlock once we are done checking the chain // defer unlock once we are done checking the chain
...@@ -70,7 +70,7 @@ func CrossSafeUpdate(logger log.Logger, chainID types.ChainID, d CrossSafeDeps) ...@@ -70,7 +70,7 @@ func CrossSafeUpdate(logger log.Logger, chainID types.ChainID, d CrossSafeDeps)
// If no L2 cross-safe progress can be made without additional L1 input data, // If no L2 cross-safe progress can be made without additional L1 input data,
// then a types.ErrOutOfScope error is returned, // then a types.ErrOutOfScope error is returned,
// with the current scope that will need to be expanded for further progress. // with the current scope that will need to be expanded for further progress.
func scopedCrossSafeUpdate(logger log.Logger, chainID types.ChainID, d CrossSafeDeps) (scope eth.BlockRef, err error) { func scopedCrossSafeUpdate(logger log.Logger, chainID eth.ChainID, d CrossSafeDeps) (scope eth.BlockRef, err error) {
candidateScope, candidate, err := d.CandidateCrossSafe(chainID) candidateScope, candidate, err := d.CandidateCrossSafe(chainID)
if err != nil { if err != nil {
return candidateScope, fmt.Errorf("failed to determine candidate block for cross-safe: %w", err) return candidateScope, fmt.Errorf("failed to determine candidate block for cross-safe: %w", err)
...@@ -111,7 +111,7 @@ func sliceOfExecMsgs(execMsgs map[uint32]*types.ExecutingMessage) []*types.Execu ...@@ -111,7 +111,7 @@ func sliceOfExecMsgs(execMsgs map[uint32]*types.ExecutingMessage) []*types.Execu
type CrossSafeWorker struct { type CrossSafeWorker struct {
logger log.Logger logger log.Logger
chainID types.ChainID chainID eth.ChainID
d CrossSafeDeps d CrossSafeDeps
} }
...@@ -136,7 +136,7 @@ func (c *CrossSafeWorker) OnEvent(ev event.Event) bool { ...@@ -136,7 +136,7 @@ func (c *CrossSafeWorker) OnEvent(ev event.Event) bool {
var _ event.Deriver = (*CrossUnsafeWorker)(nil) var _ event.Deriver = (*CrossUnsafeWorker)(nil)
func NewCrossSafeWorker(logger log.Logger, chainID types.ChainID, d CrossSafeDeps) *CrossSafeWorker { func NewCrossSafeWorker(logger log.Logger, chainID eth.ChainID, d CrossSafeDeps) *CrossSafeWorker {
logger = logger.New("chain", chainID) logger = logger.New("chain", chainID)
return &CrossSafeWorker{ return &CrossSafeWorker{
logger: logger, logger: logger,
......
...@@ -10,10 +10,10 @@ import ( ...@@ -10,10 +10,10 @@ import (
) )
type UnsafeFrontierCheckDeps interface { type UnsafeFrontierCheckDeps interface {
ParentBlock(chainID types.ChainID, parentOf eth.BlockID) (parent eth.BlockID, err error) ParentBlock(chainID eth.ChainID, parentOf eth.BlockID) (parent eth.BlockID, err error)
IsCrossUnsafe(chainID types.ChainID, block eth.BlockID) error IsCrossUnsafe(chainID eth.ChainID, block eth.BlockID) error
IsLocalUnsafe(chainID types.ChainID, block eth.BlockID) error IsLocalUnsafe(chainID eth.ChainID, block eth.BlockID) error
DependencySet() depset.DependencySet DependencySet() depset.DependencySet
} }
......
...@@ -23,8 +23,8 @@ func TestHazardUnsafeFrontierChecks(t *testing.T) { ...@@ -23,8 +23,8 @@ func TestHazardUnsafeFrontierChecks(t *testing.T) {
t.Run("unknown chain", func(t *testing.T) { t.Run("unknown chain", func(t *testing.T) {
ufcd := &mockUnsafeFrontierCheckDeps{ ufcd := &mockUnsafeFrontierCheckDeps{
deps: mockDependencySet{ deps: mockDependencySet{
chainIDFromIndexfn: func() (types.ChainID, error) { chainIDFromIndexfn: func() (eth.ChainID, error) {
return types.ChainID{}, types.ErrUnknownChain return eth.ChainID{}, types.ErrUnknownChain
}, },
}, },
} }
...@@ -114,17 +114,17 @@ func (m *mockUnsafeFrontierCheckDeps) DependencySet() depset.DependencySet { ...@@ -114,17 +114,17 @@ func (m *mockUnsafeFrontierCheckDeps) DependencySet() depset.DependencySet {
return m.deps return m.deps
} }
func (m *mockUnsafeFrontierCheckDeps) ParentBlock(chainID types.ChainID, block eth.BlockID) (parent eth.BlockID, err error) { func (m *mockUnsafeFrontierCheckDeps) ParentBlock(chainID eth.ChainID, block eth.BlockID) (parent eth.BlockID, err error) {
if m.parentBlockFn != nil { if m.parentBlockFn != nil {
return m.parentBlockFn() return m.parentBlockFn()
} }
return eth.BlockID{}, nil return eth.BlockID{}, nil
} }
func (m *mockUnsafeFrontierCheckDeps) IsCrossUnsafe(chainID types.ChainID, block eth.BlockID) error { func (m *mockUnsafeFrontierCheckDeps) IsCrossUnsafe(chainID eth.ChainID, block eth.BlockID) error {
return m.isCrossUnsafe return m.isCrossUnsafe
} }
func (m *mockUnsafeFrontierCheckDeps) IsLocalUnsafe(chainID types.ChainID, block eth.BlockID) error { func (m *mockUnsafeFrontierCheckDeps) IsLocalUnsafe(chainID eth.ChainID, block eth.BlockID) error {
return m.isLocalUnsafe return m.isLocalUnsafe
} }
...@@ -12,9 +12,9 @@ import ( ...@@ -12,9 +12,9 @@ import (
) )
type UnsafeStartDeps interface { type UnsafeStartDeps interface {
Check(chain types.ChainID, blockNum uint64, timestamp uint64, logIdx uint32, logHash common.Hash) (includedIn types.BlockSeal, err error) Check(chain eth.ChainID, blockNum uint64, timestamp uint64, logIdx uint32, logHash common.Hash) (includedIn types.BlockSeal, err error)
IsCrossUnsafe(chainID types.ChainID, block eth.BlockID) error IsCrossUnsafe(chainID eth.ChainID, block eth.BlockID) error
DependencySet() depset.DependencySet DependencySet() depset.DependencySet
} }
...@@ -22,7 +22,7 @@ type UnsafeStartDeps interface { ...@@ -22,7 +22,7 @@ type UnsafeStartDeps interface {
// CrossUnsafeHazards checks if the given messages all exist and pass invariants. // CrossUnsafeHazards checks if the given messages all exist and pass invariants.
// It returns a hazard-set: if any intra-block messaging happened, // It returns a hazard-set: if any intra-block messaging happened,
// these hazard blocks have to be verified. // these hazard blocks have to be verified.
func CrossUnsafeHazards(d UnsafeStartDeps, chainID types.ChainID, func CrossUnsafeHazards(d UnsafeStartDeps, chainID eth.ChainID,
candidate types.BlockSeal, execMsgs []*types.ExecutingMessage) (hazards map[types.ChainIndex]types.BlockSeal, err error) { candidate types.BlockSeal, execMsgs []*types.ExecutingMessage) (hazards map[types.ChainIndex]types.BlockSeal, err error) {
hazards = make(map[types.ChainIndex]types.BlockSeal) hazards = make(map[types.ChainIndex]types.BlockSeal)
......
...@@ -14,7 +14,7 @@ import ( ...@@ -14,7 +14,7 @@ import (
func TestCrossUnsafeHazards(t *testing.T) { func TestCrossUnsafeHazards(t *testing.T) {
t.Run("empty execMsgs", func(t *testing.T) { t.Run("empty execMsgs", func(t *testing.T) {
usd := &mockUnsafeStartDeps{} usd := &mockUnsafeStartDeps{}
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
candidate := types.BlockSeal{} candidate := types.BlockSeal{}
execMsgs := []*types.ExecutingMessage{} execMsgs := []*types.ExecutingMessage{}
// when there are no execMsgs, // when there are no execMsgs,
...@@ -30,7 +30,7 @@ func TestCrossUnsafeHazards(t *testing.T) { ...@@ -30,7 +30,7 @@ func TestCrossUnsafeHazards(t *testing.T) {
return false, nil return false, nil
}, },
} }
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
candidate := types.BlockSeal{} candidate := types.BlockSeal{}
execMsgs := []*types.ExecutingMessage{{}} execMsgs := []*types.ExecutingMessage{{}}
// when there is one execMsg, and CanExecuteAt returns false, // when there is one execMsg, and CanExecuteAt returns false,
...@@ -46,7 +46,7 @@ func TestCrossUnsafeHazards(t *testing.T) { ...@@ -46,7 +46,7 @@ func TestCrossUnsafeHazards(t *testing.T) {
return false, errors.New("some error") return false, errors.New("some error")
}, },
} }
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
candidate := types.BlockSeal{} candidate := types.BlockSeal{}
execMsgs := []*types.ExecutingMessage{{}} execMsgs := []*types.ExecutingMessage{{}}
// when there is one execMsg, and CanExecuteAt returns false, // when there is one execMsg, and CanExecuteAt returns false,
...@@ -58,11 +58,11 @@ func TestCrossUnsafeHazards(t *testing.T) { ...@@ -58,11 +58,11 @@ func TestCrossUnsafeHazards(t *testing.T) {
t.Run("unknown chain", func(t *testing.T) { t.Run("unknown chain", func(t *testing.T) {
usd := &mockUnsafeStartDeps{} usd := &mockUnsafeStartDeps{}
usd.deps = mockDependencySet{ usd.deps = mockDependencySet{
chainIDFromIndexfn: func() (types.ChainID, error) { chainIDFromIndexfn: func() (eth.ChainID, error) {
return types.ChainID{}, types.ErrUnknownChain return eth.ChainID{}, types.ErrUnknownChain
}, },
} }
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
candidate := types.BlockSeal{} candidate := types.BlockSeal{}
execMsgs := []*types.ExecutingMessage{{}} execMsgs := []*types.ExecutingMessage{{}}
// when there is one execMsg, and ChainIDFromIndex returns ErrUnknownChain, // when there is one execMsg, and ChainIDFromIndex returns ErrUnknownChain,
...@@ -74,11 +74,11 @@ func TestCrossUnsafeHazards(t *testing.T) { ...@@ -74,11 +74,11 @@ func TestCrossUnsafeHazards(t *testing.T) {
t.Run("ChainIDFromUInt64 returns error", func(t *testing.T) { t.Run("ChainIDFromUInt64 returns error", func(t *testing.T) {
usd := &mockUnsafeStartDeps{} usd := &mockUnsafeStartDeps{}
usd.deps = mockDependencySet{ usd.deps = mockDependencySet{
chainIDFromIndexfn: func() (types.ChainID, error) { chainIDFromIndexfn: func() (eth.ChainID, error) {
return types.ChainID{}, errors.New("some error") return eth.ChainID{}, errors.New("some error")
}, },
} }
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
candidate := types.BlockSeal{} candidate := types.BlockSeal{}
execMsgs := []*types.ExecutingMessage{{}} execMsgs := []*types.ExecutingMessage{{}}
// when there is one execMsg, and ChainIDFromIndex returns some other error, // when there is one execMsg, and ChainIDFromIndex returns some other error,
...@@ -94,7 +94,7 @@ func TestCrossUnsafeHazards(t *testing.T) { ...@@ -94,7 +94,7 @@ func TestCrossUnsafeHazards(t *testing.T) {
return false, nil return false, nil
}, },
} }
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
candidate := types.BlockSeal{} candidate := types.BlockSeal{}
execMsgs := []*types.ExecutingMessage{{}} execMsgs := []*types.ExecutingMessage{{}}
// when there is one execMsg, and CanInitiateAt returns false, // when there is one execMsg, and CanInitiateAt returns false,
...@@ -110,7 +110,7 @@ func TestCrossUnsafeHazards(t *testing.T) { ...@@ -110,7 +110,7 @@ func TestCrossUnsafeHazards(t *testing.T) {
return false, errors.New("some error") return false, errors.New("some error")
}, },
} }
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
candidate := types.BlockSeal{} candidate := types.BlockSeal{}
execMsgs := []*types.ExecutingMessage{{}} execMsgs := []*types.ExecutingMessage{{}}
// when there is one execMsg, and CanInitiateAt returns an error, // when there is one execMsg, and CanInitiateAt returns an error,
...@@ -122,7 +122,7 @@ func TestCrossUnsafeHazards(t *testing.T) { ...@@ -122,7 +122,7 @@ func TestCrossUnsafeHazards(t *testing.T) {
t.Run("timestamp is greater than candidate", func(t *testing.T) { t.Run("timestamp is greater than candidate", func(t *testing.T) {
usd := &mockUnsafeStartDeps{} usd := &mockUnsafeStartDeps{}
usd.deps = mockDependencySet{} usd.deps = mockDependencySet{}
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
candidate := types.BlockSeal{Timestamp: 2} candidate := types.BlockSeal{Timestamp: 2}
em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 10} em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 10}
execMsgs := []*types.ExecutingMessage{em1} execMsgs := []*types.ExecutingMessage{em1}
...@@ -138,7 +138,7 @@ func TestCrossUnsafeHazards(t *testing.T) { ...@@ -138,7 +138,7 @@ func TestCrossUnsafeHazards(t *testing.T) {
return types.BlockSeal{}, errors.New("some error") return types.BlockSeal{}, errors.New("some error")
} }
usd.deps = mockDependencySet{} usd.deps = mockDependencySet{}
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
candidate := types.BlockSeal{Timestamp: 2} candidate := types.BlockSeal{Timestamp: 2}
em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 2} em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 2}
execMsgs := []*types.ExecutingMessage{em1} execMsgs := []*types.ExecutingMessage{em1}
...@@ -156,7 +156,7 @@ func TestCrossUnsafeHazards(t *testing.T) { ...@@ -156,7 +156,7 @@ func TestCrossUnsafeHazards(t *testing.T) {
return sampleBlockSeal, nil return sampleBlockSeal, nil
} }
usd.deps = mockDependencySet{} usd.deps = mockDependencySet{}
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
candidate := types.BlockSeal{Timestamp: 2} candidate := types.BlockSeal{Timestamp: 2}
em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 2} em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 2}
em2 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 2} em2 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 2}
...@@ -182,7 +182,7 @@ func TestCrossUnsafeHazards(t *testing.T) { ...@@ -182,7 +182,7 @@ func TestCrossUnsafeHazards(t *testing.T) {
return sampleBlockSeal2, nil return sampleBlockSeal2, nil
} }
usd.deps = mockDependencySet{} usd.deps = mockDependencySet{}
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
candidate := types.BlockSeal{Timestamp: 2} candidate := types.BlockSeal{Timestamp: 2}
em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 2} em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 2}
em2 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 2} em2 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 2}
...@@ -200,7 +200,7 @@ func TestCrossUnsafeHazards(t *testing.T) { ...@@ -200,7 +200,7 @@ func TestCrossUnsafeHazards(t *testing.T) {
return types.BlockSeal{}, errors.New("some error") return types.BlockSeal{}, errors.New("some error")
} }
usd.deps = mockDependencySet{} usd.deps = mockDependencySet{}
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
candidate := types.BlockSeal{Timestamp: 2} candidate := types.BlockSeal{Timestamp: 2}
em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 1} em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 1}
execMsgs := []*types.ExecutingMessage{em1} execMsgs := []*types.ExecutingMessage{em1}
...@@ -221,7 +221,7 @@ func TestCrossUnsafeHazards(t *testing.T) { ...@@ -221,7 +221,7 @@ func TestCrossUnsafeHazards(t *testing.T) {
return errors.New("some error") return errors.New("some error")
} }
usd.deps = mockDependencySet{} usd.deps = mockDependencySet{}
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
candidate := types.BlockSeal{Timestamp: 2} candidate := types.BlockSeal{Timestamp: 2}
em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 1} em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 1}
execMsgs := []*types.ExecutingMessage{em1} execMsgs := []*types.ExecutingMessage{em1}
...@@ -242,7 +242,7 @@ func TestCrossUnsafeHazards(t *testing.T) { ...@@ -242,7 +242,7 @@ func TestCrossUnsafeHazards(t *testing.T) {
return nil return nil
} }
usd.deps = mockDependencySet{} usd.deps = mockDependencySet{}
chainID := types.ChainIDFromUInt64(0) chainID := eth.ChainIDFromUInt64(0)
candidate := types.BlockSeal{Timestamp: 2} candidate := types.BlockSeal{Timestamp: 2}
em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 0} em1 := &types.ExecutingMessage{Chain: types.ChainIndex(0), Timestamp: 0}
execMsgs := []*types.ExecutingMessage{em1} execMsgs := []*types.ExecutingMessage{em1}
...@@ -261,14 +261,14 @@ type mockUnsafeStartDeps struct { ...@@ -261,14 +261,14 @@ type mockUnsafeStartDeps struct {
isCrossUnsafeFn func() error isCrossUnsafeFn func() error
} }
func (m *mockUnsafeStartDeps) Check(chain types.ChainID, blockNum uint64, timestamp uint64, logIdx uint32, logHash common.Hash) (includedIn types.BlockSeal, err error) { func (m *mockUnsafeStartDeps) Check(chain eth.ChainID, blockNum uint64, timestamp uint64, logIdx uint32, logHash common.Hash) (includedIn types.BlockSeal, err error) {
if m.checkFn != nil { if m.checkFn != nil {
return m.checkFn() return m.checkFn()
} }
return types.BlockSeal{}, nil return types.BlockSeal{}, nil
} }
func (m *mockUnsafeStartDeps) IsCrossUnsafe(chainID types.ChainID, derived eth.BlockID) error { func (m *mockUnsafeStartDeps) IsCrossUnsafe(chainID eth.ChainID, derived eth.BlockID) error {
if m.isCrossUnsafeFn != nil { if m.isCrossUnsafeFn != nil {
return m.isCrossUnsafeFn() return m.isCrossUnsafeFn()
} }
......
...@@ -13,17 +13,17 @@ import ( ...@@ -13,17 +13,17 @@ import (
) )
type CrossUnsafeDeps interface { type CrossUnsafeDeps interface {
CrossUnsafe(chainID types.ChainID) (types.BlockSeal, error) CrossUnsafe(chainID eth.ChainID) (types.BlockSeal, error)
UnsafeStartDeps UnsafeStartDeps
UnsafeFrontierCheckDeps UnsafeFrontierCheckDeps
OpenBlock(chainID types.ChainID, blockNum uint64) (block eth.BlockRef, logCount uint32, execMsgs map[uint32]*types.ExecutingMessage, err error) OpenBlock(chainID eth.ChainID, blockNum uint64) (block eth.BlockRef, logCount uint32, execMsgs map[uint32]*types.ExecutingMessage, err error)
UpdateCrossUnsafe(chain types.ChainID, crossUnsafe types.BlockSeal) error UpdateCrossUnsafe(chain eth.ChainID, crossUnsafe types.BlockSeal) error
} }
func CrossUnsafeUpdate(logger log.Logger, chainID types.ChainID, d CrossUnsafeDeps) error { func CrossUnsafeUpdate(logger log.Logger, chainID eth.ChainID, d CrossUnsafeDeps) error {
var candidate types.BlockSeal var candidate types.BlockSeal
var execMsgs []*types.ExecutingMessage var execMsgs []*types.ExecutingMessage
...@@ -74,7 +74,7 @@ func CrossUnsafeUpdate(logger log.Logger, chainID types.ChainID, d CrossUnsafeDe ...@@ -74,7 +74,7 @@ func CrossUnsafeUpdate(logger log.Logger, chainID types.ChainID, d CrossUnsafeDe
type CrossUnsafeWorker struct { type CrossUnsafeWorker struct {
logger log.Logger logger log.Logger
chainID types.ChainID chainID eth.ChainID
d CrossUnsafeDeps d CrossUnsafeDeps
} }
...@@ -99,7 +99,7 @@ func (c *CrossUnsafeWorker) OnEvent(ev event.Event) bool { ...@@ -99,7 +99,7 @@ func (c *CrossUnsafeWorker) OnEvent(ev event.Event) bool {
var _ event.Deriver = (*CrossUnsafeWorker)(nil) var _ event.Deriver = (*CrossUnsafeWorker)(nil)
func NewCrossUnsafeWorker(logger log.Logger, chainID types.ChainID, d CrossUnsafeDeps) *CrossUnsafeWorker { func NewCrossUnsafeWorker(logger log.Logger, chainID eth.ChainID, d CrossUnsafeDeps) *CrossUnsafeWorker {
logger = logger.New("chain", chainID) logger = logger.New("chain", chainID)
return &CrossUnsafeWorker{ return &CrossUnsafeWorker{
logger: logger, logger: logger,
......
...@@ -3,12 +3,13 @@ package db ...@@ -3,12 +3,13 @@ package db
import ( import (
"errors" "errors"
"github.com/ethereum-optimism/optimism/op-service/eth"
"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types" "github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types"
) )
// maybeInitSafeDB initializes the chain database if it is not already initialized // maybeInitSafeDB initializes the chain database if it is not already initialized
// it checks if the Local Safe database is empty, and loads it with the Anchor Point if so // it checks if the Local Safe database is empty, and loads it with the Anchor Point if so
func (db *ChainsDB) maybeInitSafeDB(id types.ChainID, anchor types.DerivedBlockRefPair) { func (db *ChainsDB) maybeInitSafeDB(id eth.ChainID, anchor types.DerivedBlockRefPair) {
_, err := db.LocalSafe(id) _, err := db.LocalSafe(id)
if errors.Is(err, types.ErrFuture) { if errors.Is(err, types.ErrFuture) {
db.logger.Debug("initializing chain database", "chain", id) db.logger.Debug("initializing chain database", "chain", id)
...@@ -23,7 +24,7 @@ func (db *ChainsDB) maybeInitSafeDB(id types.ChainID, anchor types.DerivedBlockR ...@@ -23,7 +24,7 @@ func (db *ChainsDB) maybeInitSafeDB(id types.ChainID, anchor types.DerivedBlockR
} }
} }
func (db *ChainsDB) maybeInitEventsDB(id types.ChainID, anchor types.DerivedBlockRefPair) { func (db *ChainsDB) maybeInitEventsDB(id eth.ChainID, anchor types.DerivedBlockRefPair) {
_, _, _, err := db.OpenBlock(id, 0) _, _, _, err := db.OpenBlock(id, 0)
if errors.Is(err, types.ErrFuture) { if errors.Is(err, types.ErrFuture) {
db.logger.Debug("initializing events database", "chain", id) db.logger.Debug("initializing events database", "chain", id)
......
...@@ -76,17 +76,17 @@ var _ LogStorage = (*logs.DB)(nil) ...@@ -76,17 +76,17 @@ var _ LogStorage = (*logs.DB)(nil)
// it implements the LogStorage interface, as well as several DB interfaces needed by the cross package. // it implements the LogStorage interface, as well as several DB interfaces needed by the cross package.
type ChainsDB struct { type ChainsDB struct {
// unsafe info: the sequence of block seals and events // unsafe info: the sequence of block seals and events
logDBs locks.RWMap[types.ChainID, LogStorage] logDBs locks.RWMap[eth.ChainID, LogStorage]
// cross-unsafe: how far we have processed the unsafe data. // cross-unsafe: how far we have processed the unsafe data.
// If present but set to a zeroed value the cross-unsafe will fallback to cross-safe. // If present but set to a zeroed value the cross-unsafe will fallback to cross-safe.
crossUnsafe locks.RWMap[types.ChainID, *locks.RWValue[types.BlockSeal]] crossUnsafe locks.RWMap[eth.ChainID, *locks.RWValue[types.BlockSeal]]
// local-safe: index of what we optimistically know about L2 blocks being derived from L1 // local-safe: index of what we optimistically know about L2 blocks being derived from L1
localDBs locks.RWMap[types.ChainID, LocalDerivedFromStorage] localDBs locks.RWMap[eth.ChainID, LocalDerivedFromStorage]
// cross-safe: index of L2 blocks we know to only have cross-L2 valid dependencies // cross-safe: index of L2 blocks we know to only have cross-L2 valid dependencies
crossDBs locks.RWMap[types.ChainID, CrossDerivedFromStorage] crossDBs locks.RWMap[eth.ChainID, CrossDerivedFromStorage]
// finalized: the L1 finality progress. This can be translated into what may be considered as finalized in L2. // finalized: the L1 finality progress. This can be translated into what may be considered as finalized in L2.
// It is initially zeroed, and the L2 finality query will return // It is initially zeroed, and the L2 finality query will return
...@@ -131,7 +131,7 @@ func (db *ChainsDB) OnEvent(ev event.Event) bool { ...@@ -131,7 +131,7 @@ func (db *ChainsDB) OnEvent(ev event.Event) bool {
return true return true
} }
func (db *ChainsDB) AddLogDB(chainID types.ChainID, logDB LogStorage) { func (db *ChainsDB) AddLogDB(chainID eth.ChainID, logDB LogStorage) {
if db.logDBs.Has(chainID) { if db.logDBs.Has(chainID) {
db.logger.Warn("overwriting existing log DB for chain", "chain", chainID) db.logger.Warn("overwriting existing log DB for chain", "chain", chainID)
} }
...@@ -139,7 +139,7 @@ func (db *ChainsDB) AddLogDB(chainID types.ChainID, logDB LogStorage) { ...@@ -139,7 +139,7 @@ func (db *ChainsDB) AddLogDB(chainID types.ChainID, logDB LogStorage) {
db.logDBs.Set(chainID, logDB) db.logDBs.Set(chainID, logDB)
} }
func (db *ChainsDB) AddLocalDerivedFromDB(chainID types.ChainID, dfDB LocalDerivedFromStorage) { func (db *ChainsDB) AddLocalDerivedFromDB(chainID eth.ChainID, dfDB LocalDerivedFromStorage) {
if db.localDBs.Has(chainID) { if db.localDBs.Has(chainID) {
db.logger.Warn("overwriting existing local derived-from DB for chain", "chain", chainID) db.logger.Warn("overwriting existing local derived-from DB for chain", "chain", chainID)
} }
...@@ -147,7 +147,7 @@ func (db *ChainsDB) AddLocalDerivedFromDB(chainID types.ChainID, dfDB LocalDeriv ...@@ -147,7 +147,7 @@ func (db *ChainsDB) AddLocalDerivedFromDB(chainID types.ChainID, dfDB LocalDeriv
db.localDBs.Set(chainID, dfDB) db.localDBs.Set(chainID, dfDB)
} }
func (db *ChainsDB) AddCrossDerivedFromDB(chainID types.ChainID, dfDB CrossDerivedFromStorage) { func (db *ChainsDB) AddCrossDerivedFromDB(chainID eth.ChainID, dfDB CrossDerivedFromStorage) {
if db.crossDBs.Has(chainID) { if db.crossDBs.Has(chainID) {
db.logger.Warn("overwriting existing cross derived-from DB for chain", "chain", chainID) db.logger.Warn("overwriting existing cross derived-from DB for chain", "chain", chainID)
} }
...@@ -155,7 +155,7 @@ func (db *ChainsDB) AddCrossDerivedFromDB(chainID types.ChainID, dfDB CrossDeriv ...@@ -155,7 +155,7 @@ func (db *ChainsDB) AddCrossDerivedFromDB(chainID types.ChainID, dfDB CrossDeriv
db.crossDBs.Set(chainID, dfDB) db.crossDBs.Set(chainID, dfDB)
} }
func (db *ChainsDB) AddCrossUnsafeTracker(chainID types.ChainID) { func (db *ChainsDB) AddCrossUnsafeTracker(chainID eth.ChainID) {
if db.crossUnsafe.Has(chainID) { if db.crossUnsafe.Has(chainID) {
db.logger.Warn("overwriting existing cross-unsafe tracker for chain", "chain", chainID) db.logger.Warn("overwriting existing cross-unsafe tracker for chain", "chain", chainID)
} }
...@@ -167,7 +167,7 @@ func (db *ChainsDB) AddCrossUnsafeTracker(chainID types.ChainID) { ...@@ -167,7 +167,7 @@ func (db *ChainsDB) AddCrossUnsafeTracker(chainID types.ChainID) {
// to ensure it can resume recording from the first log of the next block. // to ensure it can resume recording from the first log of the next block.
func (db *ChainsDB) ResumeFromLastSealedBlock() error { func (db *ChainsDB) ResumeFromLastSealedBlock() error {
var result error var result error
db.logDBs.Range(func(chain types.ChainID, logStore LogStorage) bool { db.logDBs.Range(func(chain eth.ChainID, logStore LogStorage) bool {
headNum, ok := logStore.LatestSealedBlockNum() headNum, ok := logStore.LatestSealedBlockNum()
if !ok { if !ok {
// db must be empty, nothing to rewind to // db must be empty, nothing to rewind to
...@@ -190,7 +190,7 @@ func (db *ChainsDB) DependencySet() depset.DependencySet { ...@@ -190,7 +190,7 @@ func (db *ChainsDB) DependencySet() depset.DependencySet {
func (db *ChainsDB) Close() error { func (db *ChainsDB) Close() error {
var combined error var combined error
db.logDBs.Range(func(id types.ChainID, logDB LogStorage) bool { db.logDBs.Range(func(id eth.ChainID, logDB LogStorage) bool {
if err := logDB.Close(); err != nil { if err := logDB.Close(); err != nil {
combined = errors.Join(combined, fmt.Errorf("failed to close log db for chain %v: %w", id, err)) combined = errors.Join(combined, fmt.Errorf("failed to close log db for chain %v: %w", id, err))
} }
......
...@@ -5,10 +5,10 @@ import ( ...@@ -5,10 +5,10 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types" "github.com/ethereum-optimism/optimism/op-service/eth"
) )
func prepLocalDerivedFromDBPath(chainID types.ChainID, datadir string) (string, error) { func prepLocalDerivedFromDBPath(chainID eth.ChainID, datadir string) (string, error) {
dir, err := prepChainDir(chainID, datadir) dir, err := prepChainDir(chainID, datadir)
if err != nil { if err != nil {
return "", err return "", err
...@@ -16,7 +16,7 @@ func prepLocalDerivedFromDBPath(chainID types.ChainID, datadir string) (string, ...@@ -16,7 +16,7 @@ func prepLocalDerivedFromDBPath(chainID types.ChainID, datadir string) (string,
return filepath.Join(dir, "local_safe.db"), nil return filepath.Join(dir, "local_safe.db"), nil
} }
func prepCrossDerivedFromDBPath(chainID types.ChainID, datadir string) (string, error) { func prepCrossDerivedFromDBPath(chainID eth.ChainID, datadir string) (string, error) {
dir, err := prepChainDir(chainID, datadir) dir, err := prepChainDir(chainID, datadir)
if err != nil { if err != nil {
return "", err return "", err
...@@ -24,7 +24,7 @@ func prepCrossDerivedFromDBPath(chainID types.ChainID, datadir string) (string, ...@@ -24,7 +24,7 @@ func prepCrossDerivedFromDBPath(chainID types.ChainID, datadir string) (string,
return filepath.Join(dir, "cross_safe.db"), nil return filepath.Join(dir, "cross_safe.db"), nil
} }
func prepLogDBPath(chainID types.ChainID, datadir string) (string, error) { func prepLogDBPath(chainID eth.ChainID, datadir string) (string, error) {
dir, err := prepChainDir(chainID, datadir) dir, err := prepChainDir(chainID, datadir)
if err != nil { if err != nil {
return "", err return "", err
...@@ -32,7 +32,7 @@ func prepLogDBPath(chainID types.ChainID, datadir string) (string, error) { ...@@ -32,7 +32,7 @@ func prepLogDBPath(chainID types.ChainID, datadir string) (string, error) {
return filepath.Join(dir, "log.db"), nil return filepath.Join(dir, "log.db"), nil
} }
func prepChainDir(chainID types.ChainID, datadir string) (string, error) { func prepChainDir(chainID eth.ChainID, datadir string) (string, error) {
dir := filepath.Join(datadir, chainID.String()) dir := filepath.Join(datadir, chainID.String())
if err := os.MkdirAll(dir, 0755); err != nil { if err := os.MkdirAll(dir, 0755); err != nil {
return "", fmt.Errorf("failed to create chain directory %v: %w", dir, err) return "", fmt.Errorf("failed to create chain directory %v: %w", dir, err)
......
...@@ -6,7 +6,7 @@ import ( ...@@ -6,7 +6,7 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types" "github.com/ethereum-optimism/optimism/op-service/eth"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
...@@ -15,7 +15,7 @@ func TestLogDBPath(t *testing.T) { ...@@ -15,7 +15,7 @@ func TestLogDBPath(t *testing.T) {
chainIDStr := "42984928492928428424243444" chainIDStr := "42984928492928428424243444"
chainIDBig, ok := new(big.Int).SetString(chainIDStr, 10) chainIDBig, ok := new(big.Int).SetString(chainIDStr, 10)
require.True(t, ok) require.True(t, ok)
chainID := types.ChainIDFromBig(chainIDBig) chainID := eth.ChainIDFromBig(chainIDBig)
expected := filepath.Join(base, "subdir", chainIDStr, "log.db") expected := filepath.Join(base, "subdir", chainIDStr, "log.db")
path, err := prepLogDBPath(chainID, filepath.Join(base, "subdir")) path, err := prepLogDBPath(chainID, filepath.Join(base, "subdir"))
require.NoError(t, err) require.NoError(t, err)
......
...@@ -3,14 +3,14 @@ package db ...@@ -3,14 +3,14 @@ package db
import ( import (
"fmt" "fmt"
"github.com/ethereum-optimism/optimism/op-service/eth"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/backend/db/fromda" "github.com/ethereum-optimism/optimism/op-supervisor/supervisor/backend/db/fromda"
"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/backend/db/logs" "github.com/ethereum-optimism/optimism/op-supervisor/supervisor/backend/db/logs"
"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types"
) )
func OpenLogDB(logger log.Logger, chainID types.ChainID, dataDir string, m logs.Metrics) (*logs.DB, error) { func OpenLogDB(logger log.Logger, chainID eth.ChainID, dataDir string, m logs.Metrics) (*logs.DB, error) {
path, err := prepLogDBPath(chainID, dataDir) path, err := prepLogDBPath(chainID, dataDir)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to create datadir for chain %s: %w", chainID, err) return nil, fmt.Errorf("failed to create datadir for chain %s: %w", chainID, err)
...@@ -22,7 +22,7 @@ func OpenLogDB(logger log.Logger, chainID types.ChainID, dataDir string, m logs. ...@@ -22,7 +22,7 @@ func OpenLogDB(logger log.Logger, chainID types.ChainID, dataDir string, m logs.
return logDB, nil return logDB, nil
} }
func OpenLocalDerivedFromDB(logger log.Logger, chainID types.ChainID, dataDir string, m fromda.ChainMetrics) (*fromda.DB, error) { func OpenLocalDerivedFromDB(logger log.Logger, chainID eth.ChainID, dataDir string, m fromda.ChainMetrics) (*fromda.DB, error) {
path, err := prepLocalDerivedFromDBPath(chainID, dataDir) path, err := prepLocalDerivedFromDBPath(chainID, dataDir)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to prepare datadir for chain %s: %w", chainID, err) return nil, fmt.Errorf("failed to prepare datadir for chain %s: %w", chainID, err)
...@@ -34,7 +34,7 @@ func OpenLocalDerivedFromDB(logger log.Logger, chainID types.ChainID, dataDir st ...@@ -34,7 +34,7 @@ func OpenLocalDerivedFromDB(logger log.Logger, chainID types.ChainID, dataDir st
return db, nil return db, nil
} }
func OpenCrossDerivedFromDB(logger log.Logger, chainID types.ChainID, dataDir string, m fromda.ChainMetrics) (*fromda.DB, error) { func OpenCrossDerivedFromDB(logger log.Logger, chainID eth.ChainID, dataDir string, m fromda.ChainMetrics) (*fromda.DB, error) {
path, err := prepCrossDerivedFromDBPath(chainID, dataDir) path, err := prepCrossDerivedFromDBPath(chainID, dataDir)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to prepare datadir for chain %s: %w", chainID, err) return nil, fmt.Errorf("failed to prepare datadir for chain %s: %w", chainID, err)
......
...@@ -11,8 +11,8 @@ import ( ...@@ -11,8 +11,8 @@ import (
"time" "time"
"github.com/ethereum-optimism/optimism/op-service/client" "github.com/ethereum-optimism/optimism/op-service/client"
"github.com/ethereum-optimism/optimism/op-service/eth"
"github.com/ethereum-optimism/optimism/op-service/retry" "github.com/ethereum-optimism/optimism/op-service/retry"
"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types"
) )
var ( var (
...@@ -57,7 +57,7 @@ func NewClient(config Config, serverURL string) (*Client, error) { ...@@ -57,7 +57,7 @@ func NewClient(config Config, serverURL string) (*Client, error) {
} }
// SyncAll syncs all known databases for the given chains. // SyncAll syncs all known databases for the given chains.
func (c *Client) SyncAll(ctx context.Context, chains []types.ChainID, resume bool) error { func (c *Client) SyncAll(ctx context.Context, chains []eth.ChainID, resume bool) error {
for _, chain := range chains { for _, chain := range chains {
for fileAlias := range Databases { for fileAlias := range Databases {
if err := c.SyncDatabase(ctx, chain, fileAlias, resume); err != nil { if err := c.SyncDatabase(ctx, chain, fileAlias, resume); err != nil {
...@@ -70,7 +70,7 @@ func (c *Client) SyncAll(ctx context.Context, chains []types.ChainID, resume boo ...@@ -70,7 +70,7 @@ func (c *Client) SyncAll(ctx context.Context, chains []types.ChainID, resume boo
// SyncDatabase downloads the named file from the server. // SyncDatabase downloads the named file from the server.
// If the local file exists, it will attempt to resume the download if resume is true. // If the local file exists, it will attempt to resume the download if resume is true.
func (c *Client) SyncDatabase(ctx context.Context, chainID types.ChainID, database Database, resume bool) error { func (c *Client) SyncDatabase(ctx context.Context, chainID eth.ChainID, database Database, resume bool) error {
// Validate file alias // Validate file alias
filePath, exists := Databases[database] filePath, exists := Databases[database]
if !exists { if !exists {
...@@ -111,7 +111,7 @@ func (c *Client) SyncDatabase(ctx context.Context, chainID types.ChainID, databa ...@@ -111,7 +111,7 @@ func (c *Client) SyncDatabase(ctx context.Context, chainID types.ChainID, databa
} }
// attemptSync makes a single attempt to sync the file // attemptSync makes a single attempt to sync the file
func (c *Client) attemptSync(ctx context.Context, chainID types.ChainID, database Database, absPath string, initialSize int64) error { func (c *Client) attemptSync(ctx context.Context, chainID eth.ChainID, database Database, absPath string, initialSize int64) error {
// First do a HEAD request to get the file size // First do a HEAD request to get the file size
path := c.buildURLPath(chainID, database) path := c.buildURLPath(chainID, database)
resp, err := c.httpClient.Get(ctx, path, nil, http.Header{"X-HTTP-Method-Override": []string{"HEAD"}}) resp, err := c.httpClient.Get(ctx, path, nil, http.Header{"X-HTTP-Method-Override": []string{"HEAD"}})
...@@ -178,7 +178,7 @@ func (c *Client) attemptSync(ctx context.Context, chainID types.ChainID, databas ...@@ -178,7 +178,7 @@ func (c *Client) attemptSync(ctx context.Context, chainID types.ChainID, databas
} }
// buildURLPath creates the URL path for a given database download request // buildURLPath creates the URL path for a given database download request
func (c *Client) buildURLPath(chainID types.ChainID, database Database) string { func (c *Client) buildURLPath(chainID eth.ChainID, database Database) string {
return fmt.Sprintf("dbsync/%s/%s", chainID.String(), database) return fmt.Sprintf("dbsync/%s/%s", chainID.String(), database)
} }
......
...@@ -7,17 +7,17 @@ import ( ...@@ -7,17 +7,17 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types" "github.com/ethereum-optimism/optimism/op-service/eth"
) )
// Server handles sync requests // Server handles sync requests
type Server struct { type Server struct {
config Config config Config
validChains map[types.ChainID]struct{} validChains map[eth.ChainID]struct{}
} }
// NewServer creates a new Server with the given config. // NewServer creates a new Server with the given config.
func NewServer(config Config, chains []types.ChainID) (*Server, error) { func NewServer(config Config, chains []eth.ChainID) (*Server, error) {
// Convert root to absolute path for security // Convert root to absolute path for security
root, err := filepath.Abs(config.DataDir) root, err := filepath.Abs(config.DataDir)
if err != nil { if err != nil {
...@@ -34,7 +34,7 @@ func NewServer(config Config, chains []types.ChainID) (*Server, error) { ...@@ -34,7 +34,7 @@ func NewServer(config Config, chains []types.ChainID) (*Server, error) {
} }
// Build map of valid chains for efficient lookup // Build map of valid chains for efficient lookup
validChains := make(map[types.ChainID]struct{}, len(chains)) validChains := make(map[eth.ChainID]struct{}, len(chains))
for _, chain := range chains { for _, chain := range chains {
validChains[chain] = struct{}{} validChains[chain] = struct{}{}
} }
...@@ -45,9 +45,9 @@ func NewServer(config Config, chains []types.ChainID) (*Server, error) { ...@@ -45,9 +45,9 @@ func NewServer(config Config, chains []types.ChainID) (*Server, error) {
}, nil }, nil
} }
func parsePath(path string) (types.ChainID, string, error) { func parsePath(path string) (eth.ChainID, string, error) {
var ( var (
chainID types.ChainID chainID eth.ChainID
fileAlias string fileAlias string
) )
......
...@@ -9,14 +9,13 @@ import ( ...@@ -9,14 +9,13 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"github.com/ethereum-optimism/optimism/op-service/eth"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types"
) )
func TestSyncBasic(t *testing.T) { func TestSyncBasic(t *testing.T) {
serverRoot, clientRoot := setupTest(t) serverRoot, clientRoot := setupTest(t)
chainID := types.ChainID{1} chainID := eth.ChainID{1}
// Create a test file on the server // Create a test file on the server
serverFile := filepath.Join(serverRoot, chainID.String(), DBLocalSafe.File()) serverFile := filepath.Join(serverRoot, chainID.String(), DBLocalSafe.File())
...@@ -26,7 +25,7 @@ func TestSyncBasic(t *testing.T) { ...@@ -26,7 +25,7 @@ func TestSyncBasic(t *testing.T) {
serverCfg := Config{ serverCfg := Config{
DataDir: serverRoot, DataDir: serverRoot,
} }
server, err := NewServer(serverCfg, []types.ChainID{chainID}) server, err := NewServer(serverCfg, []eth.ChainID{chainID})
require.NoError(t, err) require.NoError(t, err)
ts := httptest.NewServer(server) ts := httptest.NewServer(server)
defer ts.Close() defer ts.Close()
...@@ -46,7 +45,7 @@ func TestSyncBasic(t *testing.T) { ...@@ -46,7 +45,7 @@ func TestSyncBasic(t *testing.T) {
func TestSyncResume(t *testing.T) { func TestSyncResume(t *testing.T) {
serverRoot, clientRoot := setupTest(t) serverRoot, clientRoot := setupTest(t)
chainID := types.ChainID{1} // Use chain ID 1 for testing chainID := eth.ChainID{1} // Use chain ID 1 for testing
// Create a test file on the server and partial file on the client // Create a test file on the server and partial file on the client
serverFile := filepath.Join(serverRoot, chainID.String(), DBLocalSafe.File()) serverFile := filepath.Join(serverRoot, chainID.String(), DBLocalSafe.File())
...@@ -59,7 +58,7 @@ func TestSyncResume(t *testing.T) { ...@@ -59,7 +58,7 @@ func TestSyncResume(t *testing.T) {
serverCfg := Config{ serverCfg := Config{
DataDir: serverRoot, DataDir: serverRoot,
} }
server, err := NewServer(serverCfg, []types.ChainID{chainID}) server, err := NewServer(serverCfg, []eth.ChainID{chainID})
require.NoError(t, err) require.NoError(t, err)
ts := httptest.NewServer(server) ts := httptest.NewServer(server)
defer ts.Close() defer ts.Close()
...@@ -78,7 +77,7 @@ func TestSyncResume(t *testing.T) { ...@@ -78,7 +77,7 @@ func TestSyncResume(t *testing.T) {
func TestSyncRetry(t *testing.T) { func TestSyncRetry(t *testing.T) {
serverRoot, clientRoot := setupTest(t) serverRoot, clientRoot := setupTest(t)
chainID := types.ChainID{1} chainID := eth.ChainID{1}
// Create a test file // Create a test file
serverFile := filepath.Join(serverRoot, chainID.String(), DBLocalSafe.File()) serverFile := filepath.Join(serverRoot, chainID.String(), DBLocalSafe.File())
...@@ -88,7 +87,7 @@ func TestSyncRetry(t *testing.T) { ...@@ -88,7 +87,7 @@ func TestSyncRetry(t *testing.T) {
serverCfg := Config{ serverCfg := Config{
DataDir: serverRoot, DataDir: serverRoot,
} }
server, err := NewServer(serverCfg, []types.ChainID{chainID}) server, err := NewServer(serverCfg, []eth.ChainID{chainID})
require.NoError(t, err) require.NoError(t, err)
failureCount := 0 failureCount := 0
...@@ -118,12 +117,12 @@ func TestSyncRetry(t *testing.T) { ...@@ -118,12 +117,12 @@ func TestSyncRetry(t *testing.T) {
func TestSyncErrors(t *testing.T) { func TestSyncErrors(t *testing.T) {
serverRoot, clientRoot := setupTest(t) serverRoot, clientRoot := setupTest(t)
chainID := types.ChainID{1} chainID := eth.ChainID{1}
serverCfg := Config{ serverCfg := Config{
DataDir: serverRoot, DataDir: serverRoot,
} }
server, err := NewServer(serverCfg, []types.ChainID{chainID}) server, err := NewServer(serverCfg, []eth.ChainID{chainID})
require.NoError(t, err) require.NoError(t, err)
ts := httptest.NewServer(server) ts := httptest.NewServer(server)
......
...@@ -11,7 +11,7 @@ import ( ...@@ -11,7 +11,7 @@ import (
) )
func (db *ChainsDB) AddLog( func (db *ChainsDB) AddLog(
chain types.ChainID, chain eth.ChainID,
logHash common.Hash, logHash common.Hash,
parentBlock eth.BlockID, parentBlock eth.BlockID,
logIdx uint32, logIdx uint32,
...@@ -23,7 +23,7 @@ func (db *ChainsDB) AddLog( ...@@ -23,7 +23,7 @@ func (db *ChainsDB) AddLog(
return logDB.AddLog(logHash, parentBlock, logIdx, execMsg) return logDB.AddLog(logHash, parentBlock, logIdx, execMsg)
} }
func (db *ChainsDB) SealBlock(chain types.ChainID, block eth.BlockRef) error { func (db *ChainsDB) SealBlock(chain eth.ChainID, block eth.BlockRef) error {
logDB, ok := db.logDBs.Get(chain) logDB, ok := db.logDBs.Get(chain)
if !ok { if !ok {
return fmt.Errorf("cannot SealBlock: %w: %v", types.ErrUnknownChain, chain) return fmt.Errorf("cannot SealBlock: %w: %v", types.ErrUnknownChain, chain)
...@@ -40,7 +40,7 @@ func (db *ChainsDB) SealBlock(chain types.ChainID, block eth.BlockRef) error { ...@@ -40,7 +40,7 @@ func (db *ChainsDB) SealBlock(chain types.ChainID, block eth.BlockRef) error {
return nil return nil
} }
func (db *ChainsDB) Rewind(chain types.ChainID, headBlockNum uint64) error { func (db *ChainsDB) Rewind(chain eth.ChainID, headBlockNum uint64) error {
logDB, ok := db.logDBs.Get(chain) logDB, ok := db.logDBs.Get(chain)
if !ok { if !ok {
return fmt.Errorf("cannot Rewind: %w: %s", types.ErrUnknownChain, chain) return fmt.Errorf("cannot Rewind: %w: %s", types.ErrUnknownChain, chain)
...@@ -48,7 +48,7 @@ func (db *ChainsDB) Rewind(chain types.ChainID, headBlockNum uint64) error { ...@@ -48,7 +48,7 @@ func (db *ChainsDB) Rewind(chain types.ChainID, headBlockNum uint64) error {
return logDB.Rewind(headBlockNum) return logDB.Rewind(headBlockNum)
} }
func (db *ChainsDB) UpdateLocalSafe(chain types.ChainID, derivedFrom eth.BlockRef, lastDerived eth.BlockRef) { func (db *ChainsDB) UpdateLocalSafe(chain eth.ChainID, derivedFrom eth.BlockRef, lastDerived eth.BlockRef) {
logger := db.logger.New("chain", chain, "derivedFrom", derivedFrom, "lastDerived", lastDerived) logger := db.logger.New("chain", chain, "derivedFrom", derivedFrom, "lastDerived", lastDerived)
localDB, ok := db.localDBs.Get(chain) localDB, ok := db.localDBs.Get(chain)
if !ok { if !ok {
...@@ -75,7 +75,7 @@ func (db *ChainsDB) UpdateLocalSafe(chain types.ChainID, derivedFrom eth.BlockRe ...@@ -75,7 +75,7 @@ func (db *ChainsDB) UpdateLocalSafe(chain types.ChainID, derivedFrom eth.BlockRe
}) })
} }
func (db *ChainsDB) UpdateCrossUnsafe(chain types.ChainID, crossUnsafe types.BlockSeal) error { func (db *ChainsDB) UpdateCrossUnsafe(chain eth.ChainID, crossUnsafe types.BlockSeal) error {
v, ok := db.crossUnsafe.Get(chain) v, ok := db.crossUnsafe.Get(chain)
if !ok { if !ok {
return fmt.Errorf("cannot UpdateCrossUnsafe: %w: %s", types.ErrUnknownChain, chain) return fmt.Errorf("cannot UpdateCrossUnsafe: %w: %s", types.ErrUnknownChain, chain)
...@@ -89,7 +89,7 @@ func (db *ChainsDB) UpdateCrossUnsafe(chain types.ChainID, crossUnsafe types.Blo ...@@ -89,7 +89,7 @@ func (db *ChainsDB) UpdateCrossUnsafe(chain types.ChainID, crossUnsafe types.Blo
return nil return nil
} }
func (db *ChainsDB) UpdateCrossSafe(chain types.ChainID, l1View eth.BlockRef, lastCrossDerived eth.BlockRef) error { func (db *ChainsDB) UpdateCrossSafe(chain eth.ChainID, l1View eth.BlockRef, lastCrossDerived eth.BlockRef) error {
crossDB, ok := db.crossDBs.Get(chain) crossDB, ok := db.crossDBs.Get(chain)
if !ok { if !ok {
return fmt.Errorf("cannot UpdateCrossSafe: %w: %s", types.ErrUnknownChain, chain) return fmt.Errorf("cannot UpdateCrossSafe: %w: %s", types.ErrUnknownChain, chain)
......
...@@ -3,6 +3,7 @@ package depset ...@@ -3,6 +3,7 @@ package depset
import ( import (
"context" "context"
"github.com/ethereum-optimism/optimism/op-service/eth"
"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types" "github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types"
) )
...@@ -18,22 +19,22 @@ type DependencySet interface { ...@@ -18,22 +19,22 @@ type DependencySet interface {
// I.e. if the chain may be executing messages at the given timestamp. // I.e. if the chain may be executing messages at the given timestamp.
// This may return an error if the query temporarily cannot be answered. // This may return an error if the query temporarily cannot be answered.
// E.g. if the DependencySet is syncing new changes. // E.g. if the DependencySet is syncing new changes.
CanExecuteAt(chainID types.ChainID, execTimestamp uint64) (bool, error) CanExecuteAt(chainID eth.ChainID, execTimestamp uint64) (bool, error)
// CanInitiateAt determines if an initiating message is valid to pull in. // CanInitiateAt determines if an initiating message is valid to pull in.
// I.e. if the message of the given chain is readable or not. // I.e. if the message of the given chain is readable or not.
// This may return an error if the query temporarily cannot be answered. // This may return an error if the query temporarily cannot be answered.
// E.g. if the DependencySet is syncing new changes. // E.g. if the DependencySet is syncing new changes.
CanInitiateAt(chainID types.ChainID, initTimestamp uint64) (bool, error) CanInitiateAt(chainID eth.ChainID, initTimestamp uint64) (bool, error)
// Chains returns the list of chains that are part of the dependency set. // Chains returns the list of chains that are part of the dependency set.
Chains() []types.ChainID Chains() []eth.ChainID
// HasChain determines if a chain is being tracked for interop purposes. // HasChain determines if a chain is being tracked for interop purposes.
// See CanExecuteAt and CanInitiateAt to check if a chain may message at a given time. // See CanExecuteAt and CanInitiateAt to check if a chain may message at a given time.
HasChain(chainID types.ChainID) bool HasChain(chainID eth.ChainID) bool
ChainIndexFromID(id types.ChainID) (types.ChainIndex, error) ChainIndexFromID(id eth.ChainID) (types.ChainIndex, error)
ChainIndexFromID ChainIndexFromID
ChainIDFromIndex ChainIDFromIndex
...@@ -41,10 +42,10 @@ type DependencySet interface { ...@@ -41,10 +42,10 @@ type DependencySet interface {
type ChainIndexFromID interface { type ChainIndexFromID interface {
// ChainIndexFromID converts a ChainID to a ChainIndex. // ChainIndexFromID converts a ChainID to a ChainIndex.
ChainIndexFromID(id types.ChainID) (types.ChainIndex, error) ChainIndexFromID(id eth.ChainID) (types.ChainIndex, error)
} }
type ChainIDFromIndex interface { type ChainIDFromIndex interface {
// ChainIDFromIndex converts a ChainIndex to a ChainID. // ChainIDFromIndex converts a ChainIndex to a ChainID.
ChainIDFromIndex(index types.ChainIndex) (types.ChainID, error) ChainIDFromIndex(index types.ChainIndex) (eth.ChainID, error)
} }
...@@ -7,22 +7,21 @@ import ( ...@@ -7,22 +7,21 @@ import (
"path" "path"
"testing" "testing"
"github.com/ethereum-optimism/optimism/op-service/eth"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types"
) )
func TestDependencySet(t *testing.T) { func TestDependencySet(t *testing.T) {
d := path.Join(t.TempDir(), "tmp_dep_set.json") d := path.Join(t.TempDir(), "tmp_dep_set.json")
depSet, err := NewStaticConfigDependencySet( depSet, err := NewStaticConfigDependencySet(
map[types.ChainID]*StaticConfigDependency{ map[eth.ChainID]*StaticConfigDependency{
types.ChainIDFromUInt64(900): { eth.ChainIDFromUInt64(900): {
ChainIndex: 900, ChainIndex: 900,
ActivationTime: 42, ActivationTime: 42,
HistoryMinTime: 100, HistoryMinTime: 100,
}, },
types.ChainIDFromUInt64(901): { eth.ChainIDFromUInt64(901): {
ChainIndex: 901, ChainIndex: 901,
ActivationTime: 30, ActivationTime: 30,
HistoryMinTime: 20, HistoryMinTime: 20,
...@@ -39,41 +38,41 @@ func TestDependencySet(t *testing.T) { ...@@ -39,41 +38,41 @@ func TestDependencySet(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
chainIDs := result.Chains() chainIDs := result.Chains()
require.Equal(t, []types.ChainID{ require.Equal(t, []eth.ChainID{
types.ChainIDFromUInt64(900), eth.ChainIDFromUInt64(900),
types.ChainIDFromUInt64(901), eth.ChainIDFromUInt64(901),
}, chainIDs) }, chainIDs)
v, err := result.CanExecuteAt(types.ChainIDFromUInt64(900), 42) v, err := result.CanExecuteAt(eth.ChainIDFromUInt64(900), 42)
require.NoError(t, err) require.NoError(t, err)
require.True(t, v) require.True(t, v)
v, err = result.CanExecuteAt(types.ChainIDFromUInt64(900), 41) v, err = result.CanExecuteAt(eth.ChainIDFromUInt64(900), 41)
require.NoError(t, err) require.NoError(t, err)
require.False(t, v) require.False(t, v)
v, err = result.CanInitiateAt(types.ChainIDFromUInt64(900), 100) v, err = result.CanInitiateAt(eth.ChainIDFromUInt64(900), 100)
require.NoError(t, err) require.NoError(t, err)
require.True(t, v) require.True(t, v)
v, err = result.CanInitiateAt(types.ChainIDFromUInt64(900), 99) v, err = result.CanInitiateAt(eth.ChainIDFromUInt64(900), 99)
require.NoError(t, err) require.NoError(t, err)
require.False(t, v) require.False(t, v)
v, err = result.CanExecuteAt(types.ChainIDFromUInt64(901), 30) v, err = result.CanExecuteAt(eth.ChainIDFromUInt64(901), 30)
require.NoError(t, err) require.NoError(t, err)
require.True(t, v) require.True(t, v)
v, err = result.CanExecuteAt(types.ChainIDFromUInt64(901), 29) v, err = result.CanExecuteAt(eth.ChainIDFromUInt64(901), 29)
require.NoError(t, err) require.NoError(t, err)
require.False(t, v) require.False(t, v)
v, err = result.CanInitiateAt(types.ChainIDFromUInt64(901), 20) v, err = result.CanInitiateAt(eth.ChainIDFromUInt64(901), 20)
require.NoError(t, err) require.NoError(t, err)
require.True(t, v) require.True(t, v)
v, err = result.CanInitiateAt(types.ChainIDFromUInt64(901), 19) v, err = result.CanInitiateAt(eth.ChainIDFromUInt64(901), 19)
require.NoError(t, err) require.NoError(t, err)
require.False(t, v) require.False(t, v)
v, err = result.CanExecuteAt(types.ChainIDFromUInt64(902), 100000) v, err = result.CanExecuteAt(eth.ChainIDFromUInt64(902), 100000)
require.NoError(t, err) require.NoError(t, err)
require.False(t, v, "902 not a dependency") require.False(t, v, "902 not a dependency")
v, err = result.CanInitiateAt(types.ChainIDFromUInt64(902), 100000) v, err = result.CanInitiateAt(eth.ChainIDFromUInt64(902), 100000)
require.NoError(t, err) require.NoError(t, err)
require.False(t, v, "902 not a dependency") require.False(t, v, "902 not a dependency")
} }
...@@ -7,6 +7,7 @@ import ( ...@@ -7,6 +7,7 @@ import (
"slices" "slices"
"sort" "sort"
"github.com/ethereum-optimism/optimism/op-service/eth"
"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types" "github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types"
) )
...@@ -28,14 +29,14 @@ type StaticConfigDependency struct { ...@@ -28,14 +29,14 @@ type StaticConfigDependency struct {
// It can be used as a DependencySetSource itself, by simply returning the itself when loading the set. // It can be used as a DependencySetSource itself, by simply returning the itself when loading the set.
type StaticConfigDependencySet struct { type StaticConfigDependencySet struct {
// dependency info per chain // dependency info per chain
dependencies map[types.ChainID]*StaticConfigDependency dependencies map[eth.ChainID]*StaticConfigDependency
// cached mapping of chain index to chain ID // cached mapping of chain index to chain ID
indexToID map[types.ChainIndex]types.ChainID indexToID map[types.ChainIndex]eth.ChainID
// cached list of chain IDs, sorted by ID value // cached list of chain IDs, sorted by ID value
chainIDs []types.ChainID chainIDs []eth.ChainID
} }
func NewStaticConfigDependencySet(dependencies map[types.ChainID]*StaticConfigDependency) (*StaticConfigDependencySet, error) { func NewStaticConfigDependencySet(dependencies map[eth.ChainID]*StaticConfigDependency) (*StaticConfigDependencySet, error) {
out := &StaticConfigDependencySet{dependencies: dependencies} out := &StaticConfigDependencySet{dependencies: dependencies}
if err := out.hydrate(); err != nil { if err := out.hydrate(); err != nil {
return nil, err return nil, err
...@@ -47,7 +48,7 @@ func NewStaticConfigDependencySet(dependencies map[types.ChainID]*StaticConfigDe ...@@ -47,7 +48,7 @@ func NewStaticConfigDependencySet(dependencies map[types.ChainID]*StaticConfigDe
// to encode/decode just the attributes that matter, // to encode/decode just the attributes that matter,
// while wrapping the decoding functionality with additional hydration step. // while wrapping the decoding functionality with additional hydration step.
type jsonStaticConfigDependencySet struct { type jsonStaticConfigDependencySet struct {
Dependencies map[types.ChainID]*StaticConfigDependency `json:"dependencies"` Dependencies map[eth.ChainID]*StaticConfigDependency `json:"dependencies"`
} }
func (ds *StaticConfigDependencySet) MarshalJSON() ([]byte, error) { func (ds *StaticConfigDependencySet) MarshalJSON() ([]byte, error) {
...@@ -68,8 +69,8 @@ func (ds *StaticConfigDependencySet) UnmarshalJSON(data []byte) error { ...@@ -68,8 +69,8 @@ func (ds *StaticConfigDependencySet) UnmarshalJSON(data []byte) error {
// hydrate sets all the cached values, based on the dependencies attribute // hydrate sets all the cached values, based on the dependencies attribute
func (ds *StaticConfigDependencySet) hydrate() error { func (ds *StaticConfigDependencySet) hydrate() error {
ds.indexToID = make(map[types.ChainIndex]types.ChainID) ds.indexToID = make(map[types.ChainIndex]eth.ChainID)
ds.chainIDs = make([]types.ChainID, 0, len(ds.dependencies)) ds.chainIDs = make([]eth.ChainID, 0, len(ds.dependencies))
for id, dep := range ds.dependencies { for id, dep := range ds.dependencies {
if existing, ok := ds.indexToID[dep.ChainIndex]; ok { if existing, ok := ds.indexToID[dep.ChainIndex]; ok {
return fmt.Errorf("chain %s cannot have the same index (%d) as chain %s", id, dep.ChainIndex, existing) return fmt.Errorf("chain %s cannot have the same index (%d) as chain %s", id, dep.ChainIndex, existing)
...@@ -91,7 +92,7 @@ func (ds *StaticConfigDependencySet) LoadDependencySet(ctx context.Context) (Dep ...@@ -91,7 +92,7 @@ func (ds *StaticConfigDependencySet) LoadDependencySet(ctx context.Context) (Dep
return ds, nil return ds, nil
} }
func (ds *StaticConfigDependencySet) CanExecuteAt(chainID types.ChainID, execTimestamp uint64) (bool, error) { func (ds *StaticConfigDependencySet) CanExecuteAt(chainID eth.ChainID, execTimestamp uint64) (bool, error) {
dep, ok := ds.dependencies[chainID] dep, ok := ds.dependencies[chainID]
if !ok { if !ok {
return false, nil return false, nil
...@@ -99,7 +100,7 @@ func (ds *StaticConfigDependencySet) CanExecuteAt(chainID types.ChainID, execTim ...@@ -99,7 +100,7 @@ func (ds *StaticConfigDependencySet) CanExecuteAt(chainID types.ChainID, execTim
return execTimestamp >= dep.ActivationTime, nil return execTimestamp >= dep.ActivationTime, nil
} }
func (ds *StaticConfigDependencySet) CanInitiateAt(chainID types.ChainID, initTimestamp uint64) (bool, error) { func (ds *StaticConfigDependencySet) CanInitiateAt(chainID eth.ChainID, initTimestamp uint64) (bool, error) {
dep, ok := ds.dependencies[chainID] dep, ok := ds.dependencies[chainID]
if !ok { if !ok {
return false, nil return false, nil
...@@ -107,16 +108,16 @@ func (ds *StaticConfigDependencySet) CanInitiateAt(chainID types.ChainID, initTi ...@@ -107,16 +108,16 @@ func (ds *StaticConfigDependencySet) CanInitiateAt(chainID types.ChainID, initTi
return initTimestamp >= dep.HistoryMinTime, nil return initTimestamp >= dep.HistoryMinTime, nil
} }
func (ds *StaticConfigDependencySet) Chains() []types.ChainID { func (ds *StaticConfigDependencySet) Chains() []eth.ChainID {
return slices.Clone(ds.chainIDs) return slices.Clone(ds.chainIDs)
} }
func (ds *StaticConfigDependencySet) HasChain(chainID types.ChainID) bool { func (ds *StaticConfigDependencySet) HasChain(chainID eth.ChainID) bool {
_, ok := ds.dependencies[chainID] _, ok := ds.dependencies[chainID]
return ok return ok
} }
func (ds *StaticConfigDependencySet) ChainIndexFromID(id types.ChainID) (types.ChainIndex, error) { func (ds *StaticConfigDependencySet) ChainIndexFromID(id eth.ChainID) (types.ChainIndex, error) {
dep, ok := ds.dependencies[id] dep, ok := ds.dependencies[id]
if !ok { if !ok {
return 0, fmt.Errorf("failed to translate chain ID %s to chain index: %w", id, types.ErrUnknownChain) return 0, fmt.Errorf("failed to translate chain ID %s to chain index: %w", id, types.ErrUnknownChain)
...@@ -124,10 +125,10 @@ func (ds *StaticConfigDependencySet) ChainIndexFromID(id types.ChainID) (types.C ...@@ -124,10 +125,10 @@ func (ds *StaticConfigDependencySet) ChainIndexFromID(id types.ChainID) (types.C
return dep.ChainIndex, nil return dep.ChainIndex, nil
} }
func (ds *StaticConfigDependencySet) ChainIDFromIndex(index types.ChainIndex) (types.ChainID, error) { func (ds *StaticConfigDependencySet) ChainIDFromIndex(index types.ChainIndex) (eth.ChainID, error) {
id, ok := ds.indexToID[index] id, ok := ds.indexToID[index]
if !ok { if !ok {
return types.ChainID{}, fmt.Errorf("failed to translate chain index %s to chain ID: %w", index, types.ErrUnknownChain) return eth.ChainID{}, fmt.Errorf("failed to translate chain index %s to chain ID: %w", index, types.ErrUnknownChain)
} }
return id, nil return id, nil
} }
...@@ -51,15 +51,15 @@ func (m *MockBackend) CheckMessages(messages []types.Message, minSafety types.Sa ...@@ -51,15 +51,15 @@ func (m *MockBackend) CheckMessages(messages []types.Message, minSafety types.Sa
return nil return nil
} }
func (m *MockBackend) LocalUnsafe(ctx context.Context, chainID types.ChainID) (eth.BlockID, error) { func (m *MockBackend) LocalUnsafe(ctx context.Context, chainID eth.ChainID) (eth.BlockID, error) {
return eth.BlockID{}, nil return eth.BlockID{}, nil
} }
func (m *MockBackend) CrossSafe(ctx context.Context, chainID types.ChainID) (types.DerivedIDPair, error) { func (m *MockBackend) CrossSafe(ctx context.Context, chainID eth.ChainID) (types.DerivedIDPair, error) {
return types.DerivedIDPair{}, nil return types.DerivedIDPair{}, nil
} }
func (m *MockBackend) Finalized(ctx context.Context, chainID types.ChainID) (eth.BlockID, error) { func (m *MockBackend) Finalized(ctx context.Context, chainID eth.ChainID) (eth.BlockID, error) {
return eth.BlockID{}, nil return eth.BlockID{}, nil
} }
...@@ -67,12 +67,12 @@ func (m *MockBackend) FinalizedL1() eth.BlockRef { ...@@ -67,12 +67,12 @@ func (m *MockBackend) FinalizedL1() eth.BlockRef {
return eth.BlockRef{} return eth.BlockRef{}
} }
func (m *MockBackend) CrossDerivedFrom(ctx context.Context, chainID types.ChainID, derived eth.BlockID) (derivedFrom eth.BlockRef, err error) { func (m *MockBackend) CrossDerivedFrom(ctx context.Context, chainID eth.ChainID, derived eth.BlockID) (derivedFrom eth.BlockRef, err error) {
return eth.BlockRef{}, nil return eth.BlockRef{}, nil
} }
func (m *MockBackend) SuperRootAtTimestamp(ctx context.Context, timestamp hexutil.Uint64) (types.SuperRootResponse, error) { func (m *MockBackend) SuperRootAtTimestamp(ctx context.Context, timestamp hexutil.Uint64) (eth.SuperRootResponse, error) {
return types.SuperRootResponse{}, nil return eth.SuperRootResponse{}, nil
} }
func (m *MockBackend) Close() error { func (m *MockBackend) Close() error {
......
...@@ -29,8 +29,8 @@ type LogProcessor interface { ...@@ -29,8 +29,8 @@ type LogProcessor interface {
} }
type DatabaseRewinder interface { type DatabaseRewinder interface {
Rewind(chain types.ChainID, headBlockNum uint64) error Rewind(chain eth.ChainID, headBlockNum uint64) error
LatestBlockNum(chain types.ChainID) (num uint64, ok bool) LatestBlockNum(chain eth.ChainID) (num uint64, ok bool)
} }
type BlockProcessorFn func(ctx context.Context, block eth.BlockRef) error type BlockProcessorFn func(ctx context.Context, block eth.BlockRef) error
...@@ -47,7 +47,7 @@ type ChainProcessor struct { ...@@ -47,7 +47,7 @@ type ChainProcessor struct {
client Source client Source
clientLock sync.Mutex clientLock sync.Mutex
chain types.ChainID chain eth.ChainID
systemContext context.Context systemContext context.Context
...@@ -62,7 +62,7 @@ type ChainProcessor struct { ...@@ -62,7 +62,7 @@ type ChainProcessor struct {
var _ event.AttachEmitter = (*ChainProcessor)(nil) var _ event.AttachEmitter = (*ChainProcessor)(nil)
var _ event.Deriver = (*ChainProcessor)(nil) var _ event.Deriver = (*ChainProcessor)(nil)
func NewChainProcessor(systemContext context.Context, log log.Logger, chain types.ChainID, processor LogProcessor, rewinder DatabaseRewinder) *ChainProcessor { func NewChainProcessor(systemContext context.Context, log log.Logger, chain eth.ChainID, processor LogProcessor, rewinder DatabaseRewinder) *ChainProcessor {
out := &ChainProcessor{ out := &ChainProcessor{
systemContext: systemContext, systemContext: systemContext,
log: log.New("chain", chain), log: log.New("chain", chain),
......
...@@ -3,6 +3,7 @@ package processors ...@@ -3,6 +3,7 @@ package processors
import ( import (
"fmt" "fmt"
"github.com/ethereum-optimism/optimism/op-service/eth"
ethTypes "github.com/ethereum/go-ethereum/core/types" ethTypes "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/types/interoptypes" "github.com/ethereum/go-ethereum/core/types/interoptypes"
"github.com/ethereum/go-ethereum/params" "github.com/ethereum/go-ethereum/params"
...@@ -28,7 +29,7 @@ func DecodeExecutingMessageLog(l *ethTypes.Log, depSet depset.ChainIndexFromID) ...@@ -28,7 +29,7 @@ func DecodeExecutingMessageLog(l *ethTypes.Log, depSet depset.ChainIndexFromID)
return nil, fmt.Errorf("invalid executing message: %w", err) return nil, fmt.Errorf("invalid executing message: %w", err)
} }
logHash := types.PayloadHashToLogHash(msg.PayloadHash, msg.Identifier.Origin) logHash := types.PayloadHashToLogHash(msg.PayloadHash, msg.Identifier.Origin)
index, err := depSet.ChainIndexFromID(types.ChainID(msg.Identifier.ChainID)) index, err := depSet.ChainIndexFromID(eth.ChainID(msg.Identifier.ChainID))
if err != nil { if err != nil {
return nil, err return nil, err
} }
......
...@@ -4,6 +4,7 @@ import ( ...@@ -4,6 +4,7 @@ import (
"encoding/json" "encoding/json"
"testing" "testing"
"github.com/ethereum-optimism/optimism/op-service/eth"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
...@@ -14,10 +15,10 @@ import ( ...@@ -14,10 +15,10 @@ import (
) )
type testDepSet struct { type testDepSet struct {
mapping map[types.ChainID]types.ChainIndex mapping map[eth.ChainID]types.ChainIndex
} }
func (t *testDepSet) ChainIndexFromID(id types.ChainID) (types.ChainIndex, error) { func (t *testDepSet) ChainIndexFromID(id eth.ChainID) (types.ChainIndex, error) {
v, ok := t.mapping[id] v, ok := t.mapping[id]
if !ok { if !ok {
return 0, types.ErrUnknownChain return 0, types.ErrUnknownChain
...@@ -48,8 +49,8 @@ func TestDecodeExecutingMessageLog(t *testing.T) { ...@@ -48,8 +49,8 @@ func TestDecodeExecutingMessageLog(t *testing.T) {
require.NoError(t, json.Unmarshal([]byte(data), &logEvent)) require.NoError(t, json.Unmarshal([]byte(data), &logEvent))
msg, err := DecodeExecutingMessageLog(&logEvent, &testDepSet{ msg, err := DecodeExecutingMessageLog(&logEvent, &testDepSet{
mapping: map[types.ChainID]types.ChainIndex{ mapping: map[eth.ChainID]types.ChainIndex{
types.ChainIDFromUInt64(900200): types.ChainIndex(123), eth.ChainIDFromUInt64(900200): types.ChainIndex(123),
}, },
}) })
require.NoError(t, err) require.NoError(t, err)
......
...@@ -14,18 +14,18 @@ import ( ...@@ -14,18 +14,18 @@ import (
) )
type LogStorage interface { type LogStorage interface {
SealBlock(chain types.ChainID, block eth.BlockRef) error SealBlock(chain eth.ChainID, block eth.BlockRef) error
AddLog(chain types.ChainID, logHash common.Hash, parentBlock eth.BlockID, logIdx uint32, execMsg *types.ExecutingMessage) error AddLog(chain eth.ChainID, logHash common.Hash, parentBlock eth.BlockID, logIdx uint32, execMsg *types.ExecutingMessage) error
} }
type logProcessor struct { type logProcessor struct {
chain types.ChainID chain eth.ChainID
logStore LogStorage logStore LogStorage
eventDecoder EventDecoderFn eventDecoder EventDecoderFn
depSet depset.ChainIndexFromID depSet depset.ChainIndexFromID
} }
func NewLogProcessor(chain types.ChainID, logStore LogStorage, depSet depset.ChainIndexFromID) LogProcessor { func NewLogProcessor(chain eth.ChainID, logStore LogStorage, depSet depset.ChainIndexFromID) LogProcessor {
return &logProcessor{ return &logProcessor{
chain: chain, chain: chain,
logStore: logStore, logStore: logStore,
......
...@@ -16,7 +16,7 @@ import ( ...@@ -16,7 +16,7 @@ import (
"github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types" "github.com/ethereum-optimism/optimism/op-supervisor/supervisor/types"
) )
var logProcessorChainID = types.ChainIDFromUInt64(4) var logProcessorChainID = eth.ChainIDFromUInt64(4)
func TestLogProcessor(t *testing.T) { func TestLogProcessor(t *testing.T) {
ctx := context.Background() ctx := context.Background()
...@@ -27,8 +27,8 @@ func TestLogProcessor(t *testing.T) { ...@@ -27,8 +27,8 @@ func TestLogProcessor(t *testing.T) {
Time: 1111, Time: 1111,
} }
depSet := &testDepSet{ depSet := &testDepSet{
mapping: map[types.ChainID]types.ChainIndex{ mapping: map[eth.ChainID]types.ChainIndex{
types.ChainIDFromUInt64(100): 4, eth.ChainIDFromUInt64(100): 4,
}, },
} }
...@@ -124,7 +124,7 @@ func TestLogProcessor(t *testing.T) { ...@@ -124,7 +124,7 @@ func TestLogProcessor(t *testing.T) {
Hash: common.Hash{0xaa}, Hash: common.Hash{0xaa},
} }
store := &stubLogStorage{} store := &stubLogStorage{}
processor := NewLogProcessor(types.ChainID{4}, store, depSet).(*logProcessor) processor := NewLogProcessor(eth.ChainID{4}, store, depSet).(*logProcessor)
processor.eventDecoder = func(l *ethTypes.Log, translator depset.ChainIndexFromID) (*types.ExecutingMessage, error) { processor.eventDecoder = func(l *ethTypes.Log, translator depset.ChainIndexFromID) (*types.ExecutingMessage, error) {
require.Equal(t, rcpts[0].Logs[0], l) require.Equal(t, rcpts[0].Logs[0], l)
return execMsg, nil return execMsg, nil
...@@ -214,7 +214,7 @@ type stubLogStorage struct { ...@@ -214,7 +214,7 @@ type stubLogStorage struct {
seals []storedSeal seals []storedSeal
} }
func (s *stubLogStorage) SealBlock(chainID types.ChainID, block eth.BlockRef) error { func (s *stubLogStorage) SealBlock(chainID eth.ChainID, block eth.BlockRef) error {
if logProcessorChainID != chainID { if logProcessorChainID != chainID {
return fmt.Errorf("chain id mismatch, expected %v but got %v", logProcessorChainID, chainID) return fmt.Errorf("chain id mismatch, expected %v but got %v", logProcessorChainID, chainID)
} }
...@@ -226,7 +226,7 @@ func (s *stubLogStorage) SealBlock(chainID types.ChainID, block eth.BlockRef) er ...@@ -226,7 +226,7 @@ func (s *stubLogStorage) SealBlock(chainID types.ChainID, block eth.BlockRef) er
return nil return nil
} }
func (s *stubLogStorage) AddLog(chainID types.ChainID, logHash common.Hash, parentBlock eth.BlockID, logIdx uint32, execMsg *types.ExecutingMessage) error { func (s *stubLogStorage) AddLog(chainID eth.ChainID, logHash common.Hash, parentBlock eth.BlockID, logIdx uint32, execMsg *types.ExecutingMessage) error {
if logProcessorChainID != chainID { if logProcessorChainID != chainID {
return fmt.Errorf("chain id mismatch, expected %v but got %v", logProcessorChainID, chainID) return fmt.Errorf("chain id mismatch, expected %v but got %v", logProcessorChainID, chainID)
} }
......
...@@ -6,7 +6,7 @@ import ( ...@@ -6,7 +6,7 @@ import (
) )
type ChainProcessEvent struct { type ChainProcessEvent struct {
ChainID types.ChainID ChainID eth.ChainID
Target uint64 Target uint64
} }
...@@ -15,7 +15,7 @@ func (ev ChainProcessEvent) String() string { ...@@ -15,7 +15,7 @@ func (ev ChainProcessEvent) String() string {
} }
type UpdateCrossUnsafeRequestEvent struct { type UpdateCrossUnsafeRequestEvent struct {
ChainID types.ChainID ChainID eth.ChainID
} }
func (ev UpdateCrossUnsafeRequestEvent) String() string { func (ev UpdateCrossUnsafeRequestEvent) String() string {
...@@ -23,7 +23,7 @@ func (ev UpdateCrossUnsafeRequestEvent) String() string { ...@@ -23,7 +23,7 @@ func (ev UpdateCrossUnsafeRequestEvent) String() string {
} }
type UpdateCrossSafeRequestEvent struct { type UpdateCrossSafeRequestEvent struct {
ChainID types.ChainID ChainID eth.ChainID
} }
func (ev UpdateCrossSafeRequestEvent) String() string { func (ev UpdateCrossSafeRequestEvent) String() string {
...@@ -31,7 +31,7 @@ func (ev UpdateCrossSafeRequestEvent) String() string { ...@@ -31,7 +31,7 @@ func (ev UpdateCrossSafeRequestEvent) String() string {
} }
type LocalUnsafeUpdateEvent struct { type LocalUnsafeUpdateEvent struct {
ChainID types.ChainID ChainID eth.ChainID
NewLocalUnsafe eth.BlockRef NewLocalUnsafe eth.BlockRef
} }
...@@ -40,7 +40,7 @@ func (ev LocalUnsafeUpdateEvent) String() string { ...@@ -40,7 +40,7 @@ func (ev LocalUnsafeUpdateEvent) String() string {
} }
type LocalSafeUpdateEvent struct { type LocalSafeUpdateEvent struct {
ChainID types.ChainID ChainID eth.ChainID
NewLocalSafe types.DerivedBlockSealPair NewLocalSafe types.DerivedBlockSealPair
} }
...@@ -49,7 +49,7 @@ func (ev LocalSafeUpdateEvent) String() string { ...@@ -49,7 +49,7 @@ func (ev LocalSafeUpdateEvent) String() string {
} }
type CrossUnsafeUpdateEvent struct { type CrossUnsafeUpdateEvent struct {
ChainID types.ChainID ChainID eth.ChainID
NewCrossUnsafe types.BlockSeal NewCrossUnsafe types.BlockSeal
} }
...@@ -58,7 +58,7 @@ func (ev CrossUnsafeUpdateEvent) String() string { ...@@ -58,7 +58,7 @@ func (ev CrossUnsafeUpdateEvent) String() string {
} }
type CrossSafeUpdateEvent struct { type CrossSafeUpdateEvent struct {
ChainID types.ChainID ChainID eth.ChainID
NewCrossSafe types.DerivedBlockSealPair NewCrossSafe types.DerivedBlockSealPair
} }
...@@ -83,7 +83,7 @@ func (ev FinalizedL1UpdateEvent) String() string { ...@@ -83,7 +83,7 @@ func (ev FinalizedL1UpdateEvent) String() string {
} }
type FinalizedL2UpdateEvent struct { type FinalizedL2UpdateEvent struct {
ChainID types.ChainID ChainID eth.ChainID
FinalizedL2 types.BlockSeal FinalizedL2 types.BlockSeal
} }
...@@ -92,7 +92,7 @@ func (ev FinalizedL2UpdateEvent) String() string { ...@@ -92,7 +92,7 @@ func (ev FinalizedL2UpdateEvent) String() string {
} }
type LocalSafeOutOfSyncEvent struct { type LocalSafeOutOfSyncEvent struct {
ChainID types.ChainID ChainID eth.ChainID
L1Ref eth.BlockRef L1Ref eth.BlockRef
Err error Err error
} }
...@@ -102,7 +102,7 @@ func (ev LocalSafeOutOfSyncEvent) String() string { ...@@ -102,7 +102,7 @@ func (ev LocalSafeOutOfSyncEvent) String() string {
} }
type LocalUnsafeReceivedEvent struct { type LocalUnsafeReceivedEvent struct {
ChainID types.ChainID ChainID eth.ChainID
NewLocalUnsafe eth.BlockRef NewLocalUnsafe eth.BlockRef
} }
...@@ -111,7 +111,7 @@ func (ev LocalUnsafeReceivedEvent) String() string { ...@@ -111,7 +111,7 @@ func (ev LocalUnsafeReceivedEvent) String() string {
} }
type LocalDerivedEvent struct { type LocalDerivedEvent struct {
ChainID types.ChainID ChainID eth.ChainID
Derived types.DerivedBlockRefPair Derived types.DerivedBlockRefPair
} }
...@@ -120,7 +120,7 @@ func (ev LocalDerivedEvent) String() string { ...@@ -120,7 +120,7 @@ func (ev LocalDerivedEvent) String() string {
} }
type AnchorEvent struct { type AnchorEvent struct {
ChainID types.ChainID ChainID eth.ChainID
Anchor types.DerivedBlockRefPair Anchor types.DerivedBlockRefPair
} }
......
...@@ -5,6 +5,7 @@ import ( ...@@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"sync/atomic" "sync/atomic"
"github.com/ethereum-optimism/optimism/op-service/eth"
"github.com/ethereum/go-ethereum/log" "github.com/ethereum/go-ethereum/log"
"github.com/ethereum-optimism/optimism/op-node/rollup/event" "github.com/ethereum-optimism/optimism/op-node/rollup/event"
...@@ -21,7 +22,7 @@ type SyncNodesController struct { ...@@ -21,7 +22,7 @@ type SyncNodesController struct {
logger log.Logger logger log.Logger
id atomic.Uint64 id atomic.Uint64
controllers locks.RWMap[types.ChainID, *locks.RWMap[*ManagedNode, struct{}]] controllers locks.RWMap[eth.ChainID, *locks.RWMap[*ManagedNode, struct{}]]
eventSys event.System eventSys event.System
...@@ -53,7 +54,7 @@ func (snc *SyncNodesController) OnEvent(ev event.Event) bool { ...@@ -53,7 +54,7 @@ func (snc *SyncNodesController) OnEvent(ev event.Event) bool {
} }
func (snc *SyncNodesController) Close() error { func (snc *SyncNodesController) Close() error {
snc.controllers.Range(func(chainID types.ChainID, controllers *locks.RWMap[*ManagedNode, struct{}]) bool { snc.controllers.Range(func(chainID eth.ChainID, controllers *locks.RWMap[*ManagedNode, struct{}]) bool {
controllers.Range(func(node *ManagedNode, _ struct{}) bool { controllers.Range(func(node *ManagedNode, _ struct{}) bool {
node.Close() node.Close()
return true return true
...@@ -65,7 +66,7 @@ func (snc *SyncNodesController) Close() error { ...@@ -65,7 +66,7 @@ func (snc *SyncNodesController) Close() error {
// AttachNodeController attaches a node to be managed by the supervisor. // AttachNodeController attaches a node to be managed by the supervisor.
// If noSubscribe, the node is not actively polled/subscribed to, and requires manual ManagedNode.PullEvents calls. // If noSubscribe, the node is not actively polled/subscribed to, and requires manual ManagedNode.PullEvents calls.
func (snc *SyncNodesController) AttachNodeController(chainID types.ChainID, ctrl SyncControl, noSubscribe bool) (Node, error) { func (snc *SyncNodesController) AttachNodeController(chainID eth.ChainID, ctrl SyncControl, noSubscribe bool) (Node, error) {
if !snc.depSet.HasChain(chainID) { if !snc.depSet.HasChain(chainID) {
return nil, fmt.Errorf("chain %v not in dependency set: %w", chainID, types.ErrUnknownChain) return nil, fmt.Errorf("chain %v not in dependency set: %w", chainID, types.ErrUnknownChain)
} }
......
...@@ -87,19 +87,19 @@ var _ SyncControl = (*mockSyncControl)(nil) ...@@ -87,19 +87,19 @@ var _ SyncControl = (*mockSyncControl)(nil)
type mockBackend struct{} type mockBackend struct{}
func (m *mockBackend) LocalSafe(ctx context.Context, chainID types.ChainID) (pair types.DerivedIDPair, err error) { func (m *mockBackend) LocalSafe(ctx context.Context, chainID eth.ChainID) (pair types.DerivedIDPair, err error) {
return types.DerivedIDPair{}, nil return types.DerivedIDPair{}, nil
} }
func (m *mockBackend) LocalUnsafe(ctx context.Context, chainID types.ChainID) (eth.BlockID, error) { func (m *mockBackend) LocalUnsafe(ctx context.Context, chainID eth.ChainID) (eth.BlockID, error) {
return eth.BlockID{}, nil return eth.BlockID{}, nil
} }
func (m *mockBackend) SafeDerivedAt(ctx context.Context, chainID types.ChainID, derivedFrom eth.BlockID) (derived eth.BlockID, err error) { func (m *mockBackend) SafeDerivedAt(ctx context.Context, chainID eth.ChainID, derivedFrom eth.BlockID) (derived eth.BlockID, err error) {
return eth.BlockID{}, nil return eth.BlockID{}, nil
} }
func (m *mockBackend) Finalized(ctx context.Context, chainID types.ChainID) (eth.BlockID, error) { func (m *mockBackend) Finalized(ctx context.Context, chainID eth.ChainID) (eth.BlockID, error) {
return eth.BlockID{}, nil return eth.BlockID{}, nil
} }
...@@ -111,13 +111,13 @@ var _ backend = (*mockBackend)(nil) ...@@ -111,13 +111,13 @@ var _ backend = (*mockBackend)(nil)
func sampleDepSet(t *testing.T) depset.DependencySet { func sampleDepSet(t *testing.T) depset.DependencySet {
depSet, err := depset.NewStaticConfigDependencySet( depSet, err := depset.NewStaticConfigDependencySet(
map[types.ChainID]*depset.StaticConfigDependency{ map[eth.ChainID]*depset.StaticConfigDependency{
types.ChainIDFromUInt64(900): { eth.ChainIDFromUInt64(900): {
ChainIndex: 900, ChainIndex: 900,
ActivationTime: 42, ActivationTime: 42,
HistoryMinTime: 100, HistoryMinTime: 100,
}, },
types.ChainIDFromUInt64(901): { eth.ChainIDFromUInt64(901): {
ChainIndex: 901, ChainIndex: 901,
ActivationTime: 30, ActivationTime: 30,
HistoryMinTime: 20, HistoryMinTime: 20,
...@@ -173,14 +173,14 @@ func TestInitFromAnchorPoint(t *testing.T) { ...@@ -173,14 +173,14 @@ func TestInitFromAnchorPoint(t *testing.T) {
} }
// after the first attach, both databases are called for update // after the first attach, both databases are called for update
_, err := controller.AttachNodeController(types.ChainIDFromUInt64(900), &ctrl, false) _, err := controller.AttachNodeController(eth.ChainIDFromUInt64(900), &ctrl, false)
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, ex.Drain()) require.NoError(t, ex.Drain())
require.Equal(t, 1, mon.anchorCalled, "an anchor point should be received") require.Equal(t, 1, mon.anchorCalled, "an anchor point should be received")
// on second attach we send the anchor again; it's up to the DB to use it or not. // on second attach we send the anchor again; it's up to the DB to use it or not.
ctrl2 := mockSyncControl{} ctrl2 := mockSyncControl{}
_, err = controller.AttachNodeController(types.ChainIDFromUInt64(901), &ctrl2, false) _, err = controller.AttachNodeController(eth.ChainIDFromUInt64(901), &ctrl2, false)
require.NoError(t, err) require.NoError(t, err)
require.NoError(t, ex.Drain()) require.NoError(t, ex.Drain())
require.Equal(t, 2, mon.anchorCalled, "anchor point again") require.Equal(t, 2, mon.anchorCalled, "anchor point again")
...@@ -199,21 +199,21 @@ func TestAttachNodeController(t *testing.T) { ...@@ -199,21 +199,21 @@ func TestAttachNodeController(t *testing.T) {
// Attach a controller for chain 900 // Attach a controller for chain 900
ctrl := mockSyncControl{} ctrl := mockSyncControl{}
_, err := controller.AttachNodeController(types.ChainIDFromUInt64(900), &ctrl, false) _, err := controller.AttachNodeController(eth.ChainIDFromUInt64(900), &ctrl, false)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, 1, controller.controllers.Len(), "controllers should have 1 entry") require.Equal(t, 1, controller.controllers.Len(), "controllers should have 1 entry")
// Attach a controller for chain 901 // Attach a controller for chain 901
ctrl2 := mockSyncControl{} ctrl2 := mockSyncControl{}
_, err = controller.AttachNodeController(types.ChainIDFromUInt64(901), &ctrl2, false) _, err = controller.AttachNodeController(eth.ChainIDFromUInt64(901), &ctrl2, false)
require.NoError(t, err) require.NoError(t, err)
require.Equal(t, 2, controller.controllers.Len(), "controllers should have 2 entries") require.Equal(t, 2, controller.controllers.Len(), "controllers should have 2 entries")
// Attach a controller for chain 902 (which is not in the dependency set) // Attach a controller for chain 902 (which is not in the dependency set)
ctrl3 := mockSyncControl{} ctrl3 := mockSyncControl{}
_, err = controller.AttachNodeController(types.ChainIDFromUInt64(902), &ctrl3, false) _, err = controller.AttachNodeController(eth.ChainIDFromUInt64(902), &ctrl3, false)
require.Error(t, err) require.Error(t, err)
require.Equal(t, 2, controller.controllers.Len(), "controllers should still have 2 entries") require.Equal(t, 2, controller.controllers.Len(), "controllers should still have 2 entries")
} }
...@@ -24,7 +24,7 @@ type SyncNodeSetup interface { ...@@ -24,7 +24,7 @@ type SyncNodeSetup interface {
type SyncSource interface { type SyncSource interface {
BlockRefByNumber(ctx context.Context, number uint64) (eth.BlockRef, error) BlockRefByNumber(ctx context.Context, number uint64) (eth.BlockRef, error)
FetchReceipts(ctx context.Context, blockHash common.Hash) (gethtypes.Receipts, error) FetchReceipts(ctx context.Context, blockHash common.Hash) (gethtypes.Receipts, error)
ChainID(ctx context.Context) (types.ChainID, error) ChainID(ctx context.Context) (eth.ChainID, error)
OutputV0AtTimestamp(ctx context.Context, timestamp uint64) (*eth.OutputV0, error) OutputV0AtTimestamp(ctx context.Context, timestamp uint64) (*eth.OutputV0, error)
PendingOutputV0AtTimestamp(ctx context.Context, timestamp uint64) (*eth.OutputV0, error) PendingOutputV0AtTimestamp(ctx context.Context, timestamp uint64) (*eth.OutputV0, error)
// String identifies the sync source // String identifies the sync source
......
...@@ -22,10 +22,10 @@ import ( ...@@ -22,10 +22,10 @@ import (
) )
type backend interface { type backend interface {
LocalSafe(ctx context.Context, chainID types.ChainID) (pair types.DerivedIDPair, err error) LocalSafe(ctx context.Context, chainID eth.ChainID) (pair types.DerivedIDPair, err error)
LocalUnsafe(ctx context.Context, chainID types.ChainID) (eth.BlockID, error) LocalUnsafe(ctx context.Context, chainID eth.ChainID) (eth.BlockID, error)
SafeDerivedAt(ctx context.Context, chainID types.ChainID, derivedFrom eth.BlockID) (derived eth.BlockID, err error) SafeDerivedAt(ctx context.Context, chainID eth.ChainID, derivedFrom eth.BlockID) (derived eth.BlockID, err error)
Finalized(ctx context.Context, chainID types.ChainID) (eth.BlockID, error) Finalized(ctx context.Context, chainID eth.ChainID) (eth.BlockID, error)
L1BlockRefByNumber(ctx context.Context, number uint64) (eth.L1BlockRef, error) L1BlockRefByNumber(ctx context.Context, number uint64) (eth.L1BlockRef, error)
} }
...@@ -37,7 +37,7 @@ const ( ...@@ -37,7 +37,7 @@ const (
type ManagedNode struct { type ManagedNode struct {
log log.Logger log log.Logger
Node SyncControl Node SyncControl
chainID types.ChainID chainID eth.ChainID
backend backend backend backend
...@@ -57,7 +57,7 @@ type ManagedNode struct { ...@@ -57,7 +57,7 @@ type ManagedNode struct {
var _ event.AttachEmitter = (*ManagedNode)(nil) var _ event.AttachEmitter = (*ManagedNode)(nil)
var _ event.Deriver = (*ManagedNode)(nil) var _ event.Deriver = (*ManagedNode)(nil)
func NewManagedNode(log log.Logger, id types.ChainID, node SyncControl, backend backend, noSubscribe bool) *ManagedNode { func NewManagedNode(log log.Logger, id eth.ChainID, node SyncControl, backend backend, noSubscribe bool) *ManagedNode {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
m := &ManagedNode{ m := &ManagedNode{
log: log.New("chain", id), log: log.New("chain", id),
......
...@@ -17,7 +17,7 @@ import ( ...@@ -17,7 +17,7 @@ import (
) )
func TestEventResponse(t *testing.T) { func TestEventResponse(t *testing.T) {
chainID := types.ChainIDFromUInt64(1) chainID := eth.ChainIDFromUInt64(1)
logger := testlog.Logger(t, log.LvlInfo) logger := testlog.Logger(t, log.LvlInfo)
syncCtrl := &mockSyncControl{} syncCtrl := &mockSyncControl{}
backend := &mockBackend{} backend := &mockBackend{}
......
...@@ -63,8 +63,8 @@ func (rs *RPCSyncNode) FetchReceipts(ctx context.Context, blockHash common.Hash) ...@@ -63,8 +63,8 @@ func (rs *RPCSyncNode) FetchReceipts(ctx context.Context, blockHash common.Hash)
return out, nil return out, nil
} }
func (rs *RPCSyncNode) ChainID(ctx context.Context) (types.ChainID, error) { func (rs *RPCSyncNode) ChainID(ctx context.Context) (eth.ChainID, error) {
var chainID types.ChainID var chainID eth.ChainID
err := rs.cl.CallContext(ctx, &chainID, "interop_chainID") err := rs.cl.CallContext(ctx, &chainID, "interop_chainID")
return chainID, err return chainID, err
} }
......
...@@ -18,12 +18,12 @@ type AdminBackend interface { ...@@ -18,12 +18,12 @@ type AdminBackend interface {
type QueryBackend interface { type QueryBackend interface {
CheckMessage(identifier types.Identifier, payloadHash common.Hash) (types.SafetyLevel, error) CheckMessage(identifier types.Identifier, payloadHash common.Hash) (types.SafetyLevel, error)
CheckMessages(messages []types.Message, minSafety types.SafetyLevel) error CheckMessages(messages []types.Message, minSafety types.SafetyLevel) error
CrossDerivedFrom(ctx context.Context, chainID types.ChainID, derived eth.BlockID) (derivedFrom eth.BlockRef, err error) CrossDerivedFrom(ctx context.Context, chainID eth.ChainID, derived eth.BlockID) (derivedFrom eth.BlockRef, err error)
LocalUnsafe(ctx context.Context, chainID types.ChainID) (eth.BlockID, error) LocalUnsafe(ctx context.Context, chainID eth.ChainID) (eth.BlockID, error)
CrossSafe(ctx context.Context, chainID types.ChainID) (types.DerivedIDPair, error) CrossSafe(ctx context.Context, chainID eth.ChainID) (types.DerivedIDPair, error)
Finalized(ctx context.Context, chainID types.ChainID) (eth.BlockID, error) Finalized(ctx context.Context, chainID eth.ChainID) (eth.BlockID, error)
FinalizedL1() eth.BlockRef FinalizedL1() eth.BlockRef
SuperRootAtTimestamp(ctx context.Context, timestamp hexutil.Uint64) (types.SuperRootResponse, error) SuperRootAtTimestamp(ctx context.Context, timestamp hexutil.Uint64) (eth.SuperRootResponse, error)
} }
type Backend interface { type Backend interface {
...@@ -51,15 +51,15 @@ func (q *QueryFrontend) CheckMessages( ...@@ -51,15 +51,15 @@ func (q *QueryFrontend) CheckMessages(
return q.Supervisor.CheckMessages(messages, minSafety) return q.Supervisor.CheckMessages(messages, minSafety)
} }
func (q *QueryFrontend) LocalUnsafe(ctx context.Context, chainID types.ChainID) (eth.BlockID, error) { func (q *QueryFrontend) LocalUnsafe(ctx context.Context, chainID eth.ChainID) (eth.BlockID, error) {
return q.Supervisor.LocalUnsafe(ctx, chainID) return q.Supervisor.LocalUnsafe(ctx, chainID)
} }
func (q *QueryFrontend) CrossSafe(ctx context.Context, chainID types.ChainID) (types.DerivedIDPair, error) { func (q *QueryFrontend) CrossSafe(ctx context.Context, chainID eth.ChainID) (types.DerivedIDPair, error) {
return q.Supervisor.CrossSafe(ctx, chainID) return q.Supervisor.CrossSafe(ctx, chainID)
} }
func (q *QueryFrontend) Finalized(ctx context.Context, chainID types.ChainID) (eth.BlockID, error) { func (q *QueryFrontend) Finalized(ctx context.Context, chainID eth.ChainID) (eth.BlockID, error) {
return q.Supervisor.Finalized(ctx, chainID) return q.Supervisor.Finalized(ctx, chainID)
} }
...@@ -67,11 +67,11 @@ func (q *QueryFrontend) FinalizedL1() eth.BlockRef { ...@@ -67,11 +67,11 @@ func (q *QueryFrontend) FinalizedL1() eth.BlockRef {
return q.Supervisor.FinalizedL1() return q.Supervisor.FinalizedL1()
} }
func (q *QueryFrontend) CrossDerivedFrom(ctx context.Context, chainID types.ChainID, derived eth.BlockID) (derivedFrom eth.BlockRef, err error) { func (q *QueryFrontend) CrossDerivedFrom(ctx context.Context, chainID eth.ChainID, derived eth.BlockID) (derivedFrom eth.BlockRef, err error) {
return q.Supervisor.CrossDerivedFrom(ctx, chainID, derived) return q.Supervisor.CrossDerivedFrom(ctx, chainID, derived)
} }
func (q *QueryFrontend) SuperRootAtTimestamp(ctx context.Context, timestamp hexutil.Uint64) (types.SuperRootResponse, error) { func (q *QueryFrontend) SuperRootAtTimestamp(ctx context.Context, timestamp hexutil.Uint64) (eth.SuperRootResponse, error) {
return q.Supervisor.SuperRootAtTimestamp(ctx, timestamp) return q.Supervisor.SuperRootAtTimestamp(ctx, timestamp)
} }
......
...@@ -5,6 +5,7 @@ import ( ...@@ -5,6 +5,7 @@ import (
"testing" "testing"
"time" "time"
"github.com/ethereum-optimism/optimism/op-service/eth"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
...@@ -22,7 +23,7 @@ import ( ...@@ -22,7 +23,7 @@ import (
) )
func TestSupervisorService(t *testing.T) { func TestSupervisorService(t *testing.T) {
depSet, err := depset.NewStaticConfigDependencySet(make(map[types.ChainID]*depset.StaticConfigDependency)) depSet, err := depset.NewStaticConfigDependencySet(make(map[eth.ChainID]*depset.StaticConfigDependency))
require.NoError(t, err) require.NoError(t, err)
cfg := &config.Config{ cfg := &config.Config{
...@@ -71,7 +72,7 @@ func TestSupervisorService(t *testing.T) { ...@@ -71,7 +72,7 @@ func TestSupervisorService(t *testing.T) {
BlockNumber: 123, BlockNumber: 123,
LogIndex: 42, LogIndex: 42,
Timestamp: 1234567, Timestamp: 1234567,
ChainID: types.ChainID{0xbb}, ChainID: eth.ChainID{0xbb},
}, common.Hash{0xcc}) }, common.Hash{0xcc})
cancel() cancel()
require.NoError(t, err) require.NoError(t, err)
......
...@@ -5,13 +5,10 @@ import ( ...@@ -5,13 +5,10 @@ import (
"errors" "errors"
"fmt" "fmt"
"math" "math"
"math/big"
"strconv" "strconv"
ethTypes "github.com/ethereum/go-ethereum/core/types" ethTypes "github.com/ethereum/go-ethereum/core/types"
"github.com/holiman/uint256"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil" "github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/crypto"
...@@ -62,7 +59,7 @@ type Identifier struct { ...@@ -62,7 +59,7 @@ type Identifier struct {
BlockNumber uint64 BlockNumber uint64
LogIndex uint32 LogIndex uint32
Timestamp uint64 Timestamp uint64
ChainID ChainID // flat, not a pointer, to make Identifier safe as map key ChainID eth.ChainID // flat, not a pointer, to make Identifier safe as map key
} }
type identifierMarshaling struct { type identifierMarshaling struct {
...@@ -95,7 +92,7 @@ func (id *Identifier) UnmarshalJSON(input []byte) error { ...@@ -95,7 +92,7 @@ func (id *Identifier) UnmarshalJSON(input []byte) error {
} }
id.LogIndex = uint32(dec.LogIndex) id.LogIndex = uint32(dec.LogIndex)
id.Timestamp = uint64(dec.Timestamp) id.Timestamp = uint64(dec.Timestamp)
id.ChainID = (ChainID)(dec.ChainID) id.ChainID = (eth.ChainID)(dec.ChainID)
return nil return nil
} }
...@@ -178,54 +175,6 @@ const ( ...@@ -178,54 +175,6 @@ const (
Invalid SafetyLevel = "invalid" Invalid SafetyLevel = "invalid"
) )
type ChainID uint256.Int
func ChainIDFromBig(chainID *big.Int) ChainID {
return ChainID(*uint256.MustFromBig(chainID))
}
func ChainIDFromUInt64(i uint64) ChainID {
return ChainID(*uint256.NewInt(i))
}
func (id ChainID) String() string {
return ((*uint256.Int)(&id)).Dec()
}
func (id ChainID) ToUInt32() (uint32, error) {
v := (*uint256.Int)(&id)
if !v.IsUint64() {
return 0, fmt.Errorf("ChainID too large for uint32: %v", id)
}
v64 := v.Uint64()
if v64 > math.MaxUint32 {
return 0, fmt.Errorf("ChainID too large for uint32: %v", id)
}
return uint32(v64), nil
}
func (id *ChainID) ToBig() *big.Int {
return (*uint256.Int)(id).ToBig()
}
func (id ChainID) MarshalText() ([]byte, error) {
return []byte(id.String()), nil
}
func (id *ChainID) UnmarshalText(data []byte) error {
var x uint256.Int
err := x.UnmarshalText(data)
if err != nil {
return err
}
*id = ChainID(x)
return nil
}
func (id ChainID) Cmp(other ChainID) int {
return (*uint256.Int)(&id).Cmp((*uint256.Int)(&other))
}
type ReferenceView struct { type ReferenceView struct {
Local eth.BlockID `json:"local"` Local eth.BlockID `json:"local"`
Cross eth.BlockID `json:"cross"` Cross eth.BlockID `json:"cross"`
...@@ -352,72 +301,3 @@ type ManagedEvent struct { ...@@ -352,72 +301,3 @@ type ManagedEvent struct {
DerivationUpdate *DerivedBlockRefPair `json:"derivationUpdate,omitempty"` DerivationUpdate *DerivedBlockRefPair `json:"derivationUpdate,omitempty"`
ExhaustL1 *DerivedBlockRefPair `json:"exhaustL1,omitempty"` ExhaustL1 *DerivedBlockRefPair `json:"exhaustL1,omitempty"`
} }
type ChainRootInfo struct {
ChainID ChainID `json:"chainID"`
// Canonical is the output root of the latest canonical block at a particular Timestamp.
Canonical eth.Bytes32 `json:"canonical"`
// Pending is the output root preimage for the latest block at a particular Timestamp prior to validation of
// executing messages. If the original block was valid, this will be the preimage of the
// output root from the Canonical array. If it was invalid, it will be the output root preimage from the
// Optimistic Block Deposited Transaction added to the deposit-only block.
Pending []byte `json:"pending"`
}
type chainRootInfoMarshalling struct {
ChainID ChainID `json:"chainID"`
Canonical common.Hash `json:"canonical"`
Pending hexutil.Bytes `json:"pending"`
}
func (i ChainRootInfo) MarshalJSON() ([]byte, error) {
return json.Marshal(&chainRootInfoMarshalling{
ChainID: i.ChainID,
Canonical: common.Hash(i.Canonical),
Pending: i.Pending,
})
}
func (i *ChainRootInfo) UnmarshalJSON(input []byte) error {
var dec chainRootInfoMarshalling
if err := json.Unmarshal(input, &dec); err != nil {
return err
}
i.ChainID = dec.ChainID
i.Canonical = eth.Bytes32(dec.Canonical)
i.Pending = dec.Pending
return nil
}
type SuperRootResponse struct {
Timestamp uint64 `json:"timestamp"`
SuperRoot eth.Bytes32 `json:"superRoot"`
// Chains is the list of ChainRootInfo for each chain in the dependency set.
// It represents the state of the chain at or before the Timestamp.
Chains []ChainRootInfo `json:"chains"`
}
type superRootResponseMarshalling struct {
Timestamp hexutil.Uint64 `json:"timestamp"`
SuperRoot common.Hash `json:"superRoot"`
Chains []ChainRootInfo `json:"chains"`
}
func (r SuperRootResponse) MarshalJSON() ([]byte, error) {
return json.Marshal(&superRootResponseMarshalling{
Timestamp: hexutil.Uint64(r.Timestamp),
SuperRoot: common.Hash(r.SuperRoot),
Chains: r.Chains,
})
}
func (r *SuperRootResponse) UnmarshalJSON(input []byte) error {
var dec superRootResponseMarshalling
if err := json.Unmarshal(input, &dec); err != nil {
return err
}
r.Timestamp = uint64(dec.Timestamp)
r.SuperRoot = eth.Bytes32(dec.SuperRoot)
r.Chains = dec.Chains
return nil
}
...@@ -2,14 +2,13 @@ package types ...@@ -2,14 +2,13 @@ package types
import ( import (
"encoding/json" "encoding/json"
"math"
"math/big" "math/big"
"testing" "testing"
"github.com/ethereum-optimism/optimism/op-service/eth"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
"github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/common"
"github.com/holiman/uint256"
) )
func FuzzRoundtripIdentifierJSONMarshal(f *testing.F) { func FuzzRoundtripIdentifierJSONMarshal(f *testing.F) {
...@@ -23,7 +22,7 @@ func FuzzRoundtripIdentifierJSONMarshal(f *testing.F) { ...@@ -23,7 +22,7 @@ func FuzzRoundtripIdentifierJSONMarshal(f *testing.F) {
BlockNumber: blockNumber, BlockNumber: blockNumber,
LogIndex: logIndex, LogIndex: logIndex,
Timestamp: timestamp, Timestamp: timestamp,
ChainID: ChainIDFromBig(new(big.Int).SetBytes(chainID)), ChainID: eth.ChainIDFromBig(new(big.Int).SetBytes(chainID)),
} }
raw, err := json.Marshal(&id) raw, err := json.Marshal(&id)
...@@ -39,35 +38,3 @@ func FuzzRoundtripIdentifierJSONMarshal(f *testing.F) { ...@@ -39,35 +38,3 @@ func FuzzRoundtripIdentifierJSONMarshal(f *testing.F) {
require.Equal(t, id.ChainID, dec.ChainID) require.Equal(t, id.ChainID, dec.ChainID)
}) })
} }
func TestChainID_String(t *testing.T) {
tests := []struct {
input ChainID
expected string
}{
{ChainIDFromUInt64(0), "0"},
{ChainIDFromUInt64(1), "1"},
{ChainIDFromUInt64(871975192374), "871975192374"},
{ChainIDFromUInt64(math.MaxInt64), "9223372036854775807"},
{ChainID(*uint256.NewInt(math.MaxUint64)), "18446744073709551615"},
{ChainID(*uint256.MustFromDecimal("1844674407370955161618446744073709551616")), "1844674407370955161618446744073709551616"},
}
for _, test := range tests {
test := test
t.Run(test.expected, func(t *testing.T) {
t.Run("String", func(t *testing.T) {
require.Equal(t, test.expected, test.input.String())
})
t.Run("MarshalText", func(t *testing.T) {
data, err := test.input.MarshalText()
require.NoError(t, err)
require.Equal(t, test.expected, string(data))
})
t.Run("UnmarshalText", func(t *testing.T) {
var id ChainID
require.NoError(t, id.UnmarshalText([]byte(test.expected)))
require.Equal(t, test.input, id)
})
})
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment