Skip to content

Commit

Permalink
feat: support for adding interop contracts to forked networks
Browse files Browse the repository at this point in the history
  • Loading branch information
tremarkley committed Aug 13, 2024
1 parent 9528b8d commit e37e0e6
Show file tree
Hide file tree
Showing 9 changed files with 176 additions and 58 deletions.
2 changes: 1 addition & 1 deletion cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ var (
)

const (
minAnvilTimestamp = "2024-07-25T15:52:50.932621000Z"
minAnvilTimestamp = "2024-08-12T00:20:02.123144000Z"
)

func main() {
Expand Down
1 change: 1 addition & 0 deletions config/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ var (
type ForkConfig struct {
RPCUrl string
BlockNumber uint64
UseInterop bool
}

type SecretsConfig struct {
Expand Down
9 changes: 9 additions & 0 deletions config/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const (

ChainsFlagName = "chains"
NetworkFlagName = "network"
InteropFlagName = "experiment.interop"
L2StartingPortFlagName = "l2.starting.port"
)

Expand Down Expand Up @@ -61,13 +62,20 @@ func ForkCLIFlags(envPrefix string) []cli.Flag {
Usage: fmt.Sprintf("superchain network. options: %s. In order to replace the public rpc endpoint for the network, specify the ($%s_RPC_URL_<NETWORK>) env variable. i.e SUPERSIM_RPC_URL_MAINNET=http://mainnet.infura.io/v3/<API-KEY>", networks, envPrefix),
EnvVars: opservice.PrefixEnvVar(envPrefix, "NETWORK"),
},
&cli.BoolFlag{
Name: InteropFlagName,
Value: false,
Usage: "Enable interop in fork mode",
EnvVars: opservice.PrefixEnvVar(envPrefix, "FORK_WITH_INTEROP"),
},
}
}

type ForkCLIConfig struct {
L1ForkHeight uint64
Network string
Chains []string
UseInterop bool
}

type CLIConfig struct {
Expand All @@ -88,6 +96,7 @@ func ReadCLIConfig(ctx *cli.Context) (*CLIConfig, error) {
L1ForkHeight: ctx.Uint64(L1ForkHeightFlagName),
Network: ctx.String(NetworkFlagName),
Chains: ctx.StringSlice(ChainsFlagName),
UseInterop: ctx.Bool(InteropFlagName),
}
}

Expand Down
6 changes: 1 addition & 5 deletions contracts/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,7 @@ cache/
out/

# Ignores development broadcast logs
!/broadcast
/broadcast/*/31337/
/broadcast/*/901/
/broadcast/*/902/
/broadcast/**/dry-run/
/broadcast

# Docs
docs/
Expand Down
120 changes: 110 additions & 10 deletions genesis/applier.go
Original file line number Diff line number Diff line change
@@ -1,27 +1,127 @@
package genesis

import (
"context"
_ "embed"
"encoding/json"
"fmt"
"math/big"
"strings"
"sync"

"github.com/ethereum/go-ethereum/core"
"github.com/ethereum-optimism/optimism/op-service/predeploys"

"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/ethclient"
)

func ApplyChainID(genesisJson []byte, chainId *big.Int) ([]byte, error) {
var genesis core.Genesis
if err := json.Unmarshal(genesisJson, &genesis); err != nil {
return nil, fmt.Errorf("unable to parse genesis json: %w", err)
//go:embed generated/l2-allocs/901-l2-allocs.json
var l2AllocsJSON []byte

type alloc struct {
Balance string `json:"balance"`
Code string `json:"code"`
Nonce string `json:"nonce"`
Storage map[string]string `json:"storage"`
}

type allocs map[string]alloc

type predeploy struct {
proxy common.Address
impl common.Address
}

var interopProxyPredeploys = []common.Address{
predeploys.CrossL2InboxAddr,
predeploys.L2toL2CrossDomainMessengerAddr,
predeploys.L1BlockAddr,
}

const (
emptyCode = "0x"
)

// Uses same logic as `predeployToCodeNamespace` in Predeploy.sol to determine impl address.
func predeployToCodeNamespace(addr common.Address) common.Address {
addrBigInt := new(big.Int).SetBytes(addr.Bytes())

namespaceBigInt := new(big.Int).SetBytes(common.FromHex("0xc0D3C0d3C0d3C0D3c0d3C0d3c0D3C0d3c0d30000"))
resultBigInt := new(big.Int).Or(new(big.Int).And(addrBigInt, big.NewInt(0xffff)), namespaceBigInt)

return common.BytesToAddress(resultBigInt.Bytes())
}

func fetchAllocForAddr(addr common.Address, allocsJSON []byte) (*alloc, error) {
var allocs allocs
err := json.Unmarshal(allocsJSON, &allocs)
if err != nil {
return nil, fmt.Errorf("Failed to unmarshal allocs: %s", err)
}

alloc, exists := allocs[strings.ToLower(addr.String())]
if !exists {
return nil, fmt.Errorf("alloc not found: %s", addr)
}

if genesis.Config.ChainID.Cmp(chainId) != 0 {
genesis.Config.ChainID = chainId
return &alloc, nil
}

func applyAllocToAddress(ctx context.Context, rpcClient *ethclient.Client, alloc *alloc, address common.Address) error {
if alloc.Code != emptyCode {
err := rpcClient.Client().CallContext(ctx, nil, "anvil_setCode", address.Hex(), alloc.Code)
if err != nil {
return fmt.Errorf("failed to set code for %s: %w", address, err)
}
}
if alloc.Storage != nil {
for storageSlot, storageValue := range alloc.Storage {
err := rpcClient.Client().CallContext(ctx, nil, "anvil_setStorageAt", address.Hex(), storageSlot, storageValue)
if err != nil {
return fmt.Errorf("failed to set storage for %s: %w", address, err)
}
}
}
return nil
}

func applyAllocForPredeploy(ctx context.Context, rpcClient *ethclient.Client, predeploy predeploy, allocsJSON []byte) error {
implAlloc, err := fetchAllocForAddr(predeploy.impl, allocsJSON)
if err != nil {
return fmt.Errorf("failed to fetch alloc for %s: %w", predeploy.impl, err)
}
if err := applyAllocToAddress(ctx, rpcClient, implAlloc, predeploy.impl); err != nil {
return fmt.Errorf("failed to apply alloc for %s: %w", predeploy.impl, err)
}

result, err := json.Marshal(genesis)
proxyAlloc, err := fetchAllocForAddr(predeploy.proxy, allocsJSON)
if err != nil {
return nil, fmt.Errorf("error marshaling genesis: %w", err)
return fmt.Errorf("failed to fetch alloc for %s: %w", predeploy.proxy, err)
}
if err := applyAllocToAddress(ctx, rpcClient, proxyAlloc, predeploy.proxy); err != nil {
return fmt.Errorf("failed to apply alloc for %s: %w", predeploy.proxy, err)
}

return nil
}

func ConfigureInteropForChain(ctx context.Context, rpcClient *ethclient.Client) {
var interopPredeploys []predeploy
for _, proxy := range interopProxyPredeploys {
implContractAddress := predeployToCodeNamespace(proxy)
interopPredeploys = append(interopPredeploys, predeploy{proxy: proxy, impl: implContractAddress})
}

var wg sync.WaitGroup
wg.Add(len(interopPredeploys))
for _, predeploy := range interopPredeploys {
predeploy := predeploy
go func() {
defer wg.Done()
applyAllocForPredeploy(ctx, rpcClient, predeploy, l2AllocsJSON)

Check failure on line 121 in genesis/applier.go

View workflow job for this annotation

GitHub Actions / go-lint

Error return value is not checked (errcheck)
}()

}

return result, nil
wg.Wait()
}
10 changes: 5 additions & 5 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ go 1.22.3
require (
github.com/btcsuite/btcd v0.24.2
github.com/btcsuite/btcd/btcutil v1.1.5
github.com/ethereum-optimism/optimism v1.8.1-0.20240802214749-e1c7dbe2c420
github.com/ethereum-optimism/superchain-registry/superchain v0.0.0-20240801182704-4810f97b7ee9
github.com/ethereum-optimism/optimism v1.9.1-0.20240808190618-0c8d7c8c5186
github.com/ethereum-optimism/superchain-registry/superchain v0.0.0-20240803025447-c92ef420eec2
github.com/ethereum/go-ethereum v1.13.15
github.com/stretchr/testify v1.9.0
github.com/tyler-smith/go-bip39 v1.1.0
Expand Down Expand Up @@ -89,18 +89,18 @@ require (
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 // indirect
golang.org/x/mod v0.19.0 // indirect
golang.org/x/net v0.27.0 // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/sys v0.22.0 // indirect
golang.org/x/term v0.22.0 // indirect
golang.org/x/text v0.16.0 // indirect
golang.org/x/time v0.5.0 // indirect
golang.org/x/time v0.6.0 // indirect
golang.org/x/tools v0.23.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
rsc.io/tmplfunc v0.0.3 // indirect
)

replace github.com/ethereum/go-ethereum => github.com/ethereum-optimism/op-geth v1.101315.3-rc.1
replace github.com/ethereum/go-ethereum => github.com/ethereum-optimism/op-geth v1.101315.3-rc.2

replace github.com/crate-crypto/go-kzg-4844 v1.0.0 => github.com/crate-crypto/go-kzg-4844 v0.7.0
20 changes: 10 additions & 10 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,12 @@ github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0/go.mod h1:v57UDF4pDQJcEfFUCRop3
github.com/decred/dcrd/lru v1.0.0/go.mod h1:mxKOwFd7lFjN2GZYsiz/ecgqR6kkYAl+0pz0tEMk218=
github.com/ethereum-optimism/go-ethereum-hdwallet v0.1.3 h1:RWHKLhCrQThMfch+QJ1Z8veEq5ZO3DfIhZ7xgRP9WTc=
github.com/ethereum-optimism/go-ethereum-hdwallet v0.1.3/go.mod h1:QziizLAiF0KqyLdNJYD7O5cpDlaFMNZzlxYNcWsJUxs=
github.com/ethereum-optimism/op-geth v1.101315.3-rc.1 h1:Q/B0FBdtglzsFtqurvUsiNfH8isCOFFF/pf9ss0L4eY=
github.com/ethereum-optimism/op-geth v1.101315.3-rc.1/go.mod h1:h5C5tP+7gkMrlUGENuiV5ddlwJ4RxLdmdapRuTAGlnw=
github.com/ethereum-optimism/optimism v1.8.1-0.20240802214749-e1c7dbe2c420 h1:xRHLzOR1A12EWS6YXk6jhng9qKuvis4UvIfjkXZ1pog=
github.com/ethereum-optimism/optimism v1.8.1-0.20240802214749-e1c7dbe2c420/go.mod h1:GE3IIBkV9ELGuu5qcy2MsEWNaGCGbaYlXSnRGztFioM=
github.com/ethereum-optimism/superchain-registry/superchain v0.0.0-20240801182704-4810f97b7ee9 h1:Yqi7oOCWRN3SMl3rL5zGYSHIw2MyuTJ1nqokSi7ejfU=
github.com/ethereum-optimism/superchain-registry/superchain v0.0.0-20240801182704-4810f97b7ee9/go.mod h1:zy9f3TNPS7pwW4msMitF83fp0Wf452tZ6+Fg6d4JyXM=
github.com/ethereum-optimism/op-geth v1.101315.3-rc.2 h1:4Ne3RUZ09uqY5QnbVuDVD2Xt8JbxegCv3mkICt3aT6c=
github.com/ethereum-optimism/op-geth v1.101315.3-rc.2/go.mod h1:nZ3TvP4mhOsfKkrgaT3GrDO4oCn5awPXFHKpVHuO63s=
github.com/ethereum-optimism/optimism v1.9.1-0.20240808190618-0c8d7c8c5186 h1:CFRDZakOMGPHjGR0NMf40zWEykHBNSVoTdbyhhYJBkQ=
github.com/ethereum-optimism/optimism v1.9.1-0.20240808190618-0c8d7c8c5186/go.mod h1:2yZhdVfBNNvWEzEC2OrIDmLwXu4YTU2yr65TBkpVY0E=
github.com/ethereum-optimism/superchain-registry/superchain v0.0.0-20240803025447-c92ef420eec2 h1:ySJykDUyb8RbcfLL3pz0Cs5Ji6NMVT7kmAY634DOCoE=
github.com/ethereum-optimism/superchain-registry/superchain v0.0.0-20240803025447-c92ef420eec2/go.mod h1:zy9f3TNPS7pwW4msMitF83fp0Wf452tZ6+Fg6d4JyXM=
github.com/ethereum/c-kzg-4844 v1.0.0 h1:0X1LBXxaEtYD9xsyj9B9ctQEZIpnvVDeoBx8aHEwTNA=
github.com/ethereum/c-kzg-4844 v1.0.0/go.mod h1:VewdlzQmpT5QSrVhbBuGoCdFJkpaJlO1aQputP83wc0=
github.com/fjl/memsize v0.0.2 h1:27txuSD9or+NZlnOWdKUxeBzTAUkWCVh+4Gf2dWFOzA=
Expand Down Expand Up @@ -351,8 +351,8 @@ golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ=
golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
Expand Down Expand Up @@ -391,8 +391,8 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4=
golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI=
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/time v0.6.0 h1:eTDhh4ZXt5Qf0augr54TN6suAUudPcawVZeIAPU7D4U=
golang.org/x/time v0.6.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
Expand Down
45 changes: 20 additions & 25 deletions opsimulator/opsimulator.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ import (
"math/big"
"net"
"net/http"
"net/http/httputil"
"net/url"
"strconv"
"strings"
"sync/atomic"
Expand All @@ -21,7 +19,9 @@ import (

"github.com/ethereum-optimism/supersim/anvil"
"github.com/ethereum-optimism/supersim/config"
"github.com/ethereum-optimism/supersim/genesis"
"github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/core/types"
Expand Down Expand Up @@ -95,13 +95,8 @@ func New(log log.Logger, port uint64, l1Chain, l2Chain config.Chain, l2Config *c
}

func (opSim *OpSimulator) Start(ctx context.Context) error {
proxy, err := opSim.createReverseProxy()
if err != nil {
return fmt.Errorf("error creating reverse proxy: %w", err)
}

mux := http.NewServeMux()
mux.Handle("/", opSim.handler(proxy, ctx))
mux.Handle("/", opSim.handler(ctx))

hs, err := ophttp.StartHTTPServer(net.JoinHostPort(host, fmt.Sprintf("%d", opSim.port)), mux)
if err != nil {
Expand All @@ -118,6 +113,10 @@ func (opSim *OpSimulator) Start(ctx context.Context) error {
}
}

if opSim.Config().ForkConfig != nil && opSim.Config().ForkConfig.UseInterop {
genesis.ConfigureInteropForChain(ctx, opSim.l2Chain.EthClient())
}

opSim.startStartupTasks()
if err := opSim.startupTasks.Wait(); err != nil {
return fmt.Errorf("failed to start opsimulator: %w", err)
Expand Down Expand Up @@ -146,7 +145,7 @@ func (opSim *OpSimulator) Stopped() bool {
func (opSim *OpSimulator) startStartupTasks() {
for _, chainID := range opSim.L2Config.DependencySet {
opSim.startupTasks.Go(func() error {
return opSim.AddDependency(chainID, opSim.L2Config.DependencySet)
return opSim.AddDependency(chainID)
})
}
}
Expand Down Expand Up @@ -179,7 +178,7 @@ func (opSim *OpSimulator) startBackgroundTasks() {
})
}

func (opSim *OpSimulator) handler(proxy *httputil.ReverseProxy, ctx context.Context) http.HandlerFunc {
func (opSim *OpSimulator) handler(ctx context.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions {
// handle preflight requests
Expand Down Expand Up @@ -322,17 +321,26 @@ func forwardRPCRequest(ctx context.Context, rpcClient *rpc.Client, req *jsonRpcM
}

// Update dependency set on the L2#L1BlockInterop using a deposit tx
func (opSim *OpSimulator) AddDependency(chainID uint64, depSet []uint64) error {
func (opSim *OpSimulator) AddDependency(chainID uint64) error {
dep, err := NewAddDependencyDepositTx(big.NewInt(int64(chainID)))

if err != nil {
return fmt.Errorf("failed to create setConfig deposit tx: %w", err)
}

if err := opSim.l2Chain.EthSendTransaction(context.Background(), types.NewTx(dep)); err != nil {
tx := types.NewTx(dep)
if err := opSim.l2Chain.EthSendTransaction(context.Background(), tx); err != nil {
return fmt.Errorf("failed to send setConfig deposit tx: %w", err)
}

txReceipt, err := bind.WaitMined(context.Background(), opSim.l2Chain.EthClient(), tx)
if err != nil {
return fmt.Errorf("failed to get tx receipt for deposit tx: %w", err)
}
if txReceipt.Status == 0 {
return fmt.Errorf("setConfig deposit tx failed")
}

return nil
}

Expand Down Expand Up @@ -458,19 +466,6 @@ func getFromAddress(tx *types.Transaction) (common.Address, error) {
return from, err
}

func (opSim *OpSimulator) createReverseProxy() (*httputil.ReverseProxy, error) {
targetURL, err := url.Parse(opSim.l2Chain.Endpoint())
if err != nil {
return nil, fmt.Errorf("failed to parse target URL: %w", err)
}
proxy := &httputil.ReverseProxy{
Rewrite: func(r *httputil.ProxyRequest) {
r.SetURL(targetURL)
},
}
return proxy, nil
}

func (opSim *OpSimulator) Endpoint() string {
return fmt.Sprintf("http://%s:%d", host, opSim.port)
}
Expand Down
Loading

0 comments on commit e37e0e6

Please sign in to comment.