diff --git a/.github/workflows/ci-cd-main-branch-docker-images.yml b/.github/workflows/ci-cd-main-branch-docker-images.yml index 1f34f03dbae..746c207dcda 100644 --- a/.github/workflows/ci-cd-main-branch-docker-images.yml +++ b/.github/workflows/ci-cd-main-branch-docker-images.yml @@ -62,7 +62,7 @@ jobs: export tag_name='docker_pectra'; export keep_images=5; export latest_suffix=''; - export binaries="erigon caplin diag devnet downloader evm hack integration rpcdaemon rpctest sentinel sentry state txpool" + export binaries="erigon caplin diag downloader evm hack integration rpcdaemon rpctest sentinel sentry state txpool" ;; * ) # use last string after last slash '/' by default if branch contains slash: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8429e08058c..52901091610 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -11,7 +11,7 @@ env: DOCKER_BASE_IMAGE: "debian:12-slim" APP_REPO: "erigontech/erigon" PACKAGE: "github.com/erigontech/erigon" - BINARIES: "erigon downloader devnet evm caplin diag integration rpcdaemon sentry txpool" + BINARIES: "erigon downloader evm caplin diag integration rpcdaemon sentry txpool" DOCKERHUB_REPOSITORY: "erigontech/erigon" DOCKERHUB_REPOSITORY_DEV: "erigontech/dev-erigon" DOCKERFILE_PATH: "Dockerfile" diff --git a/Makefile b/Makefile index de04015af3e..33b626ce578 100644 --- a/Makefile +++ b/Makefile @@ -136,7 +136,6 @@ geth: erigon erigon: go-version erigon.cmd @rm -f $(GOBIN)/tg # Remove old binary to prevent confusion where users still use it because of the scripts -COMMANDS += devnet COMMANDS += capcli COMMANDS += downloader COMMANDS += hack diff --git a/cmd/devnet/README.md b/cmd/devnet/README.md deleted file mode 100644 index 6967649a57a..00000000000 --- a/cmd/devnet/README.md +++ /dev/null @@ -1,130 +0,0 @@ -# Devnet - -This is an automated tool run on the devnet that simulates p2p connection between nodes and ultimately tests operations on them. -See [DEV_CHAIN](https://github.com/erigontech/erigon/blob/main/docs/DEV_CHAIN.md) for a manual version. - -The devnet code performs 3 main functions: - -* It runs a series of internal Erigon nodes which will connect to each other to form an internal P2P network -* It allows for the specification of a series of scenarios which will be run against the nodes on that internal network -* It can optionally run a `support` connection which allows the nodes on the network to be connected to the Erigon diagnostic system - -The specification of both nodes and scenarios for the devnet is done by specifying configuration objects. These objects are currently built in code using go `structs` but are capable of being read as configuration. - -## Devnet runtime start-up - -The devnet runs as a single `go` process which can be started with the following arguments: - -| Arg | Required | Default | Description | -| --- | -------- |---------| ----------- | -| datadir | Y | | The data directory for the devnet contains all the devnet nodes data and logs | -| chain | N | dev | The devnet chain to run currently supported: dev or bor-devnet | -| bor.withoutheimdall | N | false | Bor specific - tells the devnet to run without a heimdall service. With this flag only a single validator is supported on the devnet | -| metrics | N | false | Enable metrics collection and reporting from devnet nodes | -| metrics.node | N | 0 | At the moment only one node on the network can produce metrics. This value specifies index of the node in the cluster to attach to | -| metrics.port | N | 6061 | The network port of the node to connect to for gather ing metrics | -| diagnostics.addr | N | | Address of the diagnostics system provided by the support team, include unique session PIN, if this is specified the devnet will start a `support` tunnel and connect to the diagnostics platform to provide metrics from the specified node on the devnet | -| insecure | N | false | Used if `diagnostics.addr` is set to allow communication with diagnostics system - -## Network Configuration - -Networks configurations are currently specified in code in `main.go` in the `selectNetwork` function. This contains a series of `structs` with the following structure, for example: - -```go - return &devnet.Network{ - DataDir: dataDir, - Chain: networkname.DevChainName, - Logger: logger, - BasePrivateApiAddr: "localhost:10090", - BaseRPCAddr: "localhost:8545", - Nodes: []devnet.Node{ - args.Miner{ - Node: args.Node{ - ConsoleVerbosity: "0", - DirVerbosity: "5", - }, - AccountSlots: 200, - }, - args.NonMiner{ - Node: args.Node{ - ConsoleVerbosity: "0", - DirVerbosity: "5", - }, - }, - }, - }, nil -``` - -Base IP's and addresses are iterated for each node in the network - to ensure that when the network starts there are no port clashes as the entire network operates in a single process, hence shares a common host. Individual nodes will be configured with a default set of command line arguments dependent on type. To see the default arguments per node look at the `args\node.go` file where these are specified as tags on the struct members. - -## Scenario Configuration - -Scenarios are similarly specified in code in `main.go` in the `action` function. This is the initial configuration: - -```go - scenarios.Scenario{ - Name: "all", - Steps: []*scenarios.Step{ - {Text: "InitSubscriptions", Args: []any{[]requests.SubMethod{requests.Methods.ETHNewHeads}}}, - {Text: "PingErigonRpc"}, - {Text: "CheckTxPoolContent", Args: []any{0, 0, 0}}, - {Text: "SendTxWithDynamicFee", Args: []any{recipientAddress, accounts.DevAddress, sendValue}}, - {Text: "AwaitBlocks", Args: []any{2 * time.Second}}, - }, - }) -``` - -Scenarios are created a groups of steps which are created by registering a `step` handler too see an example of this take a look at the `commands\ping.go` file which adds a ping rpc method (see `PingErigonRpc` above). - -This illustrates the registration process. The `init` function in the file registers the method with the `scenarios` package - which uses the function name as the default step name. Others can be added with additional string arguments fo the `StepHandler` call where they will treated as regular expressions to be matched when processing scenario steps. - -```go -func init() { - scenarios.MustRegisterStepHandlers( - scenarios.StepHandler(PingErigonRpc), - ) -} -``` -Each step method will be called with a `context.Context` as its initial argument. This context provides access to the underlying devnet - so the step handler can use it for processing. - -```go -func PingErigonRpc(ctx context.Context) error { - ... -} -``` -The devnet currently supports the following context methods: - -```go -func Logger(ctx context.Context) log.Logger -``` - -Fetch the devnet logger - which can be used for logging step processing. - -```go -func SelectNode(ctx context.Context, selector ...interface{}) -``` - -This method selects a node on the network the selector argument can be either an `int` index or an implementation of the `network.NodeSelector` interface. If no selector is specified an either the `current node` will be returned or a node will be selected at random from the network. - -```go -func SelectMiner(ctx context.Context, selector ...interface{}) -``` - -This method selects a mining node on the network the selector argument can be either an `int` index or an implementation of the `network.NodeSelector` interface. If no selector is specified an either the `current node` will be returned or a miner will be selected at random from the network. - -```go -func SelectNonMiner(ctx context.Context, selector ...interface{}) -``` - -This method selects a non mining node on the network the selector argument can be either an `int` index or an implementation of the `network.NodeSelector` interface. If no selector is specified an either the `current node` will be returned or a non-miner will be selected at random from the network. - -```go -func WithCurrentNode(ctx context.Context, selector interface{}) Context -``` -This method sets the `current node` on the network. This can be called to create a context with a fixed node which can be passed to subsequent step functions so that they will operate on a defined network node. - -```go -func CurrentNode(ctx context.Context) Node -``` - -This method returns the current node from the network context. diff --git a/cmd/devnet/accounts/accounts.go b/cmd/devnet/accounts/accounts.go deleted file mode 100644 index a18a7d03ee0..00000000000 --- a/cmd/devnet/accounts/accounts.go +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package accounts - -import ( - "crypto/ecdsa" - - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon-lib/crypto" - "github.com/erigontech/erigon/core" -) - -const DevAddress = "0x67b1d87101671b127f5f8714789C7192f7ad340e" - -type Account struct { - Name string - Address common.Address - sigKey *ecdsa.PrivateKey -} - -func init() { - core.DevnetSignKey = func(addr common.Address) *ecdsa.PrivateKey { - return SigKey(addr) - } - - devnetEtherbaseAccount := &Account{ - "DevnetEtherbase", - core.DevnetEtherbase, - core.DevnetSignPrivateKey, - } - accountsByAddress[core.DevnetEtherbase] = devnetEtherbaseAccount - accountsByName[devnetEtherbaseAccount.Name] = devnetEtherbaseAccount -} - -var accountsByAddress = map[common.Address]*Account{} -var accountsByName = map[string]*Account{} - -func NewAccount(name string) *Account { - if account, ok := accountsByName[name]; ok { - return account - } - - sigKey, _ := crypto.GenerateKey() - - account := &Account{ - Name: name, - Address: crypto.PubkeyToAddress(sigKey.PublicKey), - sigKey: sigKey, - } - - accountsByAddress[account.Address] = account - accountsByName[name] = account - - return account -} - -func (a *Account) SigKey() *ecdsa.PrivateKey { - return a.sigKey -} - -func GetAccount(account string) *Account { - if account, ok := accountsByName[account]; ok { - return account - } - - if account, ok := accountsByAddress[common.HexToAddress(account)]; ok { - return account - } - - return nil -} - -func SigKey(source interface{}) *ecdsa.PrivateKey { - switch source := source.(type) { - case common.Address: - if account, ok := accountsByAddress[source]; ok { - return account.sigKey - } - - if source == core.DevnetEtherbase { - return core.DevnetSignPrivateKey - } - case string: - if account := GetAccount(source); account != nil { - return account.sigKey - } - } - - return nil -} diff --git a/cmd/devnet/accounts/steps/steps.go b/cmd/devnet/accounts/steps/steps.go deleted file mode 100644 index db785c13bdc..00000000000 --- a/cmd/devnet/accounts/steps/steps.go +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package accounts_steps - -import ( - "context" - "encoding/json" - "fmt" - "math/big" - - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon/cmd/devnet/accounts" - "github.com/erigontech/erigon/cmd/devnet/devnet" - "github.com/erigontech/erigon/cmd/devnet/scenarios" - "github.com/erigontech/erigon/cmd/devnet/services" - "github.com/erigontech/erigon/cmd/devnet/transactions" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/rpc" - "github.com/erigontech/erigon/rpc/ethapi" - "github.com/erigontech/erigon/rpc/requests" -) - -func init() { - scenarios.MustRegisterStepHandlers( - scenarios.StepHandler(CreateAccount), - scenarios.StepHandler(CreateAccountWithFunds), - scenarios.StepHandler(SendFunds), - scenarios.StepHandler(GetBalance), - scenarios.StepHandler(GetNonce), - ) -} - -func CreateAccount(ctx context.Context, name string) (*accounts.Account, error) { - if account := accounts.GetAccount(name); account != nil { - return account, nil - } - - return accounts.NewAccount(name), nil -} - -func CreateAccountWithFunds(ctx context.Context, chainName string, name string, ethAmount float64) (*accounts.Account, error) { - account, err := CreateAccount(ctx, name) - - if err != nil { - return nil, err - } - - if _, err = SendFunds(ctx, chainName, name, ethAmount); err != nil { - return nil, err - } - - return account, nil -} - -func SendFunds(ctx context.Context, chainName string, name string, ethAmount float64) (uint64, error) { - chainCtx := devnet.WithCurrentNetwork(ctx, chainName) - faucet := services.Faucet(chainCtx) - - account := accounts.GetAccount(name) - - if account == nil { - return 0, fmt.Errorf("Unknown account: %s", name) - } - - facuetStartingBalance, _ := faucet.Balance(chainCtx) - - sent, hash, err := faucet.Send(chainCtx, account, ethAmount) - - if err != nil { - return 0, err - } - - blockMap, err := transactions.AwaitTransactions(chainCtx, hash) - - if err != nil { - return 0, fmt.Errorf("Failed to get transfer tx: %w", err) - } - - blockNum, _ := blockMap[hash] - - logs, err := faucet.Contract().FilterSent(&bind.FilterOpts{ - Start: blockNum, - End: &blockNum, - }) - - if err != nil { - return 0, fmt.Errorf("Failed to get post transfer logs: %w", err) - } - - sendConfirmed := false - - for logs.Next() { - if account.Address != logs.Event.Destination { - return 0, fmt.Errorf("Unexpected send destination: %s", logs.Event.Destination) - } - - if sent.Cmp(logs.Event.Amount) != 0 { - return 0, fmt.Errorf("Unexpected send amount: %s", logs.Event.Amount) - } - - sendConfirmed = true - } - - node := devnet.SelectBlockProducer(chainCtx) - - if !sendConfirmed { - logger := devnet.Logger(chainCtx) - - traceResults, err := node.TraceTransaction(hash) - - if err != nil { - return 0, fmt.Errorf("Send transaction failure: transaction trace failed: %w", err) - } - - for _, traceResult := range traceResults { - accountResult, err := node.DebugAccountAt(traceResult.BlockHash, traceResult.TransactionPosition, faucet.Address()) - - if err != nil { - return 0, fmt.Errorf("Send transaction failure: account debug failed: %w", err) - } - - logger.Info("Faucet account details", "address", faucet.Address(), "account", accountResult) - - accountCode, err := node.GetCode(faucet.Address(), rpc.AsBlockReference(traceResult.BlockHash)) - - if err != nil { - return 0, fmt.Errorf("Send transaction failure: get account code failed: %w", err) - } - - logger.Info("Faucet account code", "address", faucet.Address(), "code", accountCode) - - callResults, err := node.TraceCall(rpc.AsBlockReference(blockNum), ethapi.CallArgs{ - From: &traceResult.Action.From, - To: &traceResult.Action.To, - Data: &traceResult.Action.Input, - }, requests.TraceOpts.StateDiff, requests.TraceOpts.Trace, requests.TraceOpts.VmTrace) - - if err != nil { - return 0, fmt.Errorf("Send transaction failure: trace call failed: %w", err) - } - - results, _ := json.MarshalIndent(callResults, " ", " ") - logger.Debug("Send transaction call trace", "hash", hash, "trace", string(results)) - } - } - - balance, err := faucet.Balance(chainCtx) - - if err != nil { - return 0, fmt.Errorf("Failed to get post transfer faucet balance: %w", err) - } - - if balance.Cmp((&big.Int{}).Sub(facuetStartingBalance, sent)) != 0 { - return 0, fmt.Errorf("Unexpected post transfer faucet balance got: %s:, expected: %s", balance, (&big.Int{}).Sub(facuetStartingBalance, sent)) - } - - balance, err = node.GetBalance(account.Address, rpc.LatestBlock) - - if err != nil { - return 0, fmt.Errorf("Failed to get post transfer balance: %w", err) - } - - if balance.Cmp(sent) != 0 { - return 0, fmt.Errorf("Unexpected post transfer balance got: %s:, expected: %s", balance, sent) - } - - return balance.Uint64(), nil -} - -func GetBalance(ctx context.Context, accountName string, blockNum rpc.BlockNumber) (uint64, error) { - logger := devnet.Logger(ctx) - - node := devnet.CurrentNode(ctx) - - if node == nil { - node = devnet.SelectBlockProducer(ctx) - } - - account := accounts.GetAccount(accountName) - - if account == nil { - err := fmt.Errorf("Unknown account: %s", accountName) - logger.Error("FAILURE", "error", err) - return 0, err - } - - logger.Info("Getting balance", "address", account.Address) - - bal, err := node.GetBalance(account.Address, rpc.AsBlockReference(blockNum)) - - if err != nil { - logger.Error("FAILURE", "error", err) - return 0, err - } - - logger.Info("SUCCESS", "balance", bal) - - return bal.Uint64(), nil -} - -func GetNonce(ctx context.Context, address common.Address) (uint64, error) { - node := devnet.CurrentNode(ctx) - - if node == nil { - node = devnet.SelectBlockProducer(ctx) - } - - res, err := node.GetTransactionCount(address, rpc.LatestBlock) - - if err != nil { - return 0, fmt.Errorf("failed to get transaction count for address 0x%x: %v", address, err) - } - - return res.Uint64(), nil -} diff --git a/cmd/devnet/accounts/util.go b/cmd/devnet/accounts/util.go deleted file mode 100644 index 59d0016576d..00000000000 --- a/cmd/devnet/accounts/util.go +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package accounts - -import ( - "math/big" -) - -func EtherAmount(amount float64) *big.Int { - ether, _ := (&big.Float{}).Mul(big.NewFloat(1e18), big.NewFloat(amount)).Int(nil) - return ether -} diff --git a/cmd/devnet/admin/ping.go b/cmd/devnet/admin/ping.go deleted file mode 100644 index 3208d098ce3..00000000000 --- a/cmd/devnet/admin/ping.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package admin - -import ( - "context" - - "github.com/erigontech/erigon/cmd/devnet/devnet" - "github.com/erigontech/erigon/cmd/devnet/scenarios" -) - -func init() { - scenarios.MustRegisterStepHandlers( - scenarios.StepHandler(PingErigonRpc), - ) -} - -func PingErigonRpc(ctx context.Context) error { - err := devnet.SelectNode(ctx).PingErigonRpc().Err - if err != nil { - devnet.Logger(ctx).Error("FAILURE", "error", err) - } - return err -} diff --git a/cmd/devnet/args/args.go b/cmd/devnet/args/args.go deleted file mode 100644 index ea822c48853..00000000000 --- a/cmd/devnet/args/args.go +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package args - -import ( - "fmt" - "reflect" - "strings" - "unicode" - "unicode/utf8" -) - -type Args []string - -func AsArgs(args interface{}) (Args, error) { - - argsValue := reflect.ValueOf(args) - - if argsValue.Kind() == reflect.Ptr { - argsValue = argsValue.Elem() - } - - if argsValue.Kind() != reflect.Struct { - return nil, fmt.Errorf("Args type must be struct or struc pointer, got %T", args) - } - - return gatherArgs(argsValue, func(v reflect.Value, field reflect.StructField) (string, error) { - tag := field.Tag.Get("arg") - - if tag == "-" { - return "", nil - } - - // only process public fields (reflection won't return values of unsafe fields without unsafe operations) - if r, _ := utf8.DecodeRuneInString(field.Name); !(unicode.IsLetter(r) && unicode.IsUpper(r)) { - return "", nil - } - - var key string - var positional bool - - for _, key = range strings.Split(tag, ",") { - if key == "" { - continue - } - - key = strings.TrimLeft(key, " ") - - if pos := strings.Index(key, ":"); pos != -1 { - key = key[:pos] - } - - switch { - case strings.HasPrefix(key, "---"): - return "", fmt.Errorf("%s.%s: too many hyphens", v.Type().Name(), field.Name) - case strings.HasPrefix(key, "--"): - - case strings.HasPrefix(key, "-"): - if len(key) != 2 { - return "", fmt.Errorf("%s.%s: short arguments must be one character only", v.Type().Name(), field.Name) - } - case key == "positional": - key = "" - positional = true - default: - return "", fmt.Errorf("unrecognized tag '%s' on field %s", key, tag) - } - } - - if len(key) == 0 && !positional { - key = "--" + strings.ToLower(field.Name) - } - - var value string - - switch fv := v.FieldByIndex(field.Index); fv.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - if fv.Int() == 0 { - break - } - fallthrough - default: - value = fmt.Sprintf("%v", fv.Interface()) - } - - flagValue, isFlag := field.Tag.Lookup("flag") - - if isFlag { - if value != "true" { - if flagValue == "true" { - value = flagValue - } - } - } - - if len(value) == 0 { - if defaultString, hasDefault := field.Tag.Lookup("default"); hasDefault { - value = defaultString - } - - if len(value) == 0 { - return "", nil - } - } - - if len(key) == 0 { - return value, nil - } - - if isFlag { - if value == "true" { - return key, nil - } - - return "", nil - } - - if len(value) == 0 { - return key, nil - } - - return fmt.Sprintf("%s=%s", key, value), nil - }) -} - -func gatherArgs(v reflect.Value, visit func(v reflect.Value, field reflect.StructField) (string, error)) (args Args, err error) { - for i := 0; i < v.NumField(); i++ { - field := v.Type().Field(i) - - var gathered Args - - fieldType := field.Type - - if fieldType.Kind() == reflect.Ptr { - fieldType.Elem() - } - - if fieldType.Kind() == reflect.Struct { - gathered, err = gatherArgs(v.FieldByIndex(field.Index), visit) - } else { - var value string - - if value, err = visit(v, field); len(value) > 0 { - gathered = Args{value} - } - } - - if err != nil { - return nil, err - } - - args = append(args, gathered...) - } - - return args, nil -} diff --git a/cmd/devnet/args/node_args.go b/cmd/devnet/args/node_args.go deleted file mode 100644 index 48ac8acbe05..00000000000 --- a/cmd/devnet/args/node_args.go +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package args - -import ( - "crypto/ecdsa" - "encoding/hex" - "fmt" - "math/big" - "net" - "path/filepath" - "strconv" - - "github.com/erigontech/erigon-lib/crypto" - "github.com/erigontech/erigon/cmd/devnet/accounts" - "github.com/erigontech/erigon/core" - "github.com/erigontech/erigon/execution/chain/networkname" - chainspec "github.com/erigontech/erigon/execution/chain/spec" - "github.com/erigontech/erigon/p2p/enode" - "github.com/erigontech/erigon/rpc/requests" - - _ "github.com/erigontech/erigon/polygon/chain" // Register Polygon chains -) - -type NodeArgs struct { - requests.RequestGenerator `arg:"-"` - Name string `arg:"-"` - BuildDir string `arg:"positional" default:"./build/bin/devnet" json:"builddir"` - DataDir string `arg:"--datadir" default:"./dev" json:"datadir"` - Chain string `arg:"--chain" default:"dev" json:"chain"` - Port int `arg:"--port" json:"port,omitempty"` - AllowedPorts string `arg:"--p2p.allowed-ports" json:"p2p.allowed-ports,omitempty"` - NAT string `arg:"--nat" default:"none" json:"nat"` - ConsoleVerbosity string `arg:"--log.console.verbosity" default:"0" json:"log.console.verbosity"` - DirVerbosity string `arg:"--log.dir.verbosity" json:"log.dir.verbosity,omitempty"` - LogDirPath string `arg:"--log.dir.path" json:"log.dir.path,omitempty"` - LogDirPrefix string `arg:"--log.dir.prefix" json:"log.dir.prefix,omitempty"` - P2PProtocol string `arg:"--p2p.protocol" default:"68" json:"p2p.protocol"` - Snapshots bool `arg:"--snapshots" flag:"" default:"false" json:"snapshots,omitempty"` - Downloader string `arg:"--no-downloader" default:"true" json:"no-downloader"` - WS string `arg:"--ws" flag:"" default:"true" json:"ws"` - PrivateApiAddr string `arg:"--private.api.addr" default:"localhost:9090" json:"private.api.addr"` - HttpPort int `arg:"--http.port" default:"8545" json:"http.port"` - HttpVHosts string `arg:"--http.vhosts" json:"http.vhosts"` - HttpCorsDomain string `arg:"--http.corsdomain" json:"http.corsdomain"` - AuthRpcPort int `arg:"--authrpc.port" default:"8551" json:"authrpc.port"` - AuthRpcVHosts string `arg:"--authrpc.vhosts" json:"authrpc.vhosts"` - WSPort int `arg:"--ws.port" default:"8546" json:"ws.port"` - GRPCPort int `arg:"-" default:"8547" json:"-"` // flag not defined - TCPPort int `arg:"-" default:"8548" json:"-"` // flag not defined - Metrics bool `arg:"--metrics" flag:"" default:"false" json:"metrics"` - MetricsPort int `arg:"--metrics.port" json:"metrics.port,omitempty"` - MetricsAddr string `arg:"--metrics.addr" json:"metrics.addr,omitempty"` - StaticPeers string `arg:"--staticpeers" json:"staticpeers,omitempty"` - WithoutHeimdall bool `arg:"--bor.withoutheimdall" flag:"" default:"false" json:"bor.withoutheimdall,omitempty"` - HeimdallURL string `arg:"--bor.heimdall" json:"bor.heimdall,omitempty"` - VMDebug bool `arg:"--vmdebug" flag:"" default:"false" json:"dmdebug"` - - NodeKey *ecdsa.PrivateKey `arg:"-"` - NodeKeyHex string `arg:"--nodekeyhex" json:"nodekeyhex,omitempty"` -} - -func (node *NodeArgs) Configure(base NodeArgs, nodeNumber int) error { - if len(node.Name) == 0 { - node.Name = fmt.Sprintf("%s-%d", base.Chain, nodeNumber) - } - - node.DataDir = filepath.Join(base.DataDir, node.Name) - - node.LogDirPath = filepath.Join(base.DataDir, "logs") - node.LogDirPrefix = node.Name - - node.Chain = base.Chain - - node.StaticPeers = base.StaticPeers - - var err error - node.NodeKey, err = crypto.GenerateKey() - if err != nil { - return err - } - node.NodeKeyHex = hex.EncodeToString(crypto.FromECDSA(node.NodeKey)) - - node.Metrics = base.Metrics - node.MetricsPort = base.MetricsPort - node.MetricsAddr = base.MetricsAddr - - node.Snapshots = base.Snapshots - - node.PrivateApiAddr, _, err = portFromBase(base.PrivateApiAddr, nodeNumber, 1) - - if err != nil { - return err - } - - apiPort := base.HttpPort + (nodeNumber * 5) - - node.HttpPort = apiPort - node.WSPort = apiPort + 1 - node.GRPCPort = apiPort + 2 - node.TCPPort = apiPort + 3 - node.AuthRpcPort = apiPort + 4 - - node.Port = base.Port + nodeNumber - - return nil -} - -func (node *NodeArgs) GetName() string { - return node.Name -} - -func (node *NodeArgs) ChainID() *big.Int { - config := chainspec.ChainConfigByChainName(node.Chain) - if config == nil { - return nil - } - return config.ChainID -} - -func (node *NodeArgs) GetHttpPort() int { - return node.HttpPort -} - -func (node *NodeArgs) GetEnodeURL() string { - port := node.Port - return enode.NewV4(&node.NodeKey.PublicKey, net.ParseIP("127.0.0.1"), port, port).URLv4() -} - -func (node *NodeArgs) EnableMetrics(port int) { - node.Metrics = true - node.MetricsPort = port -} - -type BlockProducer struct { - NodeArgs - Mine bool `arg:"--mine" flag:"true"` - Etherbase string `arg:"--miner.etherbase"` - GasLimit int `arg:"--miner.gaslimit"` - DevPeriod int `arg:"--dev.period"` - BorPeriod int `arg:"--bor.period"` - BorMinBlockSize int `arg:"--bor.minblocksize"` - HttpApi string `arg:"--http.api" default:"admin,eth,erigon,web3,net,debug,trace,txpool,parity,ots"` - AccountSlots int `arg:"--txpool.accountslots" default:"16"` - account *accounts.Account -} - -func (m *BlockProducer) Configure(baseNode NodeArgs, nodeNumber int) error { - err := m.NodeArgs.Configure(baseNode, nodeNumber) - if err != nil { - return err - } - - switch m.Chain { - case networkname.Dev: - if m.DevPeriod == 0 { - m.DevPeriod = 30 - } - m.account = accounts.NewAccount(m.GetName() + "-etherbase") - core.DevnetEtherbase = m.account.Address - core.DevnetSignPrivateKey = m.account.SigKey() - - case networkname.BorDevnet: - m.account = accounts.NewAccount(m.GetName() + "-etherbase") - - if len(m.HttpApi) == 0 { - m.HttpApi = "admin,eth,erigon,web3,net,debug,trace,txpool,parity,ots,bor" - } - } - - if m.account != nil { - m.Etherbase = m.account.Address.Hex() - } - - return nil -} - -func (n *BlockProducer) Account() *accounts.Account { - return n.account -} - -func (n *BlockProducer) IsBlockProducer() bool { - return true -} - -type BlockConsumer struct { - NodeArgs - HttpApi string `arg:"--http.api" default:"admin,eth,debug,net,trace,web3,erigon,txpool" json:"http.api"` - TorrentPort string `arg:"--torrent.port" default:"42070" json:"torrent.port"` - NoDiscover string `arg:"--nodiscover" flag:"" default:"true" json:"nodiscover"` -} - -func (n *BlockConsumer) IsBlockProducer() bool { - return false -} - -func (n *BlockConsumer) Account() *accounts.Account { - return nil -} - -func portFromBase(baseAddr string, increment int, portCount int) (string, int, error) { - apiHost, apiPort, err := net.SplitHostPort(baseAddr) - - if err != nil { - return "", -1, err - } - - portNo, err := strconv.Atoi(apiPort) - - if err != nil { - return "", -1, err - } - - portNo += (increment * portCount) - - return fmt.Sprintf("%s:%d", apiHost, portNo), portNo, nil -} diff --git a/cmd/devnet/args/node_args_test.go b/cmd/devnet/args/node_args_test.go deleted file mode 100644 index b2681ac34db..00000000000 --- a/cmd/devnet/args/node_args_test.go +++ /dev/null @@ -1,239 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package args_test - -import ( - "errors" - "fmt" - "path/filepath" - "testing" - - "github.com/erigontech/erigon/cmd/devnet/args" -) - -func TestNodeArgs(t *testing.T) { - asMap := map[string]struct{}{} - - nodeArgs, _ := args.AsArgs(args.BlockProducer{ - NodeArgs: args.NodeArgs{ - DataDir: filepath.Join("data", fmt.Sprintf("%d", 1)), - PrivateApiAddr: "localhost:9092", - }, - DevPeriod: 30, - }) - - for _, arg := range nodeArgs { - asMap[arg] = struct{}{} - } - - for _, arg := range producingNodeArgs("data", 1) { - if _, ok := asMap[arg]; !ok { - t.Fatal(arg, "missing") - } - - delete(asMap, arg) - } - - if len(asMap) > 0 { - t.Fatal(asMap, "not found") - } - - nodeArgs, _ = args.AsArgs(args.BlockConsumer{ - NodeArgs: args.NodeArgs{ - DataDir: filepath.Join("data", fmt.Sprintf("%d", 2)), - StaticPeers: "enode", - PrivateApiAddr: "localhost:9091", - }, - }) - - for _, arg := range nodeArgs { - asMap[arg] = struct{}{} - } - - for _, arg := range nonProducingNodeArgs("data", 2, "enode") { - if _, ok := asMap[arg]; !ok { - t.Fatal(arg, "missing") - } - - delete(asMap, arg) - } - - if len(asMap) > 0 { - t.Fatal(asMap, "not found") - } -} - -func TestParameterFromArgument(t *testing.T) { - enode := fmt.Sprintf("%q", "1234567") - testCases := []struct { - argInput string - paramInput string - expectedRes string - expectedErr error - }{ - {"--datadir", "./dev", "--datadir=./dev", nil}, - {"--chain", "dev", "--chain=dev", nil}, - {"--dev.period", "30", "--dev.period=30", nil}, - {"--staticpeers", enode, "--staticpeers=" + enode, nil}, - {"", "30", "", errInvalidArgument}, - } - - for _, testCase := range testCases { - got, err := parameterFromArgument(testCase.argInput, testCase.paramInput) - if got != testCase.expectedRes { - t.Errorf("expected %s, got %s", testCase.expectedRes, got) - } - if err != testCase.expectedErr { - t.Errorf("expected error: %s, got error: %s", testCase.expectedErr, err) - } - } -} - -// errInvalidArgument for invalid arguments -var errInvalidArgument = errors.New("invalid argument") - -// ParameterFromArgument merges the argument and parameter and returns a flag input string -func parameterFromArgument(arg, param string) (string, error) { - if arg == "" { - return "", errInvalidArgument - } - return fmt.Sprintf("%s=%s", arg, param), nil -} - -const ( - // BuildDirArg is the build directory for the devnet executable - buildDirArg = "./build/bin/devnet" - // DataDirArg is the datadir flag - dataDirArg = "--datadir" - // ChainArg is the chain flag - chainArg = "--chain" - // DevPeriodArg is the dev.period flag - devPeriodArg = "--dev.period" - // ConsoleVerbosityArg is the log.console.verbosity flag - consoleVerbosityArg = "--log.console.verbosity" - // LogDirArg is the log.dir.path flag - logDirArg = "--log.dir.path" - // TorrentPortArg is the --torrent.port flag argument - torrentPortArg = "--torrent.port" - // Mine is the mine flag - mine = "--mine" - // NoDiscover is the nodiscover flag - noDiscover = "--nodiscover" - // PrivateApiAddrArg is the private.api.addr flag - privateApiAddrArg = "--private.api.addr" - // StaticPeersArg is the staticpeers flag - staticPeersArg = "--staticpeers" - // HttpApiArg is the http.api flag - httpApiArg = "--http.api" - // WSArg is the --ws flag for rpcdaemon - wsArg = "--ws" - - // DataDirParam is the datadir parameter - dataDirParam = "./dev" - // ChainParam is the chain parameter - chainParam = "dev" - // DevPeriodParam is the dev.period parameter - devPeriodParam = "30" - // ConsoleVerbosityParam is the verbosity parameter for the console logs - consoleVerbosityParam = "0" - // LogDirParam is the log directory parameter for logging to disk - logDirParam = "./cmd/devnet/debug_logs" - // TorrentPortParam is the port parameter for the second node - torrentPortParam = "42070" - // PrivateApiParamMine is the private.api.addr parameter for the mining node - privateApiParamMine = "localhost:9092" - // PrivateApiParamNoMine is the private.api.addr parameter for the non-mining node - privateApiParamNoMine = "localhost:9091" - // HttpApiParam is the http.api default parameter for rpcdaemon - httpApiParam = "admin,eth,erigon,web3,net,debug,trace,txpool,parity,ots" -) - -// miningNodeArgs returns custom args for starting a mining node -func producingNodeArgs(dataDir string, nodeNumber int) []string { - nodeDataDir := filepath.Join(dataDir, fmt.Sprintf("%d", nodeNumber)) - dataDirArg, _ := parameterFromArgument(dataDirArg, nodeDataDir) - chainType, _ := parameterFromArgument(chainArg, chainParam) - devPeriod, _ := parameterFromArgument(devPeriodArg, devPeriodParam) - privateApiAddr, _ := parameterFromArgument(privateApiAddrArg, privateApiParamMine) - httpApi, _ := parameterFromArgument(httpApiArg, httpApiParam) - ws := wsArg - consoleVerbosity, _ := parameterFromArgument(consoleVerbosityArg, consoleVerbosityParam) - p2pProtocol, _ := parameterFromArgument("--p2p.protocol", "68") - downloaderArg, _ := parameterFromArgument("--no-downloader", "true") - httpPortArg, _ := parameterFromArgument("--http.port", "8545") - wsPortArg, _ := parameterFromArgument("--ws.port", "8546") - authrpcPortArg, _ := parameterFromArgument("--authrpc.port", "8551") - natArg, _ := parameterFromArgument("--nat", "none") - accountSlotsArg, _ := parameterFromArgument("--txpool.accountslots", "16") - - return []string{ - buildDirArg, - dataDirArg, - chainType, - privateApiAddr, - httpPortArg, - wsPortArg, - authrpcPortArg, - mine, - httpApi, - ws, - natArg, - devPeriod, - consoleVerbosity, - p2pProtocol, - downloaderArg, - accountSlotsArg, - } -} - -// nonMiningNodeArgs returns custom args for starting a non-mining node -func nonProducingNodeArgs(dataDir string, nodeNumber int, enode string) []string { - nodeDataDir := filepath.Join(dataDir, fmt.Sprintf("%d", nodeNumber)) - dataDirArg, _ := parameterFromArgument(dataDirArg, nodeDataDir) - chainType, _ := parameterFromArgument(chainArg, chainParam) - privateApiAddr, _ := parameterFromArgument(privateApiAddrArg, privateApiParamNoMine) - staticPeers, _ := parameterFromArgument(staticPeersArg, enode) - consoleVerbosity, _ := parameterFromArgument(consoleVerbosityArg, consoleVerbosityParam) - torrentPort, _ := parameterFromArgument(torrentPortArg, torrentPortParam) - p2pProtocol, _ := parameterFromArgument("--p2p.protocol", "68") - downloaderArg, _ := parameterFromArgument("--no-downloader", "true") - httpPortArg, _ := parameterFromArgument("--http.port", "8545") - wsPortArg, _ := parameterFromArgument("--ws.port", "8546") - httpApi, _ := parameterFromArgument(httpApiArg, "admin,eth,debug,net,trace,web3,erigon,txpool") - authrpcPortArg, _ := parameterFromArgument("--authrpc.port", "8551") - natArg, _ := parameterFromArgument("--nat", "none") - ws := wsArg - - return []string{ - buildDirArg, - dataDirArg, - chainType, - privateApiAddr, - httpPortArg, - wsPortArg, - authrpcPortArg, - httpApi, - ws, - natArg, - staticPeers, - noDiscover, - consoleVerbosity, - torrentPort, - p2pProtocol, - downloaderArg, - } -} diff --git a/cmd/devnet/blocks/checks.go b/cmd/devnet/blocks/checks.go deleted file mode 100644 index ef7ff2b9b4a..00000000000 --- a/cmd/devnet/blocks/checks.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package blocks - -import ( - "context" - "fmt" - - "github.com/erigontech/erigon/cmd/devnet/devnet" - "github.com/erigontech/erigon/rpc/ethapi" - "github.com/erigontech/erigon/rpc/requests" -) - -var CompletionChecker = BlockHandlerFunc( - func(ctx context.Context, node devnet.Node, block *requests.Block, transaction *ethapi.RPCTransaction) error { - traceResults, err := node.TraceTransaction(transaction.Hash) - - if err != nil { - return fmt.Errorf("Failed to trace transaction: %s: %w", transaction.Hash, err) - } - - for _, traceResult := range traceResults { - if traceResult.TransactionHash == transaction.Hash { - if len(traceResult.Error) != 0 { - return fmt.Errorf("Transaction error: %s", traceResult.Error) - } - - break - } - } - - return nil - }) diff --git a/cmd/devnet/blocks/fees.go b/cmd/devnet/blocks/fees.go deleted file mode 100644 index d0cbeb8ca8c..00000000000 --- a/cmd/devnet/blocks/fees.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package blocks - -import ( - "context" - "fmt" - - "github.com/erigontech/erigon/cmd/devnet/devnet" - "github.com/erigontech/erigon/rpc" -) - -func BaseFeeFromBlock(ctx context.Context) (uint64, error) { - res, err := devnet.SelectNode(ctx).GetBlockByNumber(ctx, rpc.LatestBlockNumber, false) - - if err != nil { - return 0, fmt.Errorf("failed to get base fee from block: %v\n", err) - } - - return res.BaseFee.Uint64(), nil -} diff --git a/cmd/devnet/blocks/generator.go b/cmd/devnet/blocks/generator.go deleted file mode 100644 index 129258d4179..00000000000 --- a/cmd/devnet/blocks/generator.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package blocks - -import ( - "context" - "crypto/ecdsa" - "fmt" - "testing" - - "github.com/erigontech/erigon-lib/crypto" - "github.com/erigontech/erigon/core" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/execution/abi/bind/backends" - "github.com/erigontech/erigon/execution/stages/mock" - "github.com/erigontech/erigon/execution/types" -) - -type TxFn func(_ *core.BlockGen, backend bind.ContractBackend) (types.Transaction, bool) - -type TxGen struct { - Fn TxFn - Key *ecdsa.PrivateKey -} - -func GenerateBlocks(t *testing.T, gspec *types.Genesis, blocks int, txs map[int]TxGen, txPerBlock func(int) int) (*mock.MockSentry, *core.ChainPack, error) { - key, _ := crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") - m := mock.MockWithGenesis(t, gspec, key, false) - - contractBackend := backends.NewTestSimulatedBackendWithConfig(t, gspec.Alloc, gspec.Config, gspec.GasLimit) - - chain, err := core.GenerateChain(m.ChainConfig, m.Genesis, m.Engine, m.DB, blocks, func(blockNum int, block *core.BlockGen) { - var txn types.Transaction - var isContractCall bool - signer := types.LatestSignerForChainID(nil) - - txCount := txPerBlock(blockNum) - - for i := 0; i < txCount; i++ { - if txToSend, ok := txs[i%len(txs)]; ok { - txn, isContractCall = txToSend.Fn(block, contractBackend) - var err error - txn, err = types.SignTx(txn, *signer, txToSend.Key) - if err != nil { - return - } - } - - if txn != nil { - if !isContractCall { - err := contractBackend.SendTransaction(context.Background(), txn) - if err != nil { - return - } - } - - block.AddTx(txn) - } - } - - contractBackend.Commit() - }) - if err != nil { - return nil, nil, fmt.Errorf("generate chain: %w", err) - } - return m, chain, err -} diff --git a/cmd/devnet/blocks/waiter.go b/cmd/devnet/blocks/waiter.go deleted file mode 100644 index 8ae102d6c4a..00000000000 --- a/cmd/devnet/blocks/waiter.go +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package blocks - -import ( - "context" - - ethereum "github.com/erigontech/erigon" - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon-lib/log/v3" - "github.com/erigontech/erigon/cmd/devnet/devnet" - "github.com/erigontech/erigon/execution/types" - "github.com/erigontech/erigon/rpc" - "github.com/erigontech/erigon/rpc/ethapi" - "github.com/erigontech/erigon/rpc/requests" -) - -type BlockHandler interface { - Handle(ctx context.Context, node devnet.Node, block *requests.Block, transaction *ethapi.RPCTransaction) error -} - -type BlockHandlerFunc func(ctx context.Context, node devnet.Node, block *requests.Block, transaction *ethapi.RPCTransaction) error - -func (f BlockHandlerFunc) Handle(ctx context.Context, node devnet.Node, block *requests.Block, transaction *ethapi.RPCTransaction) error { - return f(ctx, node, block, transaction) -} - -type BlockMap map[common.Hash]*requests.Block - -type waitResult struct { - err error - blockMap BlockMap -} - -type blockWaiter struct { - result chan waitResult - hashes chan map[common.Hash]struct{} - waitHashes map[common.Hash]struct{} - headersSub ethereum.Subscription - handler BlockHandler - logger log.Logger -} - -type Waiter interface { - Await(common.Hash) (*requests.Block, error) - AwaitMany(...common.Hash) (BlockMap, error) -} - -type waitError struct { - err error -} - -func (w waitError) Await(common.Hash) (*requests.Block, error) { - return nil, w.err -} - -func (w waitError) AwaitMany(...common.Hash) (BlockMap, error) { - return nil, w.err -} - -type wait struct { - waiter *blockWaiter -} - -func (w wait) Await(hash common.Hash) (*requests.Block, error) { - w.waiter.hashes <- map[common.Hash]struct{}{hash: {}} - res := <-w.waiter.result - - if len(res.blockMap) > 0 { - for _, block := range res.blockMap { - return block, res.err - } - } - - return nil, res.err -} - -func (w wait) AwaitMany(hashes ...common.Hash) (BlockMap, error) { - if len(hashes) == 0 { - return nil, nil - } - - hashMap := map[common.Hash]struct{}{} - - for _, hash := range hashes { - hashMap[hash] = struct{}{} - } - - w.waiter.hashes <- hashMap - - res := <-w.waiter.result - return res.blockMap, res.err -} - -func BlockWaiter(ctx context.Context, handler BlockHandler) (Waiter, context.CancelFunc) { - ctx, cancel := context.WithCancel(ctx) - - node := devnet.SelectBlockProducer(ctx) - - waiter := &blockWaiter{ - result: make(chan waitResult, 1), - hashes: make(chan map[common.Hash]struct{}, 1), - handler: handler, - logger: devnet.Logger(ctx), - } - - var err error - - headers := make(chan *types.Header) - waiter.headersSub, err = node.Subscribe(ctx, requests.Methods.ETHNewHeads, headers) - - if err != nil { - defer close(waiter.result) - return waitError{err}, cancel - } - - go waiter.receive(ctx, node, headers) - - return wait{waiter}, cancel -} - -func (c *blockWaiter) receive(ctx context.Context, node devnet.Node, headers chan *types.Header) { - blockMap := map[common.Hash]*requests.Block{} - - defer close(c.result) - - for header := range headers { - - select { - case <-ctx.Done(): - c.headersSub.Unsubscribe() - c.result <- waitResult{blockMap: blockMap, err: ctx.Err()} - return - default: - } - - block, err := node.GetBlockByNumber(ctx, rpc.AsBlockNumber(header.Number), true) - - if err != nil { - c.logger.Error("Block waiter failed to get block", "err", err) - continue - } - - if len(block.Transactions) > 0 && c.waitHashes == nil { - c.waitHashes = <-c.hashes - } - - for i := range block.Transactions { - tx := block.Transactions[i] // avoid implicit memory aliasing - - if _, ok := c.waitHashes[tx.Hash]; ok { - c.logger.Info("Tx included into block", "txHash", tx.Hash, "blockNum", block.Number) - blockMap[tx.Hash] = block - delete(c.waitHashes, tx.Hash) - - if len(c.waitHashes) == 0 { - c.headersSub.Unsubscribe() - res := waitResult{ - err: c.handler.Handle(ctx, node, block, tx), - } - - if res.err == nil { - res.blockMap = blockMap - } - - c.result <- res - return - } - } - } - } -} diff --git a/cmd/devnet/contracts/backend.go b/cmd/devnet/contracts/backend.go deleted file mode 100644 index aac41e47254..00000000000 --- a/cmd/devnet/contracts/backend.go +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package contracts - -import ( - "context" - "fmt" - "math/big" - - ethereum "github.com/erigontech/erigon" - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon-lib/common/hexutil" - "github.com/erigontech/erigon/cmd/devnet/devnet" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/execution/types" - "github.com/erigontech/erigon/rpc" - "github.com/erigontech/erigon/rpc/ethapi" -) - -func NewBackend(node devnet.Node) bind.ContractBackend { - return contractBackend{node} -} - -type contractBackend struct { - node devnet.Node -} - -func (cb contractBackend) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) { - return cb.node.GetCode(contract, rpc.AsBlockReference(blockNumber)) -} - -func (cb contractBackend) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) { - var gasPrice *hexutil.Big - var value *hexutil.Big - - if call.Value != nil { - value = (*hexutil.Big)(call.Value.ToBig()) - } - - if call.GasPrice != nil { - gasPrice = (*hexutil.Big)(call.GasPrice.ToBig()) - } - - var blockRef rpc.BlockReference - if blockNumber != nil { - blockRef = rpc.AsBlockReference(blockNumber) - } else { - blockRef = rpc.LatestBlock - } - - return cb.node.Call(ethapi.CallArgs{ - From: &call.From, - To: call.To, - Gas: (*hexutil.Uint64)(&call.Gas), - GasPrice: gasPrice, - Value: value, - Data: (*hexutil.Bytes)(&call.Data), - }, blockRef, nil) -} - -func (cb contractBackend) PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) { - return cb.node.GetCode(account, rpc.PendingBlock) -} - -func (cb contractBackend) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) { - res, err := cb.node.GetTransactionCount(account, rpc.PendingBlock) - - if err != nil { - return 0, fmt.Errorf("failed to get transaction count for address 0x%x: %v", account, err) - } - - return res.Uint64(), nil -} - -func (cb contractBackend) SuggestGasPrice(ctx context.Context) (*big.Int, error) { - return cb.node.GasPrice() -} - -func (cb contractBackend) EstimateGas(ctx context.Context, call ethereum.CallMsg) (gas uint64, err error) { - return 1_000_000, nil - //return cb.node.EstimateGas(call, requests.BlockNumbers.Pending) -} - -func (cb contractBackend) SendTransaction(ctx context.Context, txn types.Transaction) error { - _, err := cb.node.SendTransaction(txn) - return err -} - -func (cb contractBackend) FilterLogs(ctx context.Context, query ethereum.FilterQuery) ([]types.Log, error) { - return cb.node.FilterLogs(ctx, query) -} - -func (cb contractBackend) SubscribeFilterLogs(ctx context.Context, query ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) { - return cb.node.SubscribeFilterLogs(ctx, query, ch) -} diff --git a/cmd/devnet/contracts/build/ChainIdMixin.abi b/cmd/devnet/contracts/build/ChainIdMixin.abi deleted file mode 100644 index 0679dc7f982..00000000000 --- a/cmd/devnet/contracts/build/ChainIdMixin.abi +++ /dev/null @@ -1 +0,0 @@ -[{"inputs":[],"name":"CHAINID","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"networkId","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"view","type":"function"}] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/ChainIdMixin.bin b/cmd/devnet/contracts/build/ChainIdMixin.bin deleted file mode 100644 index a42f094958c..00000000000 --- a/cmd/devnet/contracts/build/ChainIdMixin.bin +++ /dev/null @@ -1 +0,0 @@ -608060405234801561001057600080fd5b50610102806100206000396000f3fe6080604052348015600f57600080fd5b506004361060325760003560e01c80639025e64c146037578063cc79f97b14606b575b600080fd5b605760405180604001604052806002815260200161053960f01b81525081565b604051606291906080565b60405180910390f35b607361053981565b6040519081526020016062565b600060208083528351808285015260005b8181101560ab578581018301518582016040015282016091565b506000604082860101526040601f19601f830116850101925050509291505056fea2646970667358221220e6870cdfde407f0cde56918e0f6a3b3176e22f8f29210f65969323fb68f9a05b64736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/build/ChildReceiver.abi b/cmd/devnet/contracts/build/ChildReceiver.abi deleted file mode 100644 index 3e0fe97799f..00000000000 --- a/cmd/devnet/contracts/build/ChildReceiver.abi +++ /dev/null @@ -1 +0,0 @@ -[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_source","type":"address"},{"indexed":false,"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"received","type":"event"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"onStateReceive","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"senders","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/ChildReceiver.bin b/cmd/devnet/contracts/build/ChildReceiver.bin deleted file mode 100644 index bceb639d57c..00000000000 --- a/cmd/devnet/contracts/build/ChildReceiver.bin +++ /dev/null @@ -1 +0,0 @@ -608060405234801561001057600080fd5b5061029c806100206000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c806326c53bea1461003b578063982fb9d814610050575b600080fd5b61004e61004936600461015b565b610082565b005b61007061005e3660046101ef565b60006020819052908152604090205481565b60405190815260200160405180910390f35b33611001146100c85760405162461bcd60e51b815260206004820152600e60248201526d24b73b30b634b21039b2b73232b960911b604482015260640160405180910390fd5b6000806100d783850185610213565b6001600160a01b03821660009081526020819052604090205491935091506100ff828261023f565b6001600160a01b038416600081815260208181526040918290209390935580519182529181018490527ff11e547d796cc64acdf758e7cee90439494fd886a19159454aa61e473fdbafef910160405180910390a1505050505050565b60008060006040848603121561017057600080fd5b83359250602084013567ffffffffffffffff8082111561018f57600080fd5b818601915086601f8301126101a357600080fd5b8135818111156101b257600080fd5b8760208285010111156101c457600080fd5b6020830194508093505050509250925092565b6001600160a01b03811681146101ec57600080fd5b50565b60006020828403121561020157600080fd5b813561020c816101d7565b9392505050565b6000806040838503121561022657600080fd5b8235610231816101d7565b946020939093013593505050565b8082018082111561026057634e487b7160e01b600052601160045260246000fd5b9291505056fea2646970667358221220bb3a513950ddc3581a83b932be35476871cfca25f2faf93bb137e0f50d8c5ad864736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/build/ChildSender.abi b/cmd/devnet/contracts/build/ChildSender.abi deleted file mode 100644 index c0fb931d95a..00000000000 --- a/cmd/devnet/contracts/build/ChildSender.abi +++ /dev/null @@ -1 +0,0 @@ -[{"inputs":[{"internalType":"address","name":"childStateReceiver_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes","name":"message","type":"bytes"}],"name":"MessageSent","type":"event"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"sendToRoot","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"sent","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/ChildSender.bin b/cmd/devnet/contracts/build/ChildSender.bin deleted file mode 100644 index d0b73572077..00000000000 --- a/cmd/devnet/contracts/build/ChildSender.bin +++ /dev/null @@ -1 +0,0 @@ -608060405234801561001057600080fd5b506040516102b33803806102b383398101604081905261002f91610054565b600080546001600160a01b0319166001600160a01b0392909216919091179055610084565b60006020828403121561006657600080fd5b81516001600160a01b038116811461007d57600080fd5b9392505050565b610220806100936000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c80637bf786f81461003b5780638152e5021461006d575b600080fd5b61005b61004936600461012c565b60016020526000908152604090205481565b60405190815260200160405180910390f35b61008061007b36600461015c565b610082565b005b3360009081526001602052604090205461009c8282610175565b33600081815260016020908152604080832094909455905483516001600160a01b039091169181019190915291820152606081018390526100ee906080016040516020818303038152906040526100f2565b5050565b7f8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b03681604051610121919061019c565b60405180910390a150565b60006020828403121561013e57600080fd5b81356001600160a01b038116811461015557600080fd5b9392505050565b60006020828403121561016e57600080fd5b5035919050565b8082018082111561019657634e487b7160e01b600052601160045260246000fd5b92915050565b600060208083528351808285015260005b818110156101c9578581018301518582016040015282016101ad565b506000604082860101526040601f19601f830116850101925050509291505056fea26469706673582212202b5e4ad44349bb7aa70272a65afd939d928b9e646835ef4b7e65acff3d07b21364736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/build/ExitPayloadReader.abi b/cmd/devnet/contracts/build/ExitPayloadReader.abi deleted file mode 100644 index 0637a088a01..00000000000 --- a/cmd/devnet/contracts/build/ExitPayloadReader.abi +++ /dev/null @@ -1 +0,0 @@ -[] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/ExitPayloadReader.bin b/cmd/devnet/contracts/build/ExitPayloadReader.bin deleted file mode 100644 index 0e7370cd4ad..00000000000 --- a/cmd/devnet/contracts/build/ExitPayloadReader.bin +++ /dev/null @@ -1 +0,0 @@ -60566037600b82828239805160001a607314602a57634e487b7160e01b600052600060045260246000fd5b30600052607381538281f3fe73000000000000000000000000000000000000000030146080604052600080fdfea2646970667358221220bd0c6a06e3532455fce52c3e139cac58317944b0cd3296a2f68dc6791cc2b16c64736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/build/Governable.abi b/cmd/devnet/contracts/build/Governable.abi deleted file mode 100644 index 5be7d7d5b1b..00000000000 --- a/cmd/devnet/contracts/build/Governable.abi +++ /dev/null @@ -1 +0,0 @@ -[{"inputs":[{"internalType":"address","name":"_governance","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"governance","outputs":[{"internalType":"contract IGovernance","name":"","type":"address"}],"stateMutability":"view","type":"function"}] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/Governable.bin b/cmd/devnet/contracts/build/Governable.bin deleted file mode 100644 index a57aa5e0966..00000000000 --- a/cmd/devnet/contracts/build/Governable.bin +++ /dev/null @@ -1 +0,0 @@ -608060405234801561001057600080fd5b5060405161012338038061012383398101604081905261002f91610054565b600080546001600160a01b0319166001600160a01b0392909216919091179055610084565b60006020828403121561006657600080fd5b81516001600160a01b038116811461007d57600080fd5b9392505050565b6091806100926000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c80635aa6e67514602d575b600080fd5b600054603f906001600160a01b031681565b6040516001600160a01b03909116815260200160405180910390f3fea26469706673582212205573b7ff38baa0f309eb23dd31fd1b16c4f5bf2da9f9ffe920ee2553aab47bf664736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/build/ICheckpointManager.abi b/cmd/devnet/contracts/build/ICheckpointManager.abi deleted file mode 100644 index 67ba5980f82..00000000000 --- a/cmd/devnet/contracts/build/ICheckpointManager.abi +++ /dev/null @@ -1 +0,0 @@ -[{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"headerBlocks","outputs":[{"internalType":"bytes32","name":"root","type":"bytes32"},{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"end","type":"uint256"},{"internalType":"uint256","name":"createdAt","type":"uint256"},{"internalType":"address","name":"proposer","type":"address"}],"stateMutability":"view","type":"function"}] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/ICheckpointManager.bin b/cmd/devnet/contracts/build/ICheckpointManager.bin deleted file mode 100644 index 8597a1990b2..00000000000 --- a/cmd/devnet/contracts/build/ICheckpointManager.bin +++ /dev/null @@ -1 +0,0 @@ -608060405234801561001057600080fd5b5060f38061001f6000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c806341539d4a14602d575b600080fd5b6070603836600460a5565b60006020819052908152604090208054600182015460028301546003840154600490940154929391929091906001600160a01b031685565b6040805195865260208601949094529284019190915260608301526001600160a01b0316608082015260a00160405180910390f35b60006020828403121560b657600080fd5b503591905056fea26469706673582212206d025d9e83266d3f4dc870d2f3be47196b093117ab5e4367f14e44e42c9b146564736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/build/IGovernance.abi b/cmd/devnet/contracts/build/IGovernance.abi deleted file mode 100644 index 8221cabdf28..00000000000 --- a/cmd/devnet/contracts/build/IGovernance.abi +++ /dev/null @@ -1 +0,0 @@ -[{"inputs":[{"internalType":"address","name":"target","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"update","outputs":[],"stateMutability":"nonpayable","type":"function"}] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/IGovernance.bin b/cmd/devnet/contracts/build/IGovernance.bin deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/cmd/devnet/contracts/build/IRootChain.abi b/cmd/devnet/contracts/build/IRootChain.abi deleted file mode 100644 index e100705743c..00000000000 --- a/cmd/devnet/contracts/build/IRootChain.abi +++ /dev/null @@ -1 +0,0 @@ -[{"inputs":[],"name":"currentHeaderBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLastChildBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"slash","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"uint256[3][]","name":"sigs","type":"uint256[3][]"}],"name":"submitCheckpoint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"bytes","name":"sigs","type":"bytes"}],"name":"submitHeaderBlock","outputs":[],"stateMutability":"nonpayable","type":"function"}] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/IRootChain.bin b/cmd/devnet/contracts/build/IRootChain.bin deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/cmd/devnet/contracts/build/IStateReceiver.abi b/cmd/devnet/contracts/build/IStateReceiver.abi deleted file mode 100644 index b141799a3b3..00000000000 --- a/cmd/devnet/contracts/build/IStateReceiver.abi +++ /dev/null @@ -1 +0,0 @@ -[{"inputs":[{"internalType":"uint256","name":"stateId","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"onStateReceive","outputs":[],"stateMutability":"nonpayable","type":"function"}] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/IStateReceiver.bin b/cmd/devnet/contracts/build/IStateReceiver.bin deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/cmd/devnet/contracts/build/Merkle.abi b/cmd/devnet/contracts/build/Merkle.abi deleted file mode 100644 index 0637a088a01..00000000000 --- a/cmd/devnet/contracts/build/Merkle.abi +++ /dev/null @@ -1 +0,0 @@ -[] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/Merkle.bin b/cmd/devnet/contracts/build/Merkle.bin deleted file mode 100644 index df2eab89501..00000000000 --- a/cmd/devnet/contracts/build/Merkle.bin +++ /dev/null @@ -1 +0,0 @@ -60566037600b82828239805160001a607314602a57634e487b7160e01b600052600060045260246000fd5b30600052607381538281f3fe73000000000000000000000000000000000000000030146080604052600080fdfea26469706673582212207739c5fda7060eb97027fb86aa71b29b91315b4cad140f6db0f65d635eb1338764736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/build/MerklePatriciaProof.abi b/cmd/devnet/contracts/build/MerklePatriciaProof.abi deleted file mode 100644 index 0637a088a01..00000000000 --- a/cmd/devnet/contracts/build/MerklePatriciaProof.abi +++ /dev/null @@ -1 +0,0 @@ -[] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/MerklePatriciaProof.bin b/cmd/devnet/contracts/build/MerklePatriciaProof.bin deleted file mode 100644 index 613cb8ffd67..00000000000 --- a/cmd/devnet/contracts/build/MerklePatriciaProof.bin +++ /dev/null @@ -1 +0,0 @@ -60566037600b82828239805160001a607314602a57634e487b7160e01b600052600060045260246000fd5b30600052607381538281f3fe73000000000000000000000000000000000000000030146080604052600080fdfea2646970667358221220412fe39cabba782d636d2bc17109d343bfc3f003512a1188914f2742f22e22b364736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/build/ProxyStorage.abi b/cmd/devnet/contracts/build/ProxyStorage.abi deleted file mode 100644 index 0637a088a01..00000000000 --- a/cmd/devnet/contracts/build/ProxyStorage.abi +++ /dev/null @@ -1 +0,0 @@ -[] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/ProxyStorage.bin b/cmd/devnet/contracts/build/ProxyStorage.bin deleted file mode 100644 index 108862e1f4d..00000000000 --- a/cmd/devnet/contracts/build/ProxyStorage.bin +++ /dev/null @@ -1 +0,0 @@ -6080604052348015600f57600080fd5b50603f80601d6000396000f3fe6080604052600080fdfea2646970667358221220f19fe3ff1b547e638b245a1dfab869004f680ce7af6744181151cfa632254b1564736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/build/RLPReader.abi b/cmd/devnet/contracts/build/RLPReader.abi deleted file mode 100644 index 0637a088a01..00000000000 --- a/cmd/devnet/contracts/build/RLPReader.abi +++ /dev/null @@ -1 +0,0 @@ -[] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/RLPReader.bin b/cmd/devnet/contracts/build/RLPReader.bin deleted file mode 100644 index fe1e4b7272d..00000000000 --- a/cmd/devnet/contracts/build/RLPReader.bin +++ /dev/null @@ -1 +0,0 @@ -60566037600b82828239805160001a607314602a57634e487b7160e01b600052600060045260246000fd5b30600052607381538281f3fe73000000000000000000000000000000000000000030146080604052600080fdfea264697066735822122052e9a349bc8a4fd9c5d36d064e612b59e39ba032ed6620df6cc57822b5d7171164736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/build/Registry.abi b/cmd/devnet/contracts/build/Registry.abi deleted file mode 100644 index f44f3952dab..00000000000 --- a/cmd/devnet/contracts/build/Registry.abi +++ /dev/null @@ -1 +0,0 @@ -[{"inputs":[{"internalType":"address","name":"_governance","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"key","type":"bytes32"},{"indexed":true,"internalType":"address","name":"previousContract","type":"address"},{"indexed":true,"internalType":"address","name":"newContract","type":"address"}],"name":"ContractMapUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"predicate","type":"address"},{"indexed":true,"internalType":"address","name":"from","type":"address"}],"name":"PredicateAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"predicate","type":"address"},{"indexed":true,"internalType":"address","name":"from","type":"address"}],"name":"PredicateRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"validator","type":"address"},{"indexed":true,"internalType":"address","name":"from","type":"address"}],"name":"ProofValidatorAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"validator","type":"address"},{"indexed":true,"internalType":"address","name":"from","type":"address"}],"name":"ProofValidatorRemoved","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"rootToken","type":"address"},{"indexed":true,"internalType":"address","name":"childToken","type":"address"}],"name":"TokenMapped","type":"event"},{"inputs":[{"internalType":"address","name":"predicate","type":"address"}],"name":"addErc20Predicate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"predicate","type":"address"}],"name":"addErc721Predicate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"predicate","type":"address"},{"internalType":"enum Registry.Type","name":"_type","type":"uint8"}],"name":"addPredicate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"childToRootToken","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"contractMap","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"erc20Predicate","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"erc721Predicate","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getChildChainAndStateSender","outputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getDepositManagerAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getSlashingManagerAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getStakeManagerAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getValidatorShareAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getWethTokenAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getWithdrawManagerAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"governance","outputs":[{"internalType":"contract IGovernance","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"childToken","type":"address"}],"name":"isChildTokenErc721","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"isERC721","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"isTokenMapped","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"isTokenMappedAndGetPredicate","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_token","type":"address"}],"name":"isTokenMappedAndIsErc721","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_rootToken","type":"address"},{"internalType":"address","name":"_childToken","type":"address"},{"internalType":"bool","name":"_isERC721","type":"bool"}],"name":"mapToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"predicates","outputs":[{"internalType":"enum Registry.Type","name":"_type","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"proofValidatorContracts","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"predicate","type":"address"}],"name":"removePredicate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"rootToChildToken","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"_key","type":"bytes32"},{"internalType":"address","name":"_address","type":"address"}],"name":"updateContractMap","outputs":[],"stateMutability":"nonpayable","type":"function"}] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/Registry.bin b/cmd/devnet/contracts/build/Registry.bin deleted file mode 100644 index a051310fa6e..00000000000 --- a/cmd/devnet/contracts/build/Registry.bin +++ /dev/null @@ -1 +0,0 @@ -608060405234801561001057600080fd5b50604051610e17380380610e1783398101604081905261002f91610054565b600080546001600160a01b0319166001600160a01b0392909216919091179055610084565b60006020828403121561006657600080fd5b81516001600160a01b038116811461007d57600080fd5b9392505050565b610d84806100936000396000f3fe608060405234801561001057600080fd5b506004361061018e5760003560e01c80636e86b770116100de578063c881560f11610097578063d580b41811610071578063d580b418146105b0578063daa09e5414610609578063e117694b1461062c578063ea60c7c41461063f57600080fd5b8063c881560f14610561578063cac39a0514610574578063ce2611861461059d57600080fd5b80636e86b7701461043d5780638b9c948914610466578063930df82e146104bf578063b686497614610518578063bbfe7cd31461052b578063c4b875d31461053e57600080fd5b80632d4e1dc71161014b5780635aa6e675116101255780635aa6e67514610358578063627942da1461036b5780636416c1831461037e578063648b8178146103ac57600080fd5b80632d4e1dc71461030257806337b1d585146103155780633af395e51461034557600080fd5b806301f07db51461019357806305f20595146101bb5780630c9effd0146101d05780631c9486ef1461023d5780632026cfdc14610296578063287be3e4146102a9575b600080fd5b6101a66101a1366004610c22565b610668565b60405190151581526020015b60405180910390f35b6101ce6101c9366004610c22565b6106e8565b005b7f396a39c7e290685f408e5373e677285002a403b06145527a7a84a38a30d9ef1060005260036020527fd600d169c07fd47997cb07cc95ab0ac285b9f541f65f50c3956e76fb037128e4546001600160a01b03165b6040516001600160a01b0390911681526020016101b2565b7ff32233bced9bbd82f0754425f51b5ffaf897dacec3c8ac3384a66e38ea701ec860005260036020527f2c73d66689d1be6372940b8899dbabec50bc3330f12d75d9fc6019218a930993546001600160a01b0316610225565b6101ce6102a4366004610c44565b6107b5565b7f56e86af72b94d3aa725a2e35243d6acbf3dc1ada7212033defd5140c5fcb6a9d60005260036020527f239c91ef4f470b7eb660973e3444cb6cdcc8c384fbcc19cf4b3d1698f5c0fa6e546001600160a01b0316610225565b6101ce610310366004610c22565b610832565b610338610323366004610c22565b60086020526000908152604090205460ff1681565b6040516101b29190610c86565b6101ce610353366004610cae565b6108c7565b600054610225906001600160a01b031681565b610225610379366004610c22565b6109bd565b6101a661038c366004610c22565b6001600160a01b0390811660009081526004602052604090205416151590565b600360209081527f2dff30286899e5fc9aa64cfe1341ad29e9a16800a4191daec50e82fc1b6875ca547fa6604f6f9e958c3372fa784685d6216654aef3be0a2255a92dfbab50f7d0b8546000527f0672ac9c59252897b175d7a0a887cab7e9f75ad2b91a0c45d23da560c8a3c9a054604080516001600160a01b0393841681529290911692820192909252016101b2565b61022561044b366004610c22565b6005602052600090815260409020546001600160a01b031681565b7f9fa53c3a84542bc4f793667c49cfa1cbb5e8df2ae0612ada001973a5f448154b60005260036020527f89ad1c8eaa942d5b27028437c407c5982b47bd810a15834238f23ac6ed250edd546001600160a01b0316610225565b7f261885af88107524c32b47256ca1d87cafbd893a7e8cc972ae41fdfb0270335e60005260036020527f2f04f48dbb401768947a64fe05ee6ccaac2d5a350d2beacfdf4d30893026edcb546001600160a01b0316610225565b600154610225906001600160a01b031681565b6101a6610539366004610c22565b6109ef565b6101a661054c366004610c22565b60066020526000908152604090205460ff1681565b600254610225906001600160a01b031681565b610225610582366004610ce9565b6003602052600090815260409020546001600160a01b031681565b6101ce6105ab366004610c22565b610a7a565b7f1ca32e38cf142cb762bc7468b9a3eac49626b43585fcbd6d3b807227216286c260005260036020527f5f5d97228f36044d803d42ad8e4b63042a170d1d6f8a046f7c944b93cc6dbd81546001600160a01b0316610225565b6101a6610617366004610c22565b60076020526000908152604090205460ff1681565b6101ce61063a366004610d02565b610aa8565b61022561064d366004610c22565b6004602052600090815260409020546001600160a01b031681565b6001600160a01b038082166000908152600460205260408120549091166106c95760405162461bcd60e51b815260206004820152601060248201526f1513d2d15397d393d517d3505414115160821b60448201526064015b60405180910390fd5b506001600160a01b031660009081526007602052604090205460ff1690565b6106f0610b9b565b6001600160a01b03811660009081526008602052604081205460ff16600381111561071d5761071d610c70565b0361076a5760405162461bcd60e51b815260206004820152601860248201527f50726564696361746520646f6573206e6f74206578697374000000000000000060448201526064016106c0565b6001600160a01b038116600081815260086020526040808220805460ff19169055513392917fd8b3c0235cefc5e19393dedb56c1ece6b41447ef932d7c6b34eb150a4b5d5f4991a350565b6107bd610b9b565b6000828152600360205260408082205490516001600160a01b038085169392169185917fffb8cfd9cecbede837eec100fb8e17560ea22bf018e065366ee5e2ff5e0bd10c9190a460009182526003602052604090912080546001600160a01b0319166001600160a01b03909216919091179055565b61083a610b9b565b6001600160a01b03811661089e5760405162461bcd60e51b815260206004820152602560248201527f43616e206e6f7420616464206e756c6c20616464726573732061732070726564604482015264696361746560d81b60648201526084016106c0565b600180546001600160a01b0319166001600160a01b0383161781556108c49082906108c7565b50565b6108cf610b9b565b6001600160a01b03821660009081526008602052604081205460ff1660038111156108fc576108fc610c70565b146109495760405162461bcd60e51b815260206004820152601760248201527f50726564696361746520616c726561647920616464656400000000000000000060448201526064016106c0565b6001600160a01b0382166000908152600860205260409020805482919060ff1916600183600381111561097e5761097e610c70565b021790555060405133906001600160a01b038416907f0ea727f9bef04eb9a0e0da4d8fbb5b5319ddac03834baded53f84e0dcdddfedf90600090a35050565b60006109c882610668565b156109de5750506002546001600160a01b031690565b50506001546001600160a01b031690565b6001600160a01b0380821660009081526005602052604081205490911680610a595760405162461bcd60e51b815260206004820152601960248201527f4368696c6420746f6b656e206973206e6f74206d61707065640000000000000060448201526064016106c0565b6001600160a01b031660009081526007602052604090205460ff1692915050565b610a82610b9b565b600280546001600160a01b0319166001600160a01b0383161781556108c49082906108c7565b610ab0610b9b565b6001600160a01b03831615801590610ad057506001600160a01b03821615155b610b145760405162461bcd60e51b8152602060048201526015602482015274494e56414c49445f544f4b454e5f4144445245535360581b60448201526064016106c0565b6001600160a01b03838116600081815260046020908152604080832080546001600160a01b0319908116968916968717909155858452600583528184208054909116851790558383526007909152808220805460ff1916861515179055517f85920d35e6c72f6b2affffa04298b0cecfeba86e4a9f407df661f1cb8ab5e6179190a3505050565b6000546001600160a01b03163314610c045760405162461bcd60e51b815260206004820152602660248201527f4f6e6c7920676f7665726e616e636520636f6e747261637420697320617574686044820152651bdc9a5e995960d21b60648201526084016106c0565b565b80356001600160a01b0381168114610c1d57600080fd5b919050565b600060208284031215610c3457600080fd5b610c3d82610c06565b9392505050565b60008060408385031215610c5757600080fd5b82359150610c6760208401610c06565b90509250929050565b634e487b7160e01b600052602160045260246000fd5b6020810160048310610ca857634e487b7160e01b600052602160045260246000fd5b91905290565b60008060408385031215610cc157600080fd5b610cca83610c06565b9150602083013560048110610cde57600080fd5b809150509250929050565b600060208284031215610cfb57600080fd5b5035919050565b600080600060608486031215610d1757600080fd5b610d2084610c06565b9250610d2e60208501610c06565b915060408401358015158114610d4357600080fd5b80915050925092509256fea26469706673582212209592b53634fe553b451696a4b71664cb9e1d3952c10f1c50ab3bb728dac3c4a364736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/build/RootChain.abi b/cmd/devnet/contracts/build/RootChain.abi deleted file mode 100644 index 8a0765be67a..00000000000 --- a/cmd/devnet/contracts/build/RootChain.abi +++ /dev/null @@ -1 +0,0 @@ -[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"proposer","type":"address"},{"indexed":true,"internalType":"uint256","name":"headerBlockId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"reward","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"start","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"end","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"root","type":"bytes32"}],"name":"NewHeaderBlock","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"proposer","type":"address"},{"indexed":true,"internalType":"uint256","name":"headerBlockId","type":"uint256"}],"name":"ResetHeaderBlock","type":"event"},{"inputs":[],"name":"CHAINID","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"VOTE_TYPE","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_nextHeaderBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"currentHeaderBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLastChildBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"headerBlocks","outputs":[{"internalType":"bytes32","name":"root","type":"bytes32"},{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"end","type":"uint256"},{"internalType":"uint256","name":"createdAt","type":"uint256"},{"internalType":"address","name":"proposer","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"heimdallId","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"networkId","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_heimdallId","type":"string"}],"name":"setHeimdallId","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"setNextHeaderBlock","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"slash","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"uint256[3][]","name":"","type":"uint256[3][]"}],"name":"submitCheckpoint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"","type":"bytes"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"submitHeaderBlock","outputs":[],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"numDeposits","type":"uint256"}],"name":"updateDepositId","outputs":[{"internalType":"uint256","name":"depositId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/RootChain.bin b/cmd/devnet/contracts/build/RootChain.bin deleted file mode 100644 index e9039019449..00000000000 --- a/cmd/devnet/contracts/build/RootChain.bin +++ /dev/null @@ -1 +0,0 @@ -6080604052612710600255600160035534801561001b57600080fd5b50610aa48061002b6000396000f3fe608060405234801561001057600080fd5b50600436106100ea5760003560e01c8063b87e1b661161008c578063d5b844eb11610066578063d5b844eb14610207578063ea0688b314610221578063ec7e485514610234578063fbc3dd361461023c57600080fd5b8063b87e1b66146101e3578063cc79f97b146101eb578063cf24a0ea146101f457600080fd5b80635391f483116100c85780635391f483146101815780636a791f11146101a25780638d978d88146101b05780639025e64c146101b957600080fd5b80632da25de3146100ef57806341539d4a146100f15780634e43e4951461016e575b600080fd5b005b6101386100ff3660046106e0565b6004602081905260009182526040909120805460018201546002830154600384015493909401549193909290916001600160a01b031685565b6040805195865260208601949094529284019190915260608301526001600160a01b0316608082015260a0015b60405180910390f35b6100ef61017c366004610742565b610245565b61019461018f3660046106e0565b610375565b604051908152602001610165565b6100ef6100ea3660046107dc565b61019460025481565b6101d6604051806040016040528060028152602001600081525081565b604051610165919061086c565b6101946104c0565b6101946104d281565b6100ef6102023660046106e0565b6104e5565b61020f600281565b60405160ff9091168152602001610165565b6100ef61022f3660046108b5565b6105c0565b6101946105ef565b61019460015481565b600080808080610257888a018a61097e565b9550509450945094509450806104d2146102af5760405162461bcd60e51b8152602060048201526014602482015273125b9d985b1a5908189bdc8818da185a5b881a5960621b60448201526064015b60405180910390fd5b6102bb85858585610607565b6102ff5760405162461bcd60e51b8152602060048201526015602482015274494e434f52524543545f4845414445525f4441544160581b60448201526064016102a6565b6002546040805186815260208101869052908101849052600091906001600160a01b038816907fba5de06d22af2685c6c7765f60067f7d2b08c2d29f53cdf14d67f6d1c9bfb5279060600160405180910390a460025461036290612710906109e0565b6002555050600160035550505050505050565b6005546040805162c9effd60e41b815290516000926001600160a01b031691630c9effd09160048083019260209291908290030181865afa1580156103be573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103e291906109f9565b6001600160a01b0316336001600160a01b03161461044c5760405162461bcd60e51b815260206004820152602160248201527f554e415554484f52495a45445f4445504f5349545f4d414e414745525f4f4e4c6044820152605960f81b60648201526084016102a6565b6003546104576105ef565b61046191906109e0565b90508160035461047191906109e0565b600381905561271010156104bb5760405162461bcd60e51b8152602060048201526011602482015270544f4f5f4d414e595f4445504f5349545360781b60448201526064016102a6565b919050565b6000600460006104ce6105ef565b815260200190815260200160002060020154905090565b6104f161271082610a1d565b1561052e5760405162461bcd60e51b815260206004820152600d60248201526c496e76616c69642076616c756560981b60448201526064016102a6565b805b6002548110156105855760008181526004602081905260408220828155600181018390556002810183905560038101929092550180546001600160a01b031916905561057e612710826109e0565b9050610530565b5060028190556001600355604051819033907fca1d8316287f938830e225956a7bb10fd5a1a1506dd2eb3a476751a48811720590600090a350565b806040516020016105d19190610a3f565b60408051601f19818403018152919052805160209091012060015550565b6002546000906106029061271090610a5b565b905090565b60008061271061ffff16600254111561064757600460006106266105ef565b815260200190815260200160002060020154600161064491906109e0565b90505b8481146106585760009150506106d8565b6040805160a081018252848152602080820193845281830187815242606084019081526001600160a01b038b811660808601908152600280546000908152600496879052979097209551865596516001808701919091559251958501959095555160038401559351910180546001600160a01b0319169190921617905590505b949350505050565b6000602082840312156106f257600080fd5b5035919050565b60008083601f84011261070b57600080fd5b50813567ffffffffffffffff81111561072357600080fd5b60208301915083602082850101111561073b57600080fd5b9250929050565b6000806000806040858703121561075857600080fd5b843567ffffffffffffffff8082111561077057600080fd5b61077c888389016106f9565b9096509450602087013591508082111561079557600080fd5b818701915087601f8301126107a957600080fd5b8135818111156107b857600080fd5b8860206060830285010111156107cd57600080fd5b95989497505060200194505050565b600080600080604085870312156107f257600080fd5b843567ffffffffffffffff8082111561080a57600080fd5b610816888389016106f9565b9096509450602087013591508082111561082f57600080fd5b5061083c878288016106f9565b95989497509550505050565b60005b8381101561086357818101518382015260200161084b565b50506000910152565b602081526000825180602084015261088b816040850160208701610848565b601f01601f19169190910160400192915050565b634e487b7160e01b600052604160045260246000fd5b6000602082840312156108c757600080fd5b813567ffffffffffffffff808211156108df57600080fd5b818401915084601f8301126108f357600080fd5b8135818111156109055761090561089f565b604051601f8201601f19908116603f0116810190838211818310171561092d5761092d61089f565b8160405282815287602084870101111561094657600080fd5b826020860160208301376000928101602001929092525095945050505050565b6001600160a01b038116811461097b57600080fd5b50565b60008060008060008060c0878903121561099757600080fd5b86356109a281610966565b9860208801359850604088013597606081013597506080810135965060a00135945092505050565b634e487b7160e01b600052601160045260246000fd5b808201808211156109f3576109f36109ca565b92915050565b600060208284031215610a0b57600080fd5b8151610a1681610966565b9392505050565b600082610a3a57634e487b7160e01b600052601260045260246000fd5b500690565b60008251610a51818460208701610848565b9190910192915050565b818103818111156109f3576109f36109ca56fea2646970667358221220b0082d800e411bf71e97a7dba6c22d98a3bd14f4c8522096b1dfdc5b76803ccf64736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/build/RootChainHeader.abi b/cmd/devnet/contracts/build/RootChainHeader.abi deleted file mode 100644 index bc0b2ec7754..00000000000 --- a/cmd/devnet/contracts/build/RootChainHeader.abi +++ /dev/null @@ -1 +0,0 @@ -[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"proposer","type":"address"},{"indexed":true,"internalType":"uint256","name":"headerBlockId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"reward","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"start","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"end","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"root","type":"bytes32"}],"name":"NewHeaderBlock","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"proposer","type":"address"},{"indexed":true,"internalType":"uint256","name":"headerBlockId","type":"uint256"}],"name":"ResetHeaderBlock","type":"event"}] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/RootChainHeader.bin b/cmd/devnet/contracts/build/RootChainHeader.bin deleted file mode 100644 index cbf7ad2624b..00000000000 --- a/cmd/devnet/contracts/build/RootChainHeader.bin +++ /dev/null @@ -1 +0,0 @@ -6080604052348015600f57600080fd5b50603f80601d6000396000f3fe6080604052600080fdfea26469706673582212200c8ac7f24c4ac2062b97f586926948ab59c95f6377be277888fca7551590093a64736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/build/RootChainStorage.abi b/cmd/devnet/contracts/build/RootChainStorage.abi deleted file mode 100644 index f74f62e19d8..00000000000 --- a/cmd/devnet/contracts/build/RootChainStorage.abi +++ /dev/null @@ -1 +0,0 @@ -[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"proposer","type":"address"},{"indexed":true,"internalType":"uint256","name":"headerBlockId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"reward","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"start","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"end","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"root","type":"bytes32"}],"name":"NewHeaderBlock","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"proposer","type":"address"},{"indexed":true,"internalType":"uint256","name":"headerBlockId","type":"uint256"}],"name":"ResetHeaderBlock","type":"event"},{"inputs":[],"name":"CHAINID","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"VOTE_TYPE","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_nextHeaderBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"headerBlocks","outputs":[{"internalType":"bytes32","name":"root","type":"bytes32"},{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"end","type":"uint256"},{"internalType":"uint256","name":"createdAt","type":"uint256"},{"internalType":"address","name":"proposer","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"heimdallId","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"networkId","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"view","type":"function"}] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/RootChainStorage.bin b/cmd/devnet/contracts/build/RootChainStorage.bin deleted file mode 100644 index 4eb00bc7919..00000000000 --- a/cmd/devnet/contracts/build/RootChainStorage.bin +++ /dev/null @@ -1 +0,0 @@ -6080604052612710600255600160035534801561001b57600080fd5b506101f28061002b6000396000f3fe608060405234801561001057600080fd5b50600436106100625760003560e01c806341539d4a146100675780638d978d88146100e45780639025e64c146100fb578063cc79f97b14610129578063d5b844eb14610132578063fbc3dd361461014c575b600080fd5b6100ae610075366004610155565b6004602081905260009182526040909120805460018201546002830154600384015493909401549193909290916001600160a01b031685565b6040805195865260208601949094529284019190915260608301526001600160a01b0316608082015260a0015b60405180910390f35b6100ed60025481565b6040519081526020016100db565b61011c60405180604001604052806002815260200161053960f01b81525081565b6040516100db919061016e565b6100ed61053981565b61013a600281565b60405160ff90911681526020016100db565b6100ed60015481565b60006020828403121561016757600080fd5b5035919050565b600060208083528351808285015260005b8181101561019b5785810183015185820160400152820161017f565b506000604082860101526040601f19601f830116850101925050509291505056fea264697066735822122071950929b53ae66c9034d5ed38e7212ee33978b3a0467a495ec9c37f901c391064736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/build/RootReceiver.abi b/cmd/devnet/contracts/build/RootReceiver.abi deleted file mode 100644 index ed62067d186..00000000000 --- a/cmd/devnet/contracts/build/RootReceiver.abi +++ /dev/null @@ -1 +0,0 @@ -[{"inputs":[{"internalType":"address","name":"_checkpointManager","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_source","type":"address"},{"indexed":false,"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"received","type":"event"},{"inputs":[],"name":"SEND_MESSAGE_EVENT_SIG","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"checkpointManager","outputs":[{"internalType":"contract ICheckpointManager","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"processedExits","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes","name":"inputData","type":"bytes"}],"name":"receiveMessage","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"senders","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/RootReceiver.bin b/cmd/devnet/contracts/build/RootReceiver.bin deleted file mode 100644 index fc8e458bbb1..00000000000 --- a/cmd/devnet/contracts/build/RootReceiver.bin +++ /dev/null @@ -1 +0,0 @@ -608060405234801561001057600080fd5b50604051611ed1380380611ed183398101604081905261002f91610054565b600080546001600160a01b0319166001600160a01b0392909216919091179055610084565b60006020828403121561006657600080fd5b81516001600160a01b038116811461007d57600080fd5b9392505050565b611e3e806100936000396000f3fe608060405234801561001057600080fd5b50600436106100575760003560e01c80630e387de61461005c578063607f2d4214610096578063982fb9d8146100c9578063c0857ba0146100e9578063f953cec714610114575b600080fd5b6100837f8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b03681565b6040519081526020015b60405180910390f35b6100b96100a436600461196a565b60016020526000908152604090205460ff1681565b604051901515815260200161008d565b6100836100d736600461199b565b60026020526000908152604090205481565b6000546100fc906001600160a01b031681565b6040516001600160a01b03909116815260200161008d565b610127610122366004611a25565b610129565b005b60008061013583610148565b9150915061014382826103cf565b505050565b600060606000610157846104bb565b905060006101648261051a565b9050600061017183610549565b905060008161017f84610572565b6101888661072e565b60405160200161019a93929190611ac8565b60408051601f1981840301815291815281516020928301206000818152600190935291205490915060ff16156102235760405162461bcd60e51b8152602060048201526024808201527f4678526f6f7454756e6e656c3a20455849545f414c52454144595f50524f434560448201526314d4d15160e21b60648201526084015b60405180910390fd5b60008181526001602081905260408220805460ff191690911790556102478561074a565b9050600061025482610893565b9050600061026187610923565b9050610281610271846020015190565b8761027b8a61093f565b8461095b565b6102d95760405162461bcd60e51b815260206004820152602360248201527f4678526f6f7454756e6e656c3a20494e56414c49445f524543454950545f505260448201526227a7a360e91b606482015260840161021a565b610307856102e689610c28565b6102ef8a610c44565b846102f98c610c60565b6103028d610c7c565b610c98565b600061031283610db2565b90507f8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036610348610343836000610dee565b610e26565b146103955760405162461bcd60e51b815260206004820152601f60248201527f4678526f6f7454756e6e656c3a20494e56414c49445f5349474e415455524500604482015260640161021a565b60006103a084610ea1565b8060200190518101906103b39190611af5565b90506103be84610ebd565b9c909b509950505050505050505050565b6000806000838060200190518101906103e89190611b6b565b919450925090506001600160a01b038316301461043a5760405162461bcd60e51b815260206004820152601060248201526f24b73b30b634b2103932b1b2b4bb32b960811b604482015260640161021a565b6001600160a01b03821660009081526002602052604090205461045d8282611bc4565b6001600160a01b0384166000818152600260209081526040918290209390935580519182529181018490527ff11e547d796cc64acdf758e7cee90439494fd886a19159454aa61e473fdbafef910160405180910390a1505050505050565b60408051602081019091526060815260006105056105008460408051808201825260008082526020918201528151808301909252825182529182019181019190915290565b610ee6565b60408051602081019091529081529392505050565b6060610543826000015160088151811061053657610536611bd7565b6020026020010151610ffb565b92915050565b6000610543826000015160028151811061056557610565611bd7565b6020026020010151610e26565b604080516020810190915260008152815160609190156105435760008061059a600086611097565b60f81c905060018114806105b157508060ff166003145b15610658576001855160026105c69190611bed565b6105d09190611c04565b6001600160401b038111156105e7576105e76119b8565b6040519080825280601f01601f191660200182016040528015610611576020820181803683370190505b5092506000610621600187611097565b9050808460008151811061063757610637611bd7565b60200101906001600160f81b031916908160001a90535060019250506106bb565b6002855160026106689190611bed565b6106729190611c04565b6001600160401b03811115610689576106896119b8565b6040519080825280601f01601f1916602001820160405280156106b3576020820181803683370190505b509250600091505b60ff82165b8351811015610725576106ea6106d960ff851683611c04565b6106e4906002611bc4565b87611097565b8482815181106106fc576106fc611bd7565b60200101906001600160f81b031916908160001a9053508061071d81611c17565b9150506106c0565b50505092915050565b6000610543826000015160098151811061056557610565611bd7565b61076e60405180606001604052806060815260200160608152602001600081525090565b610788826000015160068151811061053657610536611bd7565b6020828101829052604080518082018252600080825290830152805180820190915282518152918101908201526107be81611118565b156107d3576107cc81610ee6565b825261087f565b602082015180516000906107e990600190611c04565b6001600160401b03811115610800576108006119b8565b6040519080825280601f01601f19166020018201604052801561082a576020820181803683370190505b50905060008083602101915082602001905061084882828551611153565b60408051808201825260008082526020918201528151808301909252845182528085019082015261087890610ee6565b8652505050505b6108888361072e565b604083015250919050565b6040805160808101825260009181018281526060808301939093528152602081019190915260006108e183600001516003815181106108d4576108d4611bd7565b6020026020010151610ee6565b8360400151815181106108f6576108f6611bd7565b60200260200101519050604051806040016040528082815260200161091a83610ee6565b90529392505050565b6000610543826000015160058151811061056557610565611bd7565b6060610543826000015160078151811061053657610536611bd7565b60008061098f8460408051808201825260008082526020918201528151808301909252825182529182019181019190915290565b9050600061099c826111de565b9050606080856000806109ae8b610572565b905080516000036109c9576000975050505050505050610c20565b60005b8651811015610c175781518311156109ef57600098505050505050505050610c20565b610a11878281518110610a0457610a04611bd7565b60200260200101516112e8565b955085805190602001208414610a3257600098505050505050505050610c20565b610a54878281518110610a4757610a47611bd7565b60200260200101516111de565b94508451601103610b335781518303610ac0578c80519060200120610a9286601081518110610a8557610a85611bd7565b6020026020010151611366565b8051906020012003610aaf57600198505050505050505050610c20565b600098505050505050505050610c20565b6000828481518110610ad457610ad4611bd7565b016020015160f81c90506010811115610af95760009950505050505050505050610c20565b610b1e868260ff1681518110610b1157610b11611bd7565b6020026020010151611402565b9450610b2b600185611bc4565b935050610c05565b8451600203610aaf576000610b5e610b5787600081518110610a8557610a85611bd7565b8486611430565b8351909150610b6d8286611bc4565b03610bc0578d80519060200120610b9087600181518110610a8557610a85611bd7565b8051906020012003610bae5760019950505050505050505050610c20565b60009950505050505050505050610c20565b80600003610bda5760009950505050505050505050610c20565b610be48185611bc4565b9350610bfc86600181518110610b1157610b11611bd7565b9450610c059050565b80610c0f81611c17565b9150506109cc565b50505050505050505b949350505050565b6000610543826000015160038151811061056557610565611bd7565b6000610543826000015160048151811061056557610565611bd7565b6000610543826000015160008151811061056557610565611bd7565b6060610543826000015160018151811061053657610536611bd7565b600080546040516320a9cea560e11b81526004810185905282916001600160a01b0316906341539d4a9060240160a060405180830381865afa158015610ce2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d069190611c30565b50505091509150610d5c8189610d1c9190611c04565b6040805160208082018d90528183018c9052606082018b905260808083018b90528351808403909101815260a09092019092528051910120908486611537565b610da85760405162461bcd60e51b815260206004820152601c60248201527f4678526f6f7454756e6e656c3a20494e56414c49445f48454144455200000000604482015260640161021a565b5050505050505050565b6040805160208101909152606081526040518060200160405280610de684602001516001815181106108d4576108d4611bd7565b905292915050565b60408051808201909152600080825260208201528251805183908110610e1657610e16611bd7565b6020026020010151905092915050565b805160009015801590610e3b57508151602110155b610e4457600080fd5b6000610e53836020015161169f565b90506000818460000151610e679190611c04565b9050600080838660200151610e7c9190611bc4565b9050805191506020831015610e9857826020036101000a820491505b50949350505050565b6060610543826020015160028151811061053657610536611bd7565b60006105438260200151600081518110610ed957610ed9611bd7565b6020026020010151611721565b6060610ef182611118565b610efa57600080fd5b6000610f058361173b565b90506000816001600160401b03811115610f2157610f216119b8565b604051908082528060200260200182016040528015610f6657816020015b6040805180820190915260008082526020820152815260200190600190039081610f3f5790505b5090506000610f78856020015161169f565b8560200151610f879190611bc4565b90506000805b84811015610ff057610f9e836117c0565b9150604051806040016040528083815260200184815250848281518110610fc757610fc7611bd7565b6020908102919091010152610fdc8284611bc4565b925080610fe881611c17565b915050610f8d565b509195945050505050565b805160609061100957600080fd5b6000611018836020015161169f565b9050600081846000015161102c9190611c04565b90506000816001600160401b03811115611048576110486119b8565b6040519080825280601f01601f191660200182016040528015611072576020820181803683370190505b5090506000816020019050610e988487602001516110909190611bc4565b8285611864565b60006110a4600284611c93565b156110de576010826110b7600286611ca7565b815181106110c7576110c7611bd7565b01602001516110d9919060f81c611cbb565b61110e565b6010826110ec600286611ca7565b815181106110fc576110fc611bd7565b016020015161110e919060f81c611cdd565b60f81b9392505050565b8051600090810361112b57506000919050565b6020820151805160001a9060c0821015611149575060009392505050565b5060019392505050565b8060000361116057505050565b602081106111985782518252611177602084611bc4565b9250611184602083611bc4565b9150611191602082611c04565b9050611160565b806000036111a557505050565b600060016111b4836020611c04565b6111c090610100611de3565b6111ca9190611c04565b935183518516941916939093179091525050565b60606111e982611118565b6111f257600080fd5b60006111fd836118a9565b90506000816001600160401b03811115611219576112196119b8565b60405190808252806020026020018201604052801561125e57816020015b60408051808201909152600080825260208201528152602001906001900390816112375790505b5090506000611270856020015161169f565b856020015161127f9190611bc4565b90506000805b84811015610ff057611296836117c0565b91506040518060400160405280838152602001848152508482815181106112bf576112bf611bd7565b60209081029190910101526112d48284611bc4565b9250806112e081611c17565b915050611285565b6060600082600001516001600160401b03811115611308576113086119b8565b6040519080825280601f01601f191660200182016040528015611332576020820181803683370190505b50905080516000036113445792915050565b600081602001905061135f8460200151828660000151611925565b5092915050565b805160609061137457600080fd5b6000611383836020015161169f565b905060008184600001516113979190611c04565b90506000816001600160401b038111156113b3576113b36119b8565b6040519080825280601f01601f1916602001820160405280156113dd576020820181803683370190505b5090506000816020019050610e988487602001516113fb9190611bc4565b8285611925565b805160009060211461141357600080fd5b600080836020015160016114279190611bc4565b51949350505050565b6000808061143d86610572565b9050600081516001600160401b0381111561145a5761145a6119b8565b6040519080825280601f01601f191660200182016040528015611484576020820181803683370190505b509050845b82516114959087611bc4565b8110156115085760008782815181106114b0576114b0611bd7565b01602001516001600160f81b031916905080836114cd8985611c04565b815181106114dd576114dd611bd7565b60200101906001600160f81b031916908160001a90535050808061150090611c17565b915050611489565b508080519060200120828051906020012003611527578151925061152c565b600092505b509095945050505050565b6000602082516115479190611c93565b1561158b5760405162461bcd60e51b8152602060048201526014602482015273092dcecc2d8d2c840e0e4dedecc40d8cadccee8d60631b604482015260640161021a565b60006020835161159b9190611ca7565b90506115a8816002611de3565b85106115ee5760405162461bcd60e51b81526020600482015260156024820152744c65616620696e64657820697320746f6f2062696760581b604482015260640161021a565b60008660205b855181116116915785810151925061160d600289611c93565b600003611645576040805160208101849052908101849052606001604051602081830303815290604052805190602001209150611672565b60408051602081018590529081018390526060016040516020818303038152906040528051906020012091505b61167d600289611ca7565b975061168a602082611bc4565b90506115f4565b509094149695505050505050565b8051600090811a60808110156116b85750600092915050565b60b88110806116d3575060c081108015906116d3575060f881105b156116e15750600192915050565b60c0811015611715576116f6600160b8611def565b6117039060ff1682611c04565b61170e906001611bc4565b9392505050565b6116f6600160f8611def565b805160009060151461173257600080fd5b61054382610e26565b8051600090810361174e57506000919050565b60008061175e846020015161169f565b846020015161176d9190611bc4565b90506000846000015185602001516117859190611bc4565b90505b808210156117b757611799826117c0565b6117a39083611bc4565b9150826117af81611c17565b935050611788565b50909392505050565b80516000908190811a60808110156117db576001915061135f565b60b8811015611801576117ef608082611c04565b6117fa906001611bc4565b915061135f565b60c081101561182e5760b78103600185019450806020036101000a8551046001820181019350505061135f565b60f8811015611842576117ef60c082611c04565b60019390930151602084900360f7016101000a900490920160f5190192915050565b8060000361187157505050565b602081106111985782518252611888602084611bc4565b9250611895602083611bc4565b91506118a2602082611c04565b9050611871565b805160009081036118bc57506000919050565b6000806118cc846020015161169f565b84602001516118db9190611bc4565b90506000846000015185602001516118f39190611bc4565b90505b808210156117b757611907826117c0565b6119119083611bc4565b91508261191d81611c17565b9350506118f6565b8060000361193257505050565b602081106111985782518252611949602084611bc4565b9250611956602083611bc4565b9150611963602082611c04565b9050611932565b60006020828403121561197c57600080fd5b5035919050565b6001600160a01b038116811461199857600080fd5b50565b6000602082840312156119ad57600080fd5b813561170e81611983565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b03811182821017156119f6576119f66119b8565b604052919050565b60006001600160401b03821115611a1757611a176119b8565b50601f01601f191660200190565b600060208284031215611a3757600080fd5b81356001600160401b03811115611a4d57600080fd5b8201601f81018413611a5e57600080fd5b8035611a71611a6c826119fe565b6119ce565b818152856020838501011115611a8657600080fd5b81602084016020830137600091810160200191909152949350505050565b60005b83811015611abf578181015183820152602001611aa7565b50506000910152565b83815260008351611ae0816020850160208801611aa4565b60209201918201929092526040019392505050565b600060208284031215611b0757600080fd5b81516001600160401b03811115611b1d57600080fd5b8201601f81018413611b2e57600080fd5b8051611b3c611a6c826119fe565b818152856020838501011115611b5157600080fd5b611b62826020830160208601611aa4565b95945050505050565b600080600060608486031215611b8057600080fd5b8351611b8b81611983565b6020850151909350611b9c81611983565b80925050604084015190509250925092565b634e487b7160e01b600052601160045260246000fd5b8082018082111561054357610543611bae565b634e487b7160e01b600052603260045260246000fd5b808202811582820484141761054357610543611bae565b8181038181111561054357610543611bae565b600060018201611c2957611c29611bae565b5060010190565b600080600080600060a08688031215611c4857600080fd5b855194506020860151935060408601519250606086015191506080860151611c6f81611983565b809150509295509295909350565b634e487b7160e01b600052601260045260246000fd5b600082611ca257611ca2611c7d565b500690565b600082611cb657611cb6611c7d565b500490565b600060ff831680611cce57611cce611c7d565b8060ff84160691505092915050565b600060ff831680611cf057611cf0611c7d565b8060ff84160491505092915050565b600181815b80851115611d3a578160001904821115611d2057611d20611bae565b80851615611d2d57918102915b93841c9390800290611d04565b509250929050565b600082611d5157506001610543565b81611d5e57506000610543565b8160018114611d745760028114611d7e57611d9a565b6001915050610543565b60ff841115611d8f57611d8f611bae565b50506001821b610543565b5060208310610133831016604e8410600b8410161715611dbd575081810a610543565b611dc78383611cff565b8060001904821115611ddb57611ddb611bae565b029392505050565b600061170e8383611d42565b60ff828116828216039081111561054357610543611bae56fea2646970667358221220a924e520bf4f9d5629bc95702236e2702455bf9b57c4e9e4e344c7c7d7576a2b64736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/build/RootSender.abi b/cmd/devnet/contracts/build/RootSender.abi deleted file mode 100644 index e6c98b82f35..00000000000 --- a/cmd/devnet/contracts/build/RootSender.abi +++ /dev/null @@ -1 +0,0 @@ -[{"inputs":[{"internalType":"address","name":"stateSender_","type":"address"},{"internalType":"address","name":"childStateReceiver_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"sendToChild","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"sent","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/RootSender.bin b/cmd/devnet/contracts/build/RootSender.bin deleted file mode 100644 index ba5b6b773a2..00000000000 --- a/cmd/devnet/contracts/build/RootSender.bin +++ /dev/null @@ -1 +0,0 @@ -608060405234801561001057600080fd5b506040516102fb3803806102fb83398101604081905261002f9161007c565b600080546001600160a01b039384166001600160a01b031991821617909155600180549290931691161790556100af565b80516001600160a01b038116811461007757600080fd5b919050565b6000806040838503121561008f57600080fd5b61009883610060565b91506100a660208401610060565b90509250929050565b61023d806100be6000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c8063513e29ff1461003b5780637bf786f814610050575b600080fd5b61004e610049366004610139565b610082565b005b61007061005e366004610152565b60026020526000908152604090205481565b60405190815260200160405180910390f35b3360009081526002602052604090205461009c8282610182565b33600081815260026020908152604080832094909455905460015484519283019390935281840186905283518083038501815260608301948590526316f1983160e01b9094526001600160a01b03908116936316f1983193610103939216916064016101a9565b600060405180830381600087803b15801561011d57600080fd5b505af1158015610131573d6000803e3d6000fd5b505050505050565b60006020828403121561014b57600080fd5b5035919050565b60006020828403121561016457600080fd5b81356001600160a01b038116811461017b57600080fd5b9392505050565b808201808211156101a357634e487b7160e01b600052601160045260246000fd5b92915050565b60018060a01b038316815260006020604081840152835180604085015260005b818110156101e5578581018301518582016060015282016101c9565b506000606082860101526060601f19601f83011685010192505050939250505056fea2646970667358221220fa5fa4e9dd64f8da1ad4844228b4671828b48d8de1f8d3f92ba0e5551ce1e47c64736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/build/SafeMath.abi b/cmd/devnet/contracts/build/SafeMath.abi deleted file mode 100644 index 0637a088a01..00000000000 --- a/cmd/devnet/contracts/build/SafeMath.abi +++ /dev/null @@ -1 +0,0 @@ -[] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/SafeMath.bin b/cmd/devnet/contracts/build/SafeMath.bin deleted file mode 100644 index 2e4b4c031c1..00000000000 --- a/cmd/devnet/contracts/build/SafeMath.bin +++ /dev/null @@ -1 +0,0 @@ -60566037600b82828239805160001a607314602a57634e487b7160e01b600052600060045260246000fd5b30600052607381538281f3fe73000000000000000000000000000000000000000030146080604052600080fdfea26469706673582212201a043f7e2f0c8bbcbf3cc5dab09f7bd56ae68a8e71ec23dc15074186793c7ead64736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/build/Subscription.abi b/cmd/devnet/contracts/build/Subscription.abi deleted file mode 100644 index 9c9a4c07741..00000000000 --- a/cmd/devnet/contracts/build/Subscription.abi +++ /dev/null @@ -1 +0,0 @@ -[{"anonymous":false,"inputs":[],"name":"SubscriptionEvent","type":"event"},{"stateMutability":"nonpayable","type":"fallback"}] diff --git a/cmd/devnet/contracts/build/Subscription.bin b/cmd/devnet/contracts/build/Subscription.bin deleted file mode 100644 index 4b6bb4ae052..00000000000 --- a/cmd/devnet/contracts/build/Subscription.bin +++ /dev/null @@ -1 +0,0 @@ -6080604052348015600f57600080fd5b50607180601d6000396000f3fe6080604052348015600f57600080fd5b506040517f67abc7edb0ab50964ef0e90541d39366b9c69f6f714520f2ff4570059ee8ad8090600090a100fea264697066735822122045a70478ef4f6a283c0e153ad72ec6731dc9ee2e1c191c7334b74dea21a92eaf64736f6c634300080c0033 diff --git a/cmd/devnet/contracts/build/TestRootChain.abi b/cmd/devnet/contracts/build/TestRootChain.abi deleted file mode 100644 index 8a0765be67a..00000000000 --- a/cmd/devnet/contracts/build/TestRootChain.abi +++ /dev/null @@ -1 +0,0 @@ -[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"proposer","type":"address"},{"indexed":true,"internalType":"uint256","name":"headerBlockId","type":"uint256"},{"indexed":true,"internalType":"uint256","name":"reward","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"start","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"end","type":"uint256"},{"indexed":false,"internalType":"bytes32","name":"root","type":"bytes32"}],"name":"NewHeaderBlock","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"proposer","type":"address"},{"indexed":true,"internalType":"uint256","name":"headerBlockId","type":"uint256"}],"name":"ResetHeaderBlock","type":"event"},{"inputs":[],"name":"CHAINID","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"VOTE_TYPE","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_nextHeaderBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"currentHeaderBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLastChildBlock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"headerBlocks","outputs":[{"internalType":"bytes32","name":"root","type":"bytes32"},{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"end","type":"uint256"},{"internalType":"uint256","name":"createdAt","type":"uint256"},{"internalType":"address","name":"proposer","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"heimdallId","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"networkId","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"_heimdallId","type":"string"}],"name":"setHeimdallId","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"_value","type":"uint256"}],"name":"setNextHeaderBlock","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"slash","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data","type":"bytes"},{"internalType":"uint256[3][]","name":"","type":"uint256[3][]"}],"name":"submitCheckpoint","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"","type":"bytes"},{"internalType":"bytes","name":"","type":"bytes"}],"name":"submitHeaderBlock","outputs":[],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"uint256","name":"numDeposits","type":"uint256"}],"name":"updateDepositId","outputs":[{"internalType":"uint256","name":"depositId","type":"uint256"}],"stateMutability":"nonpayable","type":"function"}] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/TestRootChain.bin b/cmd/devnet/contracts/build/TestRootChain.bin deleted file mode 100644 index c9eb0e144aa..00000000000 --- a/cmd/devnet/contracts/build/TestRootChain.bin +++ /dev/null @@ -1 +0,0 @@ -6080604052612710600255600160035534801561001b57600080fd5b50610af88061002b6000396000f3fe608060405234801561001057600080fd5b50600436106100ea5760003560e01c8063b87e1b661161008c578063d5b844eb11610066578063d5b844eb1461020b578063ea0688b314610225578063ec7e485514610238578063fbc3dd361461024057600080fd5b8063b87e1b66146101e7578063cc79f97b146101ef578063cf24a0ea146101f857600080fd5b80635391f483116100c85780635391f483146101815780636a791f11146101a25780638d978d88146101b05780639025e64c146101b957600080fd5b80632da25de3146100ef57806341539d4a146100f15780634e43e4951461016e575b600080fd5b005b6101386100ff36600461072b565b6004602081905260009182526040909120805460018201546002830154600384015493909401549193909290916001600160a01b031685565b6040805195865260208601949094529284019190915260608301526001600160a01b0316608082015260a0015b60405180910390f35b6100ef61017c36600461078d565b610249565b61019461018f36600461072b565b61037b565b604051908152602001610165565b6100ef6100ea366004610827565b61019460025481565b6101da60405180604001604052806002815260200161053960f01b81525081565b60405161016591906108b7565b6101946104c5565b61019461053981565b6100ef61020636600461072b565b6104ea565b610213600281565b60405160ff9091168152602001610165565b6100ef610233366004610900565b6105c5565b6101946105f4565b61019460015481565b6000808080808061025c898b018b6109c9565b95509550955095509550955080610539146102b55760405162461bcd60e51b8152602060048201526014602482015273125b9d985b1a5908189bdc8818da185a5b881a5960621b60448201526064015b60405180910390fd5b6102c18686868661060b565b6103055760405162461bcd60e51b8152602060048201526015602482015274494e434f52524543545f4845414445525f4441544160581b60448201526064016102ac565b6002546040805187815260208101879052908101859052600091906001600160a01b038916907fba5de06d22af2685c6c7765f60067f7d2b08c2d29f53cdf14d67f6d1c9bfb5279060600160405180910390a4600254610367906127106106e4565b600255505060016003555050505050505050565b6005546040805162c9effd60e41b815290516000926001600160a01b031691630c9effd09160048083019260209291908290030181865afa1580156103c4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103e89190610a15565b6001600160a01b0316336001600160a01b0316146104525760405162461bcd60e51b815260206004820152602160248201527f554e415554484f52495a45445f4445504f5349545f4d414e414745525f4f4e4c6044820152605960f81b60648201526084016102ac565b6104666003546104606105f4565b906106e4565b60035490915061047690836106e4565b600381905561271010156104c05760405162461bcd60e51b8152602060048201526011602482015270544f4f5f4d414e595f4445504f5349545360781b60448201526064016102ac565b919050565b6000600460006104d36105f4565b815260200190815260200160002060020154905090565b6104f661271082610a32565b156105335760405162461bcd60e51b815260206004820152600d60248201526c496e76616c69642076616c756560981b60448201526064016102ac565b805b60025481101561058a5760008181526004602081905260408220828155600181018390556002810183905560038101929092550180546001600160a01b031916905561058361271082610a6a565b9050610535565b5060028190556001600355604051819033907fca1d8316287f938830e225956a7bb10fd5a1a1506dd2eb3a476751a48811720590600090a350565b806040516020016105d69190610a7d565b60408051601f19818403018152919052805160209091012060015550565b60025460009061060690612710610708565b905090565b60008061271061ffff16600254111561064b576004600061062a6105f4565b81526020019081526020016000206002015460016106489190610a6a565b90505b84811461065c5760009150506106dc565b6040805160a081018252848152602080820193845281830187815242606084019081526001600160a01b038b811660808601908152600280546000908152600496879052979097209551865596516001808701919091559251958501959095555160038401559351910180546001600160a01b0319169190921617905590505b949350505050565b60006106f08284610a6a565b90508281101561070257610702610a99565b92915050565b60008282111561071a5761071a610a99565b6107248284610aaf565b9392505050565b60006020828403121561073d57600080fd5b5035919050565b60008083601f84011261075657600080fd5b50813567ffffffffffffffff81111561076e57600080fd5b60208301915083602082850101111561078657600080fd5b9250929050565b600080600080604085870312156107a357600080fd5b843567ffffffffffffffff808211156107bb57600080fd5b6107c788838901610744565b909650945060208701359150808211156107e057600080fd5b818701915087601f8301126107f457600080fd5b81358181111561080357600080fd5b88602060608302850101111561081857600080fd5b95989497505060200194505050565b6000806000806040858703121561083d57600080fd5b843567ffffffffffffffff8082111561085557600080fd5b61086188838901610744565b9096509450602087013591508082111561087a57600080fd5b5061088787828801610744565b95989497509550505050565b60005b838110156108ae578181015183820152602001610896565b50506000910152565b60208152600082518060208401526108d6816040850160208701610893565b601f01601f19169190910160400192915050565b634e487b7160e01b600052604160045260246000fd5b60006020828403121561091257600080fd5b813567ffffffffffffffff8082111561092a57600080fd5b818401915084601f83011261093e57600080fd5b813581811115610950576109506108ea565b604051601f8201601f19908116603f01168101908382118183101715610978576109786108ea565b8160405282815287602084870101111561099157600080fd5b826020860160208301376000928101602001929092525095945050505050565b6001600160a01b03811681146109c657600080fd5b50565b60008060008060008060c087890312156109e257600080fd5b86356109ed816109b1565b9860208801359850604088013597606081013597506080810135965060a00135945092505050565b600060208284031215610a2757600080fd5b8151610724816109b1565b600082610a4f57634e487b7160e01b600052601260045260246000fd5b500690565b634e487b7160e01b600052601160045260246000fd5b8082018082111561070257610702610a54565b60008251610a8f818460208701610893565b9190910192915050565b634e487b7160e01b600052600160045260246000fd5b8181038181111561070257610702610a5456fea2646970667358221220e8aee67b63507e8745850c7b73e998c6ef6b5d41b72b45f8f1316e80e79a1ec964736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/build/TestStateSender.abi b/cmd/devnet/contracts/build/TestStateSender.abi deleted file mode 100644 index 0e6ddb8687f..00000000000 --- a/cmd/devnet/contracts/build/TestStateSender.abi +++ /dev/null @@ -1 +0,0 @@ -[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"}],"name":"NewRegistration","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"}],"name":"RegistrationUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":true,"internalType":"address","name":"contractAddress","type":"address"},{"indexed":false,"internalType":"bytes","name":"data","type":"bytes"}],"name":"StateSynced","type":"event"},{"inputs":[],"name":"counter","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"address","name":"receiver","type":"address"}],"name":"register","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"registrations","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"syncState","outputs":[],"stateMutability":"nonpayable","type":"function"}] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/TestStateSender.bin b/cmd/devnet/contracts/build/TestStateSender.bin deleted file mode 100644 index 3e5cd21eb0c..00000000000 --- a/cmd/devnet/contracts/build/TestStateSender.bin +++ /dev/null @@ -1 +0,0 @@ -608060405234801561001057600080fd5b50610366806100206000396000f3fe608060405234801561001057600080fd5b506004361061004c5760003560e01c806316f198311461005157806361bc221a14610066578063942e6bcf14610082578063aa677354146100c3575b600080fd5b61006461005f366004610202565b6100d6565b005b61006f60005481565b6040519081526020015b60405180910390f35b6100ab610090366004610285565b6001602052600090815260409020546001600160a01b031681565b6040516001600160a01b039091168152602001610079565b6100646100d13660046102a7565b610137565b8260005460016100e691906102da565b60008190556040516001600160a01b03861691907f103fed9db65eac19c4d870f49ab7520fe03b99f1838e5996caf47e9e43308392906101299087908790610301565b60405180910390a350505050565b6001600160a01b03818116600090815260016020526040902080546001600160a01b03191691841691821790556101a7576040516001600160a01b03808316919084169033907f3f4512aacd7a664fdb321a48e8340120d63253a91c6367a143abd19ecf68aedd90600090a45050565b6040516001600160a01b03808316919084169033907fc51cb1a93ec91e927852b3445875ec77b148271953e5c0b43698c968ad6fc47d90600090a45050565b80356001600160a01b03811681146101fd57600080fd5b919050565b60008060006040848603121561021757600080fd5b610220846101e6565b9250602084013567ffffffffffffffff8082111561023d57600080fd5b818601915086601f83011261025157600080fd5b81358181111561026057600080fd5b87602082850101111561027257600080fd5b6020830194508093505050509250925092565b60006020828403121561029757600080fd5b6102a0826101e6565b9392505050565b600080604083850312156102ba57600080fd5b6102c3836101e6565b91506102d1602084016101e6565b90509250929050565b808201808211156102fb57634e487b7160e01b600052601160045260246000fd5b92915050565b60208152816020820152818360408301376000818301604090810191909152601f909201601f1916010191905056fea2646970667358221220503899fb2efad396cb70e03842531a8cc17c120a711e076fcab0878258e1c2bf64736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/build/faucet.abi b/cmd/devnet/contracts/build/faucet.abi deleted file mode 100644 index bb17b539cdf..00000000000 --- a/cmd/devnet/contracts/build/faucet.abi +++ /dev/null @@ -1 +0,0 @@ -[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_source","type":"address"},{"indexed":false,"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"received","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"_destination","type":"address"},{"indexed":false,"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"sent","type":"event"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"destinations","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address payable","name":"_destination","type":"address"},{"internalType":"uint256","name":"_requested","type":"uint256"}],"name":"send","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"sources","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/faucet.bin b/cmd/devnet/contracts/build/faucet.bin deleted file mode 100644 index 8c16bcf58a3..00000000000 --- a/cmd/devnet/contracts/build/faucet.bin +++ /dev/null @@ -1 +0,0 @@ -608060405234801561001057600080fd5b506102ea806100206000396000f3fe6080604052600436106100385760003560e01c806359c02c37146100a0578063b750bdde146100df578063d0679d341461010c57600080fd5b3661009b57336000908152602081905260408120805434929061005c908490610225565b9091555050604080513381523460208201527ff11e547d796cc64acdf758e7cee90439494fd886a19159454aa61e473fdbafef910160405180910390a1005b600080fd5b3480156100ac57600080fd5b506100cd6100bb366004610264565b60016020526000908152604090205481565b60405190815260200160405180910390f35b3480156100eb57600080fd5b506100cd6100fa366004610264565b60006020819052908152604090205481565b61011f61011a366004610288565b610121565b005b4760000361012d575050565b600081471115610176575060405181906001600160a01b0384169082156108fc029083906000818181858888f19350505050158015610170573d6000803e3d6000fd5b506101b1565b5060405147906001600160a01b0384169082156108fc029083906000818181858888f193505050501580156101af573d6000803e3d6000fd5b505b6001600160a01b038316600090815260016020526040812080548392906101d9908490610225565b9091555050604080516001600160a01b0385168152602081018390527f3bcb2e664d8f57273201bc888e82d6549f8308a52a9fcd7702b2ea8387f769a9910160405180910390a1505050565b8082018082111561024657634e487b7160e01b600052601160045260246000fd5b92915050565b6001600160a01b038116811461026157600080fd5b50565b60006020828403121561027657600080fd5b81356102818161024c565b9392505050565b6000806040838503121561029b57600080fd5b82356102a68161024c565b94602093909301359350505056fea2646970667358221220ac81b3f12efbe2860b7a5f00b56a253c6661d9ad6df22e642da3546e0015e9d664736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/build/lib_RLPReader_sol_RLPReader.abi b/cmd/devnet/contracts/build/lib_RLPReader_sol_RLPReader.abi deleted file mode 100644 index 0637a088a01..00000000000 --- a/cmd/devnet/contracts/build/lib_RLPReader_sol_RLPReader.abi +++ /dev/null @@ -1 +0,0 @@ -[] \ No newline at end of file diff --git a/cmd/devnet/contracts/build/lib_RLPReader_sol_RLPReader.bin b/cmd/devnet/contracts/build/lib_RLPReader_sol_RLPReader.bin deleted file mode 100644 index fe1e4b7272d..00000000000 --- a/cmd/devnet/contracts/build/lib_RLPReader_sol_RLPReader.bin +++ /dev/null @@ -1 +0,0 @@ -60566037600b82828239805160001a607314602a57634e487b7160e01b600052600060045260246000fd5b30600052607381538281f3fe73000000000000000000000000000000000000000030146080604052600080fdfea264697066735822122052e9a349bc8a4fd9c5d36d064e612b59e39ba032ed6620df6cc57822b5d7171164736f6c63430008140033 \ No newline at end of file diff --git a/cmd/devnet/contracts/childreceiver.sol b/cmd/devnet/contracts/childreceiver.sol deleted file mode 100644 index 0576a2ebc4f..00000000000 --- a/cmd/devnet/contracts/childreceiver.sol +++ /dev/null @@ -1,25 +0,0 @@ -// SPDX-License-Identifier: LGPL-3.0 - -pragma solidity ^0.8.6; - -interface IStateReceiver { - function onStateReceive(uint256 stateId, bytes calldata data) external; -} - -contract ChildReceiver is IStateReceiver { - mapping(address => uint) public senders; - - constructor() { - } - - event received(address _source, uint256 _amount); - - function onStateReceive(uint, bytes calldata data) external override { - require(msg.sender == address(0x0000000000000000000000000000000000001001), "Invalid sender"); - (address from, uint amount) = abi.decode(data, (address, uint)); - uint total = senders[from]; - senders[from] = total + amount; - - emit received(from, amount); - } -} diff --git a/cmd/devnet/contracts/childsender.sol b/cmd/devnet/contracts/childsender.sol deleted file mode 100644 index 67492baa730..00000000000 --- a/cmd/devnet/contracts/childsender.sol +++ /dev/null @@ -1,28 +0,0 @@ -// SPDX-License-Identifier: LGPL-3.0 - -pragma solidity ^0.8.6; - -contract ChildSender { - address rootStateReceiver; - mapping(address => uint) public sent; - - // MessageTunnel on L1 will get data from this event - event MessageSent(bytes message); - - constructor(address childStateReceiver_) { - rootStateReceiver = childStateReceiver_; - } - - function _sendMessageToRoot(bytes memory message) internal { - emit MessageSent(message); - } - - function sendToRoot(uint amount) external { - uint total = sent[msg.sender]; - sent[msg.sender] = total + amount; - - _sendMessageToRoot( - abi.encode(rootStateReceiver, msg.sender, amount) - ); - } -} diff --git a/cmd/devnet/contracts/faucet.sol b/cmd/devnet/contracts/faucet.sol deleted file mode 100644 index 49c9caa9949..00000000000 --- a/cmd/devnet/contracts/faucet.sol +++ /dev/null @@ -1,40 +0,0 @@ -// SPDX-License-Identifier: LGPL-3.0 - -pragma solidity ^0.8.0; - -contract faucet { - mapping (address => uint256) public sources; - mapping (address => uint256) public destinations; - - constructor() {} - - event sent(address _destination, uint256 _amount); - event received(address _source, uint256 _amount); - - receive() external payable - { - sources[msg.sender] += msg.value; - emit received(msg.sender, msg.value); - } - - function send(address payable _destination, uint256 _requested) public payable - { - if (address(this).balance == 0) { - return; - } - - uint256 amount = 0; - - if (address(this).balance > _requested){ - amount = _requested; - _destination.transfer(_requested); - } - else{ - amount = address(this).balance; - _destination.transfer(amount); - } - - destinations[_destination] += amount; - emit sent(_destination, amount); - } -} \ No newline at end of file diff --git a/cmd/devnet/contracts/gen.go b/cmd/devnet/contracts/gen.go deleted file mode 100644 index f9da61a64fa..00000000000 --- a/cmd/devnet/contracts/gen.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package contracts - -// rootsender.sol -//go:generate solc --evm-version paris --allow-paths ., --abi --bin --overwrite --optimize -o build rootsender.sol -//go:generate abigen -abi build/RootSender.abi -bin build/RootSender.bin -pkg contracts -type RootSender -out ./gen_rootsender.go - -// childsender.sol -//go:generate solc --evm-version paris --allow-paths ., --abi --bin --overwrite --optimize -o build childsender.sol -//go:generate abigen -abi build/ChildSender.abi -bin build/ChildSender.bin -pkg contracts -type ChildSender -out ./gen_childsender.go - -// teststatesender.sol -//go:generate solc --evm-version paris --allow-paths ., --abi --bin --overwrite --optimize -o build teststatesender.sol -//go:generate abigen -abi build/TestStateSender.abi -bin build/TestStateSender.bin -pkg contracts -type TestStateSender -out ./gen_teststatesender.go - -// rootreceiver.sol -//go:generate solc --evm-version paris --allow-paths ., --abi --bin --overwrite --optimize -o build rootreceiver.sol -//go:generate abigen -abi build/RootReceiver.abi -bin build/RootReceiver.bin -pkg contracts -type RootReceiver -out ./gen_rootreceiver.go - -// childreceiver.sol -//go:generate solc --evm-version paris --allow-paths ., --abi --bin --overwrite --optimize -o build childreceiver.sol -//go:generate abigen -abi build/ChildReceiver.abi -bin build/ChildReceiver.bin -pkg contracts -type ChildReceiver -out ./gen_childreceiver.go - -// testrootchain.sol -//go:generate solc --evm-version paris --allow-paths ., --abi --bin --overwrite --optimize -o build testrootchain.sol -//go:generate abigen -abi build/TestRootChain.abi -bin build/TestRootChain.bin -pkg contracts -type TestRootChain -out ./gen_testrootchain.go - -// faucet.sol -//go:generate solc --evm-version paris --allow-paths ., --abi --bin --overwrite --optimize -o build faucet.sol -//go:generate abigen -abi build/faucet.abi -bin build/faucet.bin -pkg contracts -type Faucet -out ./gen_faucet.go diff --git a/cmd/devnet/contracts/gen_childreceiver.go b/cmd/devnet/contracts/gen_childreceiver.go deleted file mode 100644 index f234c73524c..00000000000 --- a/cmd/devnet/contracts/gen_childreceiver.go +++ /dev/null @@ -1,423 +0,0 @@ -// Code generated by abigen. DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package contracts - -import ( - "fmt" - "math/big" - "reflect" - "strings" - - ethereum "github.com/erigontech/erigon" - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon/execution/abi" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/execution/types" - "github.com/erigontech/erigon/p2p/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription - _ = fmt.Errorf - _ = reflect.ValueOf -) - -// ChildReceiverABI is the input ABI used to generate the binding from. -const ChildReceiverABI = "[{\"inputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"_source\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"received\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"onStateReceive\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"senders\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"}]" - -// ChildReceiverBin is the compiled bytecode used for deploying new contracts. -var ChildReceiverBin = "0x608060405234801561001057600080fd5b5061029c806100206000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c806326c53bea1461003b578063982fb9d814610050575b600080fd5b61004e61004936600461015b565b610082565b005b61007061005e3660046101ef565b60006020819052908152604090205481565b60405190815260200160405180910390f35b33611001146100c85760405162461bcd60e51b815260206004820152600e60248201526d24b73b30b634b21039b2b73232b960911b604482015260640160405180910390fd5b6000806100d783850185610213565b6001600160a01b03821660009081526020819052604090205491935091506100ff828261023f565b6001600160a01b038416600081815260208181526040918290209390935580519182529181018490527ff11e547d796cc64acdf758e7cee90439494fd886a19159454aa61e473fdbafef910160405180910390a1505050505050565b60008060006040848603121561017057600080fd5b83359250602084013567ffffffffffffffff8082111561018f57600080fd5b818601915086601f8301126101a357600080fd5b8135818111156101b257600080fd5b8760208285010111156101c457600080fd5b6020830194508093505050509250925092565b6001600160a01b03811681146101ec57600080fd5b50565b60006020828403121561020157600080fd5b813561020c816101d7565b9392505050565b6000806040838503121561022657600080fd5b8235610231816101d7565b946020939093013593505050565b8082018082111561026057634e487b7160e01b600052601160045260246000fd5b9291505056fea2646970667358221220bb3a513950ddc3581a83b932be35476871cfca25f2faf93bb137e0f50d8c5ad864736f6c63430008140033" - -// DeployChildReceiver deploys a new Ethereum contract, binding an instance of ChildReceiver to it. -func DeployChildReceiver(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, types.Transaction, *ChildReceiver, error) { - parsed, err := abi.JSON(strings.NewReader(ChildReceiverABI)) - if err != nil { - return common.Address{}, nil, nil, err - } - - address, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(ChildReceiverBin), backend) - if err != nil { - return common.Address{}, nil, nil, err - } - return address, tx, &ChildReceiver{ChildReceiverCaller: ChildReceiverCaller{contract: contract}, ChildReceiverTransactor: ChildReceiverTransactor{contract: contract}, ChildReceiverFilterer: ChildReceiverFilterer{contract: contract}}, nil -} - -// ChildReceiver is an auto generated Go binding around an Ethereum contract. -type ChildReceiver struct { - ChildReceiverCaller // Read-only binding to the contract - ChildReceiverTransactor // Write-only binding to the contract - ChildReceiverFilterer // Log filterer for contract events -} - -// ChildReceiverCaller is an auto generated read-only Go binding around an Ethereum contract. -type ChildReceiverCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ChildReceiverTransactor is an auto generated write-only Go binding around an Ethereum contract. -type ChildReceiverTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ChildReceiverFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type ChildReceiverFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ChildReceiverSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type ChildReceiverSession struct { - Contract *ChildReceiver // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// ChildReceiverCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type ChildReceiverCallerSession struct { - Contract *ChildReceiverCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// ChildReceiverTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type ChildReceiverTransactorSession struct { - Contract *ChildReceiverTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// ChildReceiverRaw is an auto generated low-level Go binding around an Ethereum contract. -type ChildReceiverRaw struct { - Contract *ChildReceiver // Generic contract binding to access the raw methods on -} - -// ChildReceiverCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type ChildReceiverCallerRaw struct { - Contract *ChildReceiverCaller // Generic read-only contract binding to access the raw methods on -} - -// ChildReceiverTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type ChildReceiverTransactorRaw struct { - Contract *ChildReceiverTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewChildReceiver creates a new instance of ChildReceiver, bound to a specific deployed contract. -func NewChildReceiver(address common.Address, backend bind.ContractBackend) (*ChildReceiver, error) { - contract, err := bindChildReceiver(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &ChildReceiver{ChildReceiverCaller: ChildReceiverCaller{contract: contract}, ChildReceiverTransactor: ChildReceiverTransactor{contract: contract}, ChildReceiverFilterer: ChildReceiverFilterer{contract: contract}}, nil -} - -// NewChildReceiverCaller creates a new read-only instance of ChildReceiver, bound to a specific deployed contract. -func NewChildReceiverCaller(address common.Address, caller bind.ContractCaller) (*ChildReceiverCaller, error) { - contract, err := bindChildReceiver(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &ChildReceiverCaller{contract: contract}, nil -} - -// NewChildReceiverTransactor creates a new write-only instance of ChildReceiver, bound to a specific deployed contract. -func NewChildReceiverTransactor(address common.Address, transactor bind.ContractTransactor) (*ChildReceiverTransactor, error) { - contract, err := bindChildReceiver(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &ChildReceiverTransactor{contract: contract}, nil -} - -// NewChildReceiverFilterer creates a new log filterer instance of ChildReceiver, bound to a specific deployed contract. -func NewChildReceiverFilterer(address common.Address, filterer bind.ContractFilterer) (*ChildReceiverFilterer, error) { - contract, err := bindChildReceiver(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &ChildReceiverFilterer{contract: contract}, nil -} - -// bindChildReceiver binds a generic wrapper to an already deployed contract. -func bindChildReceiver(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(ChildReceiverABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_ChildReceiver *ChildReceiverRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _ChildReceiver.Contract.ChildReceiverCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_ChildReceiver *ChildReceiverRaw) Transfer(opts *bind.TransactOpts) (types.Transaction, error) { - return _ChildReceiver.Contract.ChildReceiverTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_ChildReceiver *ChildReceiverRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (types.Transaction, error) { - return _ChildReceiver.Contract.ChildReceiverTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_ChildReceiver *ChildReceiverCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _ChildReceiver.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_ChildReceiver *ChildReceiverTransactorRaw) Transfer(opts *bind.TransactOpts) (types.Transaction, error) { - return _ChildReceiver.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_ChildReceiver *ChildReceiverTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (types.Transaction, error) { - return _ChildReceiver.Contract.contract.Transact(opts, method, params...) -} - -// Senders is a free data retrieval call binding the contract method 0x982fb9d8. -// -// Solidity: function senders(address ) view returns(uint256) -func (_ChildReceiver *ChildReceiverCaller) Senders(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) { - var out []interface{} - err := _ChildReceiver.contract.Call(opts, &out, "senders", arg0) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Senders is a free data retrieval call binding the contract method 0x982fb9d8. -// -// Solidity: function senders(address ) view returns(uint256) -func (_ChildReceiver *ChildReceiverSession) Senders(arg0 common.Address) (*big.Int, error) { - return _ChildReceiver.Contract.Senders(&_ChildReceiver.CallOpts, arg0) -} - -// Senders is a free data retrieval call binding the contract method 0x982fb9d8. -// -// Solidity: function senders(address ) view returns(uint256) -func (_ChildReceiver *ChildReceiverCallerSession) Senders(arg0 common.Address) (*big.Int, error) { - return _ChildReceiver.Contract.Senders(&_ChildReceiver.CallOpts, arg0) -} - -// OnStateReceive is a paid mutator transaction binding the contract method 0x26c53bea. -// -// Solidity: function onStateReceive(uint256 , bytes data) returns() -func (_ChildReceiver *ChildReceiverTransactor) OnStateReceive(opts *bind.TransactOpts, arg0 *big.Int, data []byte) (types.Transaction, error) { - return _ChildReceiver.contract.Transact(opts, "onStateReceive", arg0, data) -} - -// OnStateReceive is a paid mutator transaction binding the contract method 0x26c53bea. -// -// Solidity: function onStateReceive(uint256 , bytes data) returns() -func (_ChildReceiver *ChildReceiverSession) OnStateReceive(arg0 *big.Int, data []byte) (types.Transaction, error) { - return _ChildReceiver.Contract.OnStateReceive(&_ChildReceiver.TransactOpts, arg0, data) -} - -// OnStateReceive is a paid mutator transaction binding the contract method 0x26c53bea. -// -// Solidity: function onStateReceive(uint256 , bytes data) returns() -func (_ChildReceiver *ChildReceiverTransactorSession) OnStateReceive(arg0 *big.Int, data []byte) (types.Transaction, error) { - return _ChildReceiver.Contract.OnStateReceive(&_ChildReceiver.TransactOpts, arg0, data) -} - -// ChildReceiverOnStateReceiveParams is an auto generated read-only Go binding of transcaction calldata params -type ChildReceiverOnStateReceiveParams struct { - Param_arg0 *big.Int - Param_data []byte -} - -// Parse OnStateReceive method from calldata of a transaction -// -// Solidity: function onStateReceive(uint256 , bytes data) returns() -func ParseChildReceiverOnStateReceiveParams(calldata []byte) (*ChildReceiverOnStateReceiveParams, error) { - if len(calldata) <= 4 { - return nil, fmt.Errorf("invalid calldata input") - } - - _abi, err := abi.JSON(strings.NewReader(ChildReceiverABI)) - if err != nil { - return nil, fmt.Errorf("failed to get abi of registry metadata: %w", err) - } - - out, err := _abi.Methods["onStateReceive"].Inputs.Unpack(calldata[4:]) - if err != nil { - return nil, fmt.Errorf("failed to unpack onStateReceive params data: %w", err) - } - - var paramsResult = new(ChildReceiverOnStateReceiveParams) - value := reflect.ValueOf(paramsResult).Elem() - - if value.NumField() != len(out) { - return nil, fmt.Errorf("failed to match calldata with param field number") - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - out1 := *abi.ConvertType(out[1], new([]byte)).(*[]byte) - - return &ChildReceiverOnStateReceiveParams{ - Param_arg0: out0, Param_data: out1, - }, nil -} - -// ChildReceiverReceivedIterator is returned from FilterReceived and is used to iterate over the raw logs and unpacked data for Received events raised by the ChildReceiver contract. -type ChildReceiverReceivedIterator struct { - Event *ChildReceiverReceived // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *ChildReceiverReceivedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(ChildReceiverReceived) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(ChildReceiverReceived) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *ChildReceiverReceivedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *ChildReceiverReceivedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// ChildReceiverReceived represents a Received event raised by the ChildReceiver contract. -type ChildReceiverReceived struct { - Source common.Address - Amount *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -func (_ChildReceiver *ChildReceiverFilterer) ReceivedEventID() common.Hash { - return common.HexToHash("0xf11e547d796cc64acdf758e7cee90439494fd886a19159454aa61e473fdbafef") -} - -// FilterReceived is a free log retrieval operation binding the contract event 0xf11e547d796cc64acdf758e7cee90439494fd886a19159454aa61e473fdbafef. -// -// Solidity: event received(address _source, uint256 _amount) -func (_ChildReceiver *ChildReceiverFilterer) FilterReceived(opts *bind.FilterOpts) (*ChildReceiverReceivedIterator, error) { - - logs, sub, err := _ChildReceiver.contract.FilterLogs(opts, "received") - if err != nil { - return nil, err - } - return &ChildReceiverReceivedIterator{contract: _ChildReceiver.contract, event: "received", logs: logs, sub: sub}, nil -} - -// WatchReceived is a free log subscription operation binding the contract event 0xf11e547d796cc64acdf758e7cee90439494fd886a19159454aa61e473fdbafef. -// -// Solidity: event received(address _source, uint256 _amount) -func (_ChildReceiver *ChildReceiverFilterer) WatchReceived(opts *bind.WatchOpts, sink chan<- *ChildReceiverReceived) (event.Subscription, error) { - - logs, sub, err := _ChildReceiver.contract.WatchLogs(opts, "received") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(ChildReceiverReceived) - if err := _ChildReceiver.contract.UnpackLog(event, "received", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseReceived is a log parse operation binding the contract event 0xf11e547d796cc64acdf758e7cee90439494fd886a19159454aa61e473fdbafef. -// -// Solidity: event received(address _source, uint256 _amount) -func (_ChildReceiver *ChildReceiverFilterer) ParseReceived(log types.Log) (*ChildReceiverReceived, error) { - event := new(ChildReceiverReceived) - if err := _ChildReceiver.contract.UnpackLog(event, "received", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/cmd/devnet/contracts/gen_childsender.go b/cmd/devnet/contracts/gen_childsender.go deleted file mode 100644 index edbecdaab44..00000000000 --- a/cmd/devnet/contracts/gen_childsender.go +++ /dev/null @@ -1,420 +0,0 @@ -// Code generated by abigen. DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package contracts - -import ( - "fmt" - "math/big" - "reflect" - "strings" - - ethereum "github.com/erigontech/erigon" - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon/execution/abi" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/execution/types" - "github.com/erigontech/erigon/p2p/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription - _ = fmt.Errorf - _ = reflect.ValueOf -) - -// ChildSenderABI is the input ABI used to generate the binding from. -const ChildSenderABI = "[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"childStateReceiver_\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"message\",\"type\":\"bytes\"}],\"name\":\"MessageSent\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"sendToRoot\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"sent\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"}]" - -// ChildSenderBin is the compiled bytecode used for deploying new contracts. -var ChildSenderBin = "0x608060405234801561001057600080fd5b506040516102b33803806102b383398101604081905261002f91610054565b600080546001600160a01b0319166001600160a01b0392909216919091179055610084565b60006020828403121561006657600080fd5b81516001600160a01b038116811461007d57600080fd5b9392505050565b610220806100936000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c80637bf786f81461003b5780638152e5021461006d575b600080fd5b61005b61004936600461012c565b60016020526000908152604090205481565b60405190815260200160405180910390f35b61008061007b36600461015c565b610082565b005b3360009081526001602052604090205461009c8282610175565b33600081815260016020908152604080832094909455905483516001600160a01b039091169181019190915291820152606081018390526100ee906080016040516020818303038152906040526100f2565b5050565b7f8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b03681604051610121919061019c565b60405180910390a150565b60006020828403121561013e57600080fd5b81356001600160a01b038116811461015557600080fd5b9392505050565b60006020828403121561016e57600080fd5b5035919050565b8082018082111561019657634e487b7160e01b600052601160045260246000fd5b92915050565b600060208083528351808285015260005b818110156101c9578581018301518582016040015282016101ad565b506000604082860101526040601f19601f830116850101925050509291505056fea26469706673582212202b5e4ad44349bb7aa70272a65afd939d928b9e646835ef4b7e65acff3d07b21364736f6c63430008140033" - -// DeployChildSender deploys a new Ethereum contract, binding an instance of ChildSender to it. -func DeployChildSender(auth *bind.TransactOpts, backend bind.ContractBackend, childStateReceiver_ common.Address) (common.Address, types.Transaction, *ChildSender, error) { - parsed, err := abi.JSON(strings.NewReader(ChildSenderABI)) - if err != nil { - return common.Address{}, nil, nil, err - } - - address, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(ChildSenderBin), backend, childStateReceiver_) - if err != nil { - return common.Address{}, nil, nil, err - } - return address, tx, &ChildSender{ChildSenderCaller: ChildSenderCaller{contract: contract}, ChildSenderTransactor: ChildSenderTransactor{contract: contract}, ChildSenderFilterer: ChildSenderFilterer{contract: contract}}, nil -} - -// ChildSender is an auto generated Go binding around an Ethereum contract. -type ChildSender struct { - ChildSenderCaller // Read-only binding to the contract - ChildSenderTransactor // Write-only binding to the contract - ChildSenderFilterer // Log filterer for contract events -} - -// ChildSenderCaller is an auto generated read-only Go binding around an Ethereum contract. -type ChildSenderCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ChildSenderTransactor is an auto generated write-only Go binding around an Ethereum contract. -type ChildSenderTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ChildSenderFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type ChildSenderFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// ChildSenderSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type ChildSenderSession struct { - Contract *ChildSender // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// ChildSenderCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type ChildSenderCallerSession struct { - Contract *ChildSenderCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// ChildSenderTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type ChildSenderTransactorSession struct { - Contract *ChildSenderTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// ChildSenderRaw is an auto generated low-level Go binding around an Ethereum contract. -type ChildSenderRaw struct { - Contract *ChildSender // Generic contract binding to access the raw methods on -} - -// ChildSenderCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type ChildSenderCallerRaw struct { - Contract *ChildSenderCaller // Generic read-only contract binding to access the raw methods on -} - -// ChildSenderTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type ChildSenderTransactorRaw struct { - Contract *ChildSenderTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewChildSender creates a new instance of ChildSender, bound to a specific deployed contract. -func NewChildSender(address common.Address, backend bind.ContractBackend) (*ChildSender, error) { - contract, err := bindChildSender(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &ChildSender{ChildSenderCaller: ChildSenderCaller{contract: contract}, ChildSenderTransactor: ChildSenderTransactor{contract: contract}, ChildSenderFilterer: ChildSenderFilterer{contract: contract}}, nil -} - -// NewChildSenderCaller creates a new read-only instance of ChildSender, bound to a specific deployed contract. -func NewChildSenderCaller(address common.Address, caller bind.ContractCaller) (*ChildSenderCaller, error) { - contract, err := bindChildSender(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &ChildSenderCaller{contract: contract}, nil -} - -// NewChildSenderTransactor creates a new write-only instance of ChildSender, bound to a specific deployed contract. -func NewChildSenderTransactor(address common.Address, transactor bind.ContractTransactor) (*ChildSenderTransactor, error) { - contract, err := bindChildSender(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &ChildSenderTransactor{contract: contract}, nil -} - -// NewChildSenderFilterer creates a new log filterer instance of ChildSender, bound to a specific deployed contract. -func NewChildSenderFilterer(address common.Address, filterer bind.ContractFilterer) (*ChildSenderFilterer, error) { - contract, err := bindChildSender(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &ChildSenderFilterer{contract: contract}, nil -} - -// bindChildSender binds a generic wrapper to an already deployed contract. -func bindChildSender(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(ChildSenderABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_ChildSender *ChildSenderRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _ChildSender.Contract.ChildSenderCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_ChildSender *ChildSenderRaw) Transfer(opts *bind.TransactOpts) (types.Transaction, error) { - return _ChildSender.Contract.ChildSenderTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_ChildSender *ChildSenderRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (types.Transaction, error) { - return _ChildSender.Contract.ChildSenderTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_ChildSender *ChildSenderCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _ChildSender.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_ChildSender *ChildSenderTransactorRaw) Transfer(opts *bind.TransactOpts) (types.Transaction, error) { - return _ChildSender.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_ChildSender *ChildSenderTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (types.Transaction, error) { - return _ChildSender.Contract.contract.Transact(opts, method, params...) -} - -// Sent is a free data retrieval call binding the contract method 0x7bf786f8. -// -// Solidity: function sent(address ) view returns(uint256) -func (_ChildSender *ChildSenderCaller) Sent(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) { - var out []interface{} - err := _ChildSender.contract.Call(opts, &out, "sent", arg0) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Sent is a free data retrieval call binding the contract method 0x7bf786f8. -// -// Solidity: function sent(address ) view returns(uint256) -func (_ChildSender *ChildSenderSession) Sent(arg0 common.Address) (*big.Int, error) { - return _ChildSender.Contract.Sent(&_ChildSender.CallOpts, arg0) -} - -// Sent is a free data retrieval call binding the contract method 0x7bf786f8. -// -// Solidity: function sent(address ) view returns(uint256) -func (_ChildSender *ChildSenderCallerSession) Sent(arg0 common.Address) (*big.Int, error) { - return _ChildSender.Contract.Sent(&_ChildSender.CallOpts, arg0) -} - -// SendToRoot is a paid mutator transaction binding the contract method 0x8152e502. -// -// Solidity: function sendToRoot(uint256 amount) returns() -func (_ChildSender *ChildSenderTransactor) SendToRoot(opts *bind.TransactOpts, amount *big.Int) (types.Transaction, error) { - return _ChildSender.contract.Transact(opts, "sendToRoot", amount) -} - -// SendToRoot is a paid mutator transaction binding the contract method 0x8152e502. -// -// Solidity: function sendToRoot(uint256 amount) returns() -func (_ChildSender *ChildSenderSession) SendToRoot(amount *big.Int) (types.Transaction, error) { - return _ChildSender.Contract.SendToRoot(&_ChildSender.TransactOpts, amount) -} - -// SendToRoot is a paid mutator transaction binding the contract method 0x8152e502. -// -// Solidity: function sendToRoot(uint256 amount) returns() -func (_ChildSender *ChildSenderTransactorSession) SendToRoot(amount *big.Int) (types.Transaction, error) { - return _ChildSender.Contract.SendToRoot(&_ChildSender.TransactOpts, amount) -} - -// ChildSenderSendToRootParams is an auto generated read-only Go binding of transcaction calldata params -type ChildSenderSendToRootParams struct { - Param_amount *big.Int -} - -// Parse SendToRoot method from calldata of a transaction -// -// Solidity: function sendToRoot(uint256 amount) returns() -func ParseChildSenderSendToRootParams(calldata []byte) (*ChildSenderSendToRootParams, error) { - if len(calldata) <= 4 { - return nil, fmt.Errorf("invalid calldata input") - } - - _abi, err := abi.JSON(strings.NewReader(ChildSenderABI)) - if err != nil { - return nil, fmt.Errorf("failed to get abi of registry metadata: %w", err) - } - - out, err := _abi.Methods["sendToRoot"].Inputs.Unpack(calldata[4:]) - if err != nil { - return nil, fmt.Errorf("failed to unpack sendToRoot params data: %w", err) - } - - var paramsResult = new(ChildSenderSendToRootParams) - value := reflect.ValueOf(paramsResult).Elem() - - if value.NumField() != len(out) { - return nil, fmt.Errorf("failed to match calldata with param field number") - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return &ChildSenderSendToRootParams{ - Param_amount: out0, - }, nil -} - -// ChildSenderMessageSentIterator is returned from FilterMessageSent and is used to iterate over the raw logs and unpacked data for MessageSent events raised by the ChildSender contract. -type ChildSenderMessageSentIterator struct { - Event *ChildSenderMessageSent // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *ChildSenderMessageSentIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(ChildSenderMessageSent) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(ChildSenderMessageSent) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *ChildSenderMessageSentIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *ChildSenderMessageSentIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// ChildSenderMessageSent represents a MessageSent event raised by the ChildSender contract. -type ChildSenderMessageSent struct { - Message []byte - Raw types.Log // Blockchain specific contextual infos -} - -func (_ChildSender *ChildSenderFilterer) MessageSentEventID() common.Hash { - return common.HexToHash("0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036") -} - -// FilterMessageSent is a free log retrieval operation binding the contract event 0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036. -// -// Solidity: event MessageSent(bytes message) -func (_ChildSender *ChildSenderFilterer) FilterMessageSent(opts *bind.FilterOpts) (*ChildSenderMessageSentIterator, error) { - - logs, sub, err := _ChildSender.contract.FilterLogs(opts, "MessageSent") - if err != nil { - return nil, err - } - return &ChildSenderMessageSentIterator{contract: _ChildSender.contract, event: "MessageSent", logs: logs, sub: sub}, nil -} - -// WatchMessageSent is a free log subscription operation binding the contract event 0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036. -// -// Solidity: event MessageSent(bytes message) -func (_ChildSender *ChildSenderFilterer) WatchMessageSent(opts *bind.WatchOpts, sink chan<- *ChildSenderMessageSent) (event.Subscription, error) { - - logs, sub, err := _ChildSender.contract.WatchLogs(opts, "MessageSent") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(ChildSenderMessageSent) - if err := _ChildSender.contract.UnpackLog(event, "MessageSent", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseMessageSent is a log parse operation binding the contract event 0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036. -// -// Solidity: event MessageSent(bytes message) -func (_ChildSender *ChildSenderFilterer) ParseMessageSent(log types.Log) (*ChildSenderMessageSent, error) { - event := new(ChildSenderMessageSent) - if err := _ChildSender.contract.UnpackLog(event, "MessageSent", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/cmd/devnet/contracts/gen_faucet.go b/cmd/devnet/contracts/gen_faucet.go deleted file mode 100644 index 81f4fe7f66e..00000000000 --- a/cmd/devnet/contracts/gen_faucet.go +++ /dev/null @@ -1,614 +0,0 @@ -// Code generated by abigen. DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package contracts - -import ( - "fmt" - "math/big" - "reflect" - "strings" - - ethereum "github.com/erigontech/erigon" - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon/execution/abi" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/execution/types" - "github.com/erigontech/erigon/p2p/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription - _ = fmt.Errorf - _ = reflect.ValueOf -) - -// FaucetABI is the input ABI used to generate the binding from. -const FaucetABI = "[{\"inputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"_source\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"received\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"_destination\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"sent\",\"type\":\"event\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"destinations\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"addresspayable\",\"name\":\"_destination\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"_requested\",\"type\":\"uint256\"}],\"name\":\"send\",\"outputs\":[],\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"sources\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"stateMutability\":\"payable\",\"type\":\"receive\"}]" - -// FaucetBin is the compiled bytecode used for deploying new contracts. -var FaucetBin = "0x608060405234801561001057600080fd5b506102ea806100206000396000f3fe6080604052600436106100385760003560e01c806359c02c37146100a0578063b750bdde146100df578063d0679d341461010c57600080fd5b3661009b57336000908152602081905260408120805434929061005c908490610225565b9091555050604080513381523460208201527ff11e547d796cc64acdf758e7cee90439494fd886a19159454aa61e473fdbafef910160405180910390a1005b600080fd5b3480156100ac57600080fd5b506100cd6100bb366004610264565b60016020526000908152604090205481565b60405190815260200160405180910390f35b3480156100eb57600080fd5b506100cd6100fa366004610264565b60006020819052908152604090205481565b61011f61011a366004610288565b610121565b005b4760000361012d575050565b600081471115610176575060405181906001600160a01b0384169082156108fc029083906000818181858888f19350505050158015610170573d6000803e3d6000fd5b506101b1565b5060405147906001600160a01b0384169082156108fc029083906000818181858888f193505050501580156101af573d6000803e3d6000fd5b505b6001600160a01b038316600090815260016020526040812080548392906101d9908490610225565b9091555050604080516001600160a01b0385168152602081018390527f3bcb2e664d8f57273201bc888e82d6549f8308a52a9fcd7702b2ea8387f769a9910160405180910390a1505050565b8082018082111561024657634e487b7160e01b600052601160045260246000fd5b92915050565b6001600160a01b038116811461026157600080fd5b50565b60006020828403121561027657600080fd5b81356102818161024c565b9392505050565b6000806040838503121561029b57600080fd5b82356102a68161024c565b94602093909301359350505056fea2646970667358221220ac81b3f12efbe2860b7a5f00b56a253c6661d9ad6df22e642da3546e0015e9d664736f6c63430008140033" - -// DeployFaucet deploys a new Ethereum contract, binding an instance of Faucet to it. -func DeployFaucet(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, types.Transaction, *Faucet, error) { - parsed, err := abi.JSON(strings.NewReader(FaucetABI)) - if err != nil { - return common.Address{}, nil, nil, err - } - - address, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(FaucetBin), backend) - if err != nil { - return common.Address{}, nil, nil, err - } - return address, tx, &Faucet{FaucetCaller: FaucetCaller{contract: contract}, FaucetTransactor: FaucetTransactor{contract: contract}, FaucetFilterer: FaucetFilterer{contract: contract}}, nil -} - -// Faucet is an auto generated Go binding around an Ethereum contract. -type Faucet struct { - FaucetCaller // Read-only binding to the contract - FaucetTransactor // Write-only binding to the contract - FaucetFilterer // Log filterer for contract events -} - -// FaucetCaller is an auto generated read-only Go binding around an Ethereum contract. -type FaucetCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// FaucetTransactor is an auto generated write-only Go binding around an Ethereum contract. -type FaucetTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// FaucetFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type FaucetFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// FaucetSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type FaucetSession struct { - Contract *Faucet // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// FaucetCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type FaucetCallerSession struct { - Contract *FaucetCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// FaucetTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type FaucetTransactorSession struct { - Contract *FaucetTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// FaucetRaw is an auto generated low-level Go binding around an Ethereum contract. -type FaucetRaw struct { - Contract *Faucet // Generic contract binding to access the raw methods on -} - -// FaucetCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type FaucetCallerRaw struct { - Contract *FaucetCaller // Generic read-only contract binding to access the raw methods on -} - -// FaucetTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type FaucetTransactorRaw struct { - Contract *FaucetTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewFaucet creates a new instance of Faucet, bound to a specific deployed contract. -func NewFaucet(address common.Address, backend bind.ContractBackend) (*Faucet, error) { - contract, err := bindFaucet(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Faucet{FaucetCaller: FaucetCaller{contract: contract}, FaucetTransactor: FaucetTransactor{contract: contract}, FaucetFilterer: FaucetFilterer{contract: contract}}, nil -} - -// NewFaucetCaller creates a new read-only instance of Faucet, bound to a specific deployed contract. -func NewFaucetCaller(address common.Address, caller bind.ContractCaller) (*FaucetCaller, error) { - contract, err := bindFaucet(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &FaucetCaller{contract: contract}, nil -} - -// NewFaucetTransactor creates a new write-only instance of Faucet, bound to a specific deployed contract. -func NewFaucetTransactor(address common.Address, transactor bind.ContractTransactor) (*FaucetTransactor, error) { - contract, err := bindFaucet(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &FaucetTransactor{contract: contract}, nil -} - -// NewFaucetFilterer creates a new log filterer instance of Faucet, bound to a specific deployed contract. -func NewFaucetFilterer(address common.Address, filterer bind.ContractFilterer) (*FaucetFilterer, error) { - contract, err := bindFaucet(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &FaucetFilterer{contract: contract}, nil -} - -// bindFaucet binds a generic wrapper to an already deployed contract. -func bindFaucet(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(FaucetABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Faucet *FaucetRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Faucet.Contract.FaucetCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Faucet *FaucetRaw) Transfer(opts *bind.TransactOpts) (types.Transaction, error) { - return _Faucet.Contract.FaucetTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Faucet *FaucetRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (types.Transaction, error) { - return _Faucet.Contract.FaucetTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Faucet *FaucetCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Faucet.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Faucet *FaucetTransactorRaw) Transfer(opts *bind.TransactOpts) (types.Transaction, error) { - return _Faucet.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Faucet *FaucetTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (types.Transaction, error) { - return _Faucet.Contract.contract.Transact(opts, method, params...) -} - -// Destinations is a free data retrieval call binding the contract method 0x59c02c37. -// -// Solidity: function destinations(address ) view returns(uint256) -func (_Faucet *FaucetCaller) Destinations(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) { - var out []interface{} - err := _Faucet.contract.Call(opts, &out, "destinations", arg0) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Destinations is a free data retrieval call binding the contract method 0x59c02c37. -// -// Solidity: function destinations(address ) view returns(uint256) -func (_Faucet *FaucetSession) Destinations(arg0 common.Address) (*big.Int, error) { - return _Faucet.Contract.Destinations(&_Faucet.CallOpts, arg0) -} - -// Destinations is a free data retrieval call binding the contract method 0x59c02c37. -// -// Solidity: function destinations(address ) view returns(uint256) -func (_Faucet *FaucetCallerSession) Destinations(arg0 common.Address) (*big.Int, error) { - return _Faucet.Contract.Destinations(&_Faucet.CallOpts, arg0) -} - -// Sources is a free data retrieval call binding the contract method 0xb750bdde. -// -// Solidity: function sources(address ) view returns(uint256) -func (_Faucet *FaucetCaller) Sources(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) { - var out []interface{} - err := _Faucet.contract.Call(opts, &out, "sources", arg0) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Sources is a free data retrieval call binding the contract method 0xb750bdde. -// -// Solidity: function sources(address ) view returns(uint256) -func (_Faucet *FaucetSession) Sources(arg0 common.Address) (*big.Int, error) { - return _Faucet.Contract.Sources(&_Faucet.CallOpts, arg0) -} - -// Sources is a free data retrieval call binding the contract method 0xb750bdde. -// -// Solidity: function sources(address ) view returns(uint256) -func (_Faucet *FaucetCallerSession) Sources(arg0 common.Address) (*big.Int, error) { - return _Faucet.Contract.Sources(&_Faucet.CallOpts, arg0) -} - -// Send is a paid mutator transaction binding the contract method 0xd0679d34. -// -// Solidity: function send(address _destination, uint256 _requested) payable returns() -func (_Faucet *FaucetTransactor) Send(opts *bind.TransactOpts, _destination common.Address, _requested *big.Int) (types.Transaction, error) { - return _Faucet.contract.Transact(opts, "send", _destination, _requested) -} - -// Send is a paid mutator transaction binding the contract method 0xd0679d34. -// -// Solidity: function send(address _destination, uint256 _requested) payable returns() -func (_Faucet *FaucetSession) Send(_destination common.Address, _requested *big.Int) (types.Transaction, error) { - return _Faucet.Contract.Send(&_Faucet.TransactOpts, _destination, _requested) -} - -// Send is a paid mutator transaction binding the contract method 0xd0679d34. -// -// Solidity: function send(address _destination, uint256 _requested) payable returns() -func (_Faucet *FaucetTransactorSession) Send(_destination common.Address, _requested *big.Int) (types.Transaction, error) { - return _Faucet.Contract.Send(&_Faucet.TransactOpts, _destination, _requested) -} - -// FaucetSendParams is an auto generated read-only Go binding of transcaction calldata params -type FaucetSendParams struct { - Param__destination common.Address - Param__requested *big.Int -} - -// Parse Send method from calldata of a transaction -// -// Solidity: function send(address _destination, uint256 _requested) payable returns() -func ParseFaucetSendParams(calldata []byte) (*FaucetSendParams, error) { - if len(calldata) <= 4 { - return nil, fmt.Errorf("invalid calldata input") - } - - _abi, err := abi.JSON(strings.NewReader(FaucetABI)) - if err != nil { - return nil, fmt.Errorf("failed to get abi of registry metadata: %w", err) - } - - out, err := _abi.Methods["send"].Inputs.Unpack(calldata[4:]) - if err != nil { - return nil, fmt.Errorf("failed to unpack send params data: %w", err) - } - - var paramsResult = new(FaucetSendParams) - value := reflect.ValueOf(paramsResult).Elem() - - if value.NumField() != len(out) { - return nil, fmt.Errorf("failed to match calldata with param field number") - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - out1 := *abi.ConvertType(out[1], new(*big.Int)).(**big.Int) - - return &FaucetSendParams{ - Param__destination: out0, Param__requested: out1, - }, nil -} - -// Receive is a paid mutator transaction binding the contract receive function. -// -// Solidity: receive() payable returns() -func (_Faucet *FaucetTransactor) Receive(opts *bind.TransactOpts) (types.Transaction, error) { - return _Faucet.contract.RawTransact(opts, nil) // calldata is disallowed for receive function -} - -// Receive is a paid mutator transaction binding the contract receive function. -// -// Solidity: receive() payable returns() -func (_Faucet *FaucetSession) Receive() (types.Transaction, error) { - return _Faucet.Contract.Receive(&_Faucet.TransactOpts) -} - -// Receive is a paid mutator transaction binding the contract receive function. -// -// Solidity: receive() payable returns() -func (_Faucet *FaucetTransactorSession) Receive() (types.Transaction, error) { - return _Faucet.Contract.Receive(&_Faucet.TransactOpts) -} - -// FaucetReceivedIterator is returned from FilterReceived and is used to iterate over the raw logs and unpacked data for Received events raised by the Faucet contract. -type FaucetReceivedIterator struct { - Event *FaucetReceived // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *FaucetReceivedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(FaucetReceived) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(FaucetReceived) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *FaucetReceivedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *FaucetReceivedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// FaucetReceived represents a Received event raised by the Faucet contract. -type FaucetReceived struct { - Source common.Address - Amount *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -func (_Faucet *FaucetFilterer) ReceivedEventID() common.Hash { - return common.HexToHash("0xf11e547d796cc64acdf758e7cee90439494fd886a19159454aa61e473fdbafef") -} - -// FilterReceived is a free log retrieval operation binding the contract event 0xf11e547d796cc64acdf758e7cee90439494fd886a19159454aa61e473fdbafef. -// -// Solidity: event received(address _source, uint256 _amount) -func (_Faucet *FaucetFilterer) FilterReceived(opts *bind.FilterOpts) (*FaucetReceivedIterator, error) { - - logs, sub, err := _Faucet.contract.FilterLogs(opts, "received") - if err != nil { - return nil, err - } - return &FaucetReceivedIterator{contract: _Faucet.contract, event: "received", logs: logs, sub: sub}, nil -} - -// WatchReceived is a free log subscription operation binding the contract event 0xf11e547d796cc64acdf758e7cee90439494fd886a19159454aa61e473fdbafef. -// -// Solidity: event received(address _source, uint256 _amount) -func (_Faucet *FaucetFilterer) WatchReceived(opts *bind.WatchOpts, sink chan<- *FaucetReceived) (event.Subscription, error) { - - logs, sub, err := _Faucet.contract.WatchLogs(opts, "received") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(FaucetReceived) - if err := _Faucet.contract.UnpackLog(event, "received", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseReceived is a log parse operation binding the contract event 0xf11e547d796cc64acdf758e7cee90439494fd886a19159454aa61e473fdbafef. -// -// Solidity: event received(address _source, uint256 _amount) -func (_Faucet *FaucetFilterer) ParseReceived(log types.Log) (*FaucetReceived, error) { - event := new(FaucetReceived) - if err := _Faucet.contract.UnpackLog(event, "received", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// FaucetSentIterator is returned from FilterSent and is used to iterate over the raw logs and unpacked data for Sent events raised by the Faucet contract. -type FaucetSentIterator struct { - Event *FaucetSent // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *FaucetSentIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(FaucetSent) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(FaucetSent) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *FaucetSentIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *FaucetSentIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// FaucetSent represents a Sent event raised by the Faucet contract. -type FaucetSent struct { - Destination common.Address - Amount *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -func (_Faucet *FaucetFilterer) SentEventID() common.Hash { - return common.HexToHash("0x3bcb2e664d8f57273201bc888e82d6549f8308a52a9fcd7702b2ea8387f769a9") -} - -// FilterSent is a free log retrieval operation binding the contract event 0x3bcb2e664d8f57273201bc888e82d6549f8308a52a9fcd7702b2ea8387f769a9. -// -// Solidity: event sent(address _destination, uint256 _amount) -func (_Faucet *FaucetFilterer) FilterSent(opts *bind.FilterOpts) (*FaucetSentIterator, error) { - - logs, sub, err := _Faucet.contract.FilterLogs(opts, "sent") - if err != nil { - return nil, err - } - return &FaucetSentIterator{contract: _Faucet.contract, event: "sent", logs: logs, sub: sub}, nil -} - -// WatchSent is a free log subscription operation binding the contract event 0x3bcb2e664d8f57273201bc888e82d6549f8308a52a9fcd7702b2ea8387f769a9. -// -// Solidity: event sent(address _destination, uint256 _amount) -func (_Faucet *FaucetFilterer) WatchSent(opts *bind.WatchOpts, sink chan<- *FaucetSent) (event.Subscription, error) { - - logs, sub, err := _Faucet.contract.WatchLogs(opts, "sent") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(FaucetSent) - if err := _Faucet.contract.UnpackLog(event, "sent", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseSent is a log parse operation binding the contract event 0x3bcb2e664d8f57273201bc888e82d6549f8308a52a9fcd7702b2ea8387f769a9. -// -// Solidity: event sent(address _destination, uint256 _amount) -func (_Faucet *FaucetFilterer) ParseSent(log types.Log) (*FaucetSent, error) { - event := new(FaucetSent) - if err := _Faucet.contract.UnpackLog(event, "sent", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/cmd/devnet/contracts/gen_rootreceiver.go b/cmd/devnet/contracts/gen_rootreceiver.go deleted file mode 100644 index 101cbf6c63e..00000000000 --- a/cmd/devnet/contracts/gen_rootreceiver.go +++ /dev/null @@ -1,514 +0,0 @@ -// Code generated by abigen. DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package contracts - -import ( - "fmt" - "math/big" - "reflect" - "strings" - - ethereum "github.com/erigontech/erigon" - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon/execution/abi" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/execution/types" - "github.com/erigontech/erigon/p2p/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription - _ = fmt.Errorf - _ = reflect.ValueOf -) - -// RootReceiverABI is the input ABI used to generate the binding from. -const RootReceiverABI = "[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"_checkpointManager\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"_source\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"received\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"SEND_MESSAGE_EVENT_SIG\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"checkpointManager\",\"outputs\":[{\"internalType\":\"contractICheckpointManager\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"processedExits\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"inputData\",\"type\":\"bytes\"}],\"name\":\"receiveMessage\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"senders\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"}]" - -// RootReceiverBin is the compiled bytecode used for deploying new contracts. -var RootReceiverBin = "0x608060405234801561001057600080fd5b50604051611ed1380380611ed183398101604081905261002f91610054565b600080546001600160a01b0319166001600160a01b0392909216919091179055610084565b60006020828403121561006657600080fd5b81516001600160a01b038116811461007d57600080fd5b9392505050565b611e3e806100936000396000f3fe608060405234801561001057600080fd5b50600436106100575760003560e01c80630e387de61461005c578063607f2d4214610096578063982fb9d8146100c9578063c0857ba0146100e9578063f953cec714610114575b600080fd5b6100837f8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b03681565b6040519081526020015b60405180910390f35b6100b96100a436600461196a565b60016020526000908152604090205460ff1681565b604051901515815260200161008d565b6100836100d736600461199b565b60026020526000908152604090205481565b6000546100fc906001600160a01b031681565b6040516001600160a01b03909116815260200161008d565b610127610122366004611a25565b610129565b005b60008061013583610148565b9150915061014382826103cf565b505050565b600060606000610157846104bb565b905060006101648261051a565b9050600061017183610549565b905060008161017f84610572565b6101888661072e565b60405160200161019a93929190611ac8565b60408051601f1981840301815291815281516020928301206000818152600190935291205490915060ff16156102235760405162461bcd60e51b8152602060048201526024808201527f4678526f6f7454756e6e656c3a20455849545f414c52454144595f50524f434560448201526314d4d15160e21b60648201526084015b60405180910390fd5b60008181526001602081905260408220805460ff191690911790556102478561074a565b9050600061025482610893565b9050600061026187610923565b9050610281610271846020015190565b8761027b8a61093f565b8461095b565b6102d95760405162461bcd60e51b815260206004820152602360248201527f4678526f6f7454756e6e656c3a20494e56414c49445f524543454950545f505260448201526227a7a360e91b606482015260840161021a565b610307856102e689610c28565b6102ef8a610c44565b846102f98c610c60565b6103028d610c7c565b610c98565b600061031283610db2565b90507f8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036610348610343836000610dee565b610e26565b146103955760405162461bcd60e51b815260206004820152601f60248201527f4678526f6f7454756e6e656c3a20494e56414c49445f5349474e415455524500604482015260640161021a565b60006103a084610ea1565b8060200190518101906103b39190611af5565b90506103be84610ebd565b9c909b509950505050505050505050565b6000806000838060200190518101906103e89190611b6b565b919450925090506001600160a01b038316301461043a5760405162461bcd60e51b815260206004820152601060248201526f24b73b30b634b2103932b1b2b4bb32b960811b604482015260640161021a565b6001600160a01b03821660009081526002602052604090205461045d8282611bc4565b6001600160a01b0384166000818152600260209081526040918290209390935580519182529181018490527ff11e547d796cc64acdf758e7cee90439494fd886a19159454aa61e473fdbafef910160405180910390a1505050505050565b60408051602081019091526060815260006105056105008460408051808201825260008082526020918201528151808301909252825182529182019181019190915290565b610ee6565b60408051602081019091529081529392505050565b6060610543826000015160088151811061053657610536611bd7565b6020026020010151610ffb565b92915050565b6000610543826000015160028151811061056557610565611bd7565b6020026020010151610e26565b604080516020810190915260008152815160609190156105435760008061059a600086611097565b60f81c905060018114806105b157508060ff166003145b15610658576001855160026105c69190611bed565b6105d09190611c04565b6001600160401b038111156105e7576105e76119b8565b6040519080825280601f01601f191660200182016040528015610611576020820181803683370190505b5092506000610621600187611097565b9050808460008151811061063757610637611bd7565b60200101906001600160f81b031916908160001a90535060019250506106bb565b6002855160026106689190611bed565b6106729190611c04565b6001600160401b03811115610689576106896119b8565b6040519080825280601f01601f1916602001820160405280156106b3576020820181803683370190505b509250600091505b60ff82165b8351811015610725576106ea6106d960ff851683611c04565b6106e4906002611bc4565b87611097565b8482815181106106fc576106fc611bd7565b60200101906001600160f81b031916908160001a9053508061071d81611c17565b9150506106c0565b50505092915050565b6000610543826000015160098151811061056557610565611bd7565b61076e60405180606001604052806060815260200160608152602001600081525090565b610788826000015160068151811061053657610536611bd7565b6020828101829052604080518082018252600080825290830152805180820190915282518152918101908201526107be81611118565b156107d3576107cc81610ee6565b825261087f565b602082015180516000906107e990600190611c04565b6001600160401b03811115610800576108006119b8565b6040519080825280601f01601f19166020018201604052801561082a576020820181803683370190505b50905060008083602101915082602001905061084882828551611153565b60408051808201825260008082526020918201528151808301909252845182528085019082015261087890610ee6565b8652505050505b6108888361072e565b604083015250919050565b6040805160808101825260009181018281526060808301939093528152602081019190915260006108e183600001516003815181106108d4576108d4611bd7565b6020026020010151610ee6565b8360400151815181106108f6576108f6611bd7565b60200260200101519050604051806040016040528082815260200161091a83610ee6565b90529392505050565b6000610543826000015160058151811061056557610565611bd7565b6060610543826000015160078151811061053657610536611bd7565b60008061098f8460408051808201825260008082526020918201528151808301909252825182529182019181019190915290565b9050600061099c826111de565b9050606080856000806109ae8b610572565b905080516000036109c9576000975050505050505050610c20565b60005b8651811015610c175781518311156109ef57600098505050505050505050610c20565b610a11878281518110610a0457610a04611bd7565b60200260200101516112e8565b955085805190602001208414610a3257600098505050505050505050610c20565b610a54878281518110610a4757610a47611bd7565b60200260200101516111de565b94508451601103610b335781518303610ac0578c80519060200120610a9286601081518110610a8557610a85611bd7565b6020026020010151611366565b8051906020012003610aaf57600198505050505050505050610c20565b600098505050505050505050610c20565b6000828481518110610ad457610ad4611bd7565b016020015160f81c90506010811115610af95760009950505050505050505050610c20565b610b1e868260ff1681518110610b1157610b11611bd7565b6020026020010151611402565b9450610b2b600185611bc4565b935050610c05565b8451600203610aaf576000610b5e610b5787600081518110610a8557610a85611bd7565b8486611430565b8351909150610b6d8286611bc4565b03610bc0578d80519060200120610b9087600181518110610a8557610a85611bd7565b8051906020012003610bae5760019950505050505050505050610c20565b60009950505050505050505050610c20565b80600003610bda5760009950505050505050505050610c20565b610be48185611bc4565b9350610bfc86600181518110610b1157610b11611bd7565b9450610c059050565b80610c0f81611c17565b9150506109cc565b50505050505050505b949350505050565b6000610543826000015160038151811061056557610565611bd7565b6000610543826000015160048151811061056557610565611bd7565b6000610543826000015160008151811061056557610565611bd7565b6060610543826000015160018151811061053657610536611bd7565b600080546040516320a9cea560e11b81526004810185905282916001600160a01b0316906341539d4a9060240160a060405180830381865afa158015610ce2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d069190611c30565b50505091509150610d5c8189610d1c9190611c04565b6040805160208082018d90528183018c9052606082018b905260808083018b90528351808403909101815260a09092019092528051910120908486611537565b610da85760405162461bcd60e51b815260206004820152601c60248201527f4678526f6f7454756e6e656c3a20494e56414c49445f48454144455200000000604482015260640161021a565b5050505050505050565b6040805160208101909152606081526040518060200160405280610de684602001516001815181106108d4576108d4611bd7565b905292915050565b60408051808201909152600080825260208201528251805183908110610e1657610e16611bd7565b6020026020010151905092915050565b805160009015801590610e3b57508151602110155b610e4457600080fd5b6000610e53836020015161169f565b90506000818460000151610e679190611c04565b9050600080838660200151610e7c9190611bc4565b9050805191506020831015610e9857826020036101000a820491505b50949350505050565b6060610543826020015160028151811061053657610536611bd7565b60006105438260200151600081518110610ed957610ed9611bd7565b6020026020010151611721565b6060610ef182611118565b610efa57600080fd5b6000610f058361173b565b90506000816001600160401b03811115610f2157610f216119b8565b604051908082528060200260200182016040528015610f6657816020015b6040805180820190915260008082526020820152815260200190600190039081610f3f5790505b5090506000610f78856020015161169f565b8560200151610f879190611bc4565b90506000805b84811015610ff057610f9e836117c0565b9150604051806040016040528083815260200184815250848281518110610fc757610fc7611bd7565b6020908102919091010152610fdc8284611bc4565b925080610fe881611c17565b915050610f8d565b509195945050505050565b805160609061100957600080fd5b6000611018836020015161169f565b9050600081846000015161102c9190611c04565b90506000816001600160401b03811115611048576110486119b8565b6040519080825280601f01601f191660200182016040528015611072576020820181803683370190505b5090506000816020019050610e988487602001516110909190611bc4565b8285611864565b60006110a4600284611c93565b156110de576010826110b7600286611ca7565b815181106110c7576110c7611bd7565b01602001516110d9919060f81c611cbb565b61110e565b6010826110ec600286611ca7565b815181106110fc576110fc611bd7565b016020015161110e919060f81c611cdd565b60f81b9392505050565b8051600090810361112b57506000919050565b6020820151805160001a9060c0821015611149575060009392505050565b5060019392505050565b8060000361116057505050565b602081106111985782518252611177602084611bc4565b9250611184602083611bc4565b9150611191602082611c04565b9050611160565b806000036111a557505050565b600060016111b4836020611c04565b6111c090610100611de3565b6111ca9190611c04565b935183518516941916939093179091525050565b60606111e982611118565b6111f257600080fd5b60006111fd836118a9565b90506000816001600160401b03811115611219576112196119b8565b60405190808252806020026020018201604052801561125e57816020015b60408051808201909152600080825260208201528152602001906001900390816112375790505b5090506000611270856020015161169f565b856020015161127f9190611bc4565b90506000805b84811015610ff057611296836117c0565b91506040518060400160405280838152602001848152508482815181106112bf576112bf611bd7565b60209081029190910101526112d48284611bc4565b9250806112e081611c17565b915050611285565b6060600082600001516001600160401b03811115611308576113086119b8565b6040519080825280601f01601f191660200182016040528015611332576020820181803683370190505b50905080516000036113445792915050565b600081602001905061135f8460200151828660000151611925565b5092915050565b805160609061137457600080fd5b6000611383836020015161169f565b905060008184600001516113979190611c04565b90506000816001600160401b038111156113b3576113b36119b8565b6040519080825280601f01601f1916602001820160405280156113dd576020820181803683370190505b5090506000816020019050610e988487602001516113fb9190611bc4565b8285611925565b805160009060211461141357600080fd5b600080836020015160016114279190611bc4565b51949350505050565b6000808061143d86610572565b9050600081516001600160401b0381111561145a5761145a6119b8565b6040519080825280601f01601f191660200182016040528015611484576020820181803683370190505b509050845b82516114959087611bc4565b8110156115085760008782815181106114b0576114b0611bd7565b01602001516001600160f81b031916905080836114cd8985611c04565b815181106114dd576114dd611bd7565b60200101906001600160f81b031916908160001a90535050808061150090611c17565b915050611489565b508080519060200120828051906020012003611527578151925061152c565b600092505b509095945050505050565b6000602082516115479190611c93565b1561158b5760405162461bcd60e51b8152602060048201526014602482015273092dcecc2d8d2c840e0e4dedecc40d8cadccee8d60631b604482015260640161021a565b60006020835161159b9190611ca7565b90506115a8816002611de3565b85106115ee5760405162461bcd60e51b81526020600482015260156024820152744c65616620696e64657820697320746f6f2062696760581b604482015260640161021a565b60008660205b855181116116915785810151925061160d600289611c93565b600003611645576040805160208101849052908101849052606001604051602081830303815290604052805190602001209150611672565b60408051602081018590529081018390526060016040516020818303038152906040528051906020012091505b61167d600289611ca7565b975061168a602082611bc4565b90506115f4565b509094149695505050505050565b8051600090811a60808110156116b85750600092915050565b60b88110806116d3575060c081108015906116d3575060f881105b156116e15750600192915050565b60c0811015611715576116f6600160b8611def565b6117039060ff1682611c04565b61170e906001611bc4565b9392505050565b6116f6600160f8611def565b805160009060151461173257600080fd5b61054382610e26565b8051600090810361174e57506000919050565b60008061175e846020015161169f565b846020015161176d9190611bc4565b90506000846000015185602001516117859190611bc4565b90505b808210156117b757611799826117c0565b6117a39083611bc4565b9150826117af81611c17565b935050611788565b50909392505050565b80516000908190811a60808110156117db576001915061135f565b60b8811015611801576117ef608082611c04565b6117fa906001611bc4565b915061135f565b60c081101561182e5760b78103600185019450806020036101000a8551046001820181019350505061135f565b60f8811015611842576117ef60c082611c04565b60019390930151602084900360f7016101000a900490920160f5190192915050565b8060000361187157505050565b602081106111985782518252611888602084611bc4565b9250611895602083611bc4565b91506118a2602082611c04565b9050611871565b805160009081036118bc57506000919050565b6000806118cc846020015161169f565b84602001516118db9190611bc4565b90506000846000015185602001516118f39190611bc4565b90505b808210156117b757611907826117c0565b6119119083611bc4565b91508261191d81611c17565b9350506118f6565b8060000361193257505050565b602081106111985782518252611949602084611bc4565b9250611956602083611bc4565b9150611963602082611c04565b9050611932565b60006020828403121561197c57600080fd5b5035919050565b6001600160a01b038116811461199857600080fd5b50565b6000602082840312156119ad57600080fd5b813561170e81611983565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f191681016001600160401b03811182821017156119f6576119f66119b8565b604052919050565b60006001600160401b03821115611a1757611a176119b8565b50601f01601f191660200190565b600060208284031215611a3757600080fd5b81356001600160401b03811115611a4d57600080fd5b8201601f81018413611a5e57600080fd5b8035611a71611a6c826119fe565b6119ce565b818152856020838501011115611a8657600080fd5b81602084016020830137600091810160200191909152949350505050565b60005b83811015611abf578181015183820152602001611aa7565b50506000910152565b83815260008351611ae0816020850160208801611aa4565b60209201918201929092526040019392505050565b600060208284031215611b0757600080fd5b81516001600160401b03811115611b1d57600080fd5b8201601f81018413611b2e57600080fd5b8051611b3c611a6c826119fe565b818152856020838501011115611b5157600080fd5b611b62826020830160208601611aa4565b95945050505050565b600080600060608486031215611b8057600080fd5b8351611b8b81611983565b6020850151909350611b9c81611983565b80925050604084015190509250925092565b634e487b7160e01b600052601160045260246000fd5b8082018082111561054357610543611bae565b634e487b7160e01b600052603260045260246000fd5b808202811582820484141761054357610543611bae565b8181038181111561054357610543611bae565b600060018201611c2957611c29611bae565b5060010190565b600080600080600060a08688031215611c4857600080fd5b855194506020860151935060408601519250606086015191506080860151611c6f81611983565b809150509295509295909350565b634e487b7160e01b600052601260045260246000fd5b600082611ca257611ca2611c7d565b500690565b600082611cb657611cb6611c7d565b500490565b600060ff831680611cce57611cce611c7d565b8060ff84160691505092915050565b600060ff831680611cf057611cf0611c7d565b8060ff84160491505092915050565b600181815b80851115611d3a578160001904821115611d2057611d20611bae565b80851615611d2d57918102915b93841c9390800290611d04565b509250929050565b600082611d5157506001610543565b81611d5e57506000610543565b8160018114611d745760028114611d7e57611d9a565b6001915050610543565b60ff841115611d8f57611d8f611bae565b50506001821b610543565b5060208310610133831016604e8410600b8410161715611dbd575081810a610543565b611dc78383611cff565b8060001904821115611ddb57611ddb611bae565b029392505050565b600061170e8383611d42565b60ff828116828216039081111561054357610543611bae56fea2646970667358221220a924e520bf4f9d5629bc95702236e2702455bf9b57c4e9e4e344c7c7d7576a2b64736f6c63430008140033" - -// DeployRootReceiver deploys a new Ethereum contract, binding an instance of RootReceiver to it. -func DeployRootReceiver(auth *bind.TransactOpts, backend bind.ContractBackend, _checkpointManager common.Address) (common.Address, types.Transaction, *RootReceiver, error) { - parsed, err := abi.JSON(strings.NewReader(RootReceiverABI)) - if err != nil { - return common.Address{}, nil, nil, err - } - - address, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(RootReceiverBin), backend, _checkpointManager) - if err != nil { - return common.Address{}, nil, nil, err - } - return address, tx, &RootReceiver{RootReceiverCaller: RootReceiverCaller{contract: contract}, RootReceiverTransactor: RootReceiverTransactor{contract: contract}, RootReceiverFilterer: RootReceiverFilterer{contract: contract}}, nil -} - -// RootReceiver is an auto generated Go binding around an Ethereum contract. -type RootReceiver struct { - RootReceiverCaller // Read-only binding to the contract - RootReceiverTransactor // Write-only binding to the contract - RootReceiverFilterer // Log filterer for contract events -} - -// RootReceiverCaller is an auto generated read-only Go binding around an Ethereum contract. -type RootReceiverCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// RootReceiverTransactor is an auto generated write-only Go binding around an Ethereum contract. -type RootReceiverTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// RootReceiverFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type RootReceiverFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// RootReceiverSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type RootReceiverSession struct { - Contract *RootReceiver // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// RootReceiverCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type RootReceiverCallerSession struct { - Contract *RootReceiverCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// RootReceiverTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type RootReceiverTransactorSession struct { - Contract *RootReceiverTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// RootReceiverRaw is an auto generated low-level Go binding around an Ethereum contract. -type RootReceiverRaw struct { - Contract *RootReceiver // Generic contract binding to access the raw methods on -} - -// RootReceiverCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type RootReceiverCallerRaw struct { - Contract *RootReceiverCaller // Generic read-only contract binding to access the raw methods on -} - -// RootReceiverTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type RootReceiverTransactorRaw struct { - Contract *RootReceiverTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewRootReceiver creates a new instance of RootReceiver, bound to a specific deployed contract. -func NewRootReceiver(address common.Address, backend bind.ContractBackend) (*RootReceiver, error) { - contract, err := bindRootReceiver(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &RootReceiver{RootReceiverCaller: RootReceiverCaller{contract: contract}, RootReceiverTransactor: RootReceiverTransactor{contract: contract}, RootReceiverFilterer: RootReceiverFilterer{contract: contract}}, nil -} - -// NewRootReceiverCaller creates a new read-only instance of RootReceiver, bound to a specific deployed contract. -func NewRootReceiverCaller(address common.Address, caller bind.ContractCaller) (*RootReceiverCaller, error) { - contract, err := bindRootReceiver(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &RootReceiverCaller{contract: contract}, nil -} - -// NewRootReceiverTransactor creates a new write-only instance of RootReceiver, bound to a specific deployed contract. -func NewRootReceiverTransactor(address common.Address, transactor bind.ContractTransactor) (*RootReceiverTransactor, error) { - contract, err := bindRootReceiver(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &RootReceiverTransactor{contract: contract}, nil -} - -// NewRootReceiverFilterer creates a new log filterer instance of RootReceiver, bound to a specific deployed contract. -func NewRootReceiverFilterer(address common.Address, filterer bind.ContractFilterer) (*RootReceiverFilterer, error) { - contract, err := bindRootReceiver(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &RootReceiverFilterer{contract: contract}, nil -} - -// bindRootReceiver binds a generic wrapper to an already deployed contract. -func bindRootReceiver(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(RootReceiverABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_RootReceiver *RootReceiverRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _RootReceiver.Contract.RootReceiverCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_RootReceiver *RootReceiverRaw) Transfer(opts *bind.TransactOpts) (types.Transaction, error) { - return _RootReceiver.Contract.RootReceiverTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_RootReceiver *RootReceiverRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (types.Transaction, error) { - return _RootReceiver.Contract.RootReceiverTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_RootReceiver *RootReceiverCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _RootReceiver.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_RootReceiver *RootReceiverTransactorRaw) Transfer(opts *bind.TransactOpts) (types.Transaction, error) { - return _RootReceiver.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_RootReceiver *RootReceiverTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (types.Transaction, error) { - return _RootReceiver.Contract.contract.Transact(opts, method, params...) -} - -// SENDMESSAGEEVENTSIG is a free data retrieval call binding the contract method 0x0e387de6. -// -// Solidity: function SEND_MESSAGE_EVENT_SIG() view returns(bytes32) -func (_RootReceiver *RootReceiverCaller) SENDMESSAGEEVENTSIG(opts *bind.CallOpts) ([32]byte, error) { - var out []interface{} - err := _RootReceiver.contract.Call(opts, &out, "SEND_MESSAGE_EVENT_SIG") - - if err != nil { - return *new([32]byte), err - } - - out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) - - return out0, err - -} - -// SENDMESSAGEEVENTSIG is a free data retrieval call binding the contract method 0x0e387de6. -// -// Solidity: function SEND_MESSAGE_EVENT_SIG() view returns(bytes32) -func (_RootReceiver *RootReceiverSession) SENDMESSAGEEVENTSIG() ([32]byte, error) { - return _RootReceiver.Contract.SENDMESSAGEEVENTSIG(&_RootReceiver.CallOpts) -} - -// SENDMESSAGEEVENTSIG is a free data retrieval call binding the contract method 0x0e387de6. -// -// Solidity: function SEND_MESSAGE_EVENT_SIG() view returns(bytes32) -func (_RootReceiver *RootReceiverCallerSession) SENDMESSAGEEVENTSIG() ([32]byte, error) { - return _RootReceiver.Contract.SENDMESSAGEEVENTSIG(&_RootReceiver.CallOpts) -} - -// CheckpointManager is a free data retrieval call binding the contract method 0xc0857ba0. -// -// Solidity: function checkpointManager() view returns(address) -func (_RootReceiver *RootReceiverCaller) CheckpointManager(opts *bind.CallOpts) (common.Address, error) { - var out []interface{} - err := _RootReceiver.contract.Call(opts, &out, "checkpointManager") - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// CheckpointManager is a free data retrieval call binding the contract method 0xc0857ba0. -// -// Solidity: function checkpointManager() view returns(address) -func (_RootReceiver *RootReceiverSession) CheckpointManager() (common.Address, error) { - return _RootReceiver.Contract.CheckpointManager(&_RootReceiver.CallOpts) -} - -// CheckpointManager is a free data retrieval call binding the contract method 0xc0857ba0. -// -// Solidity: function checkpointManager() view returns(address) -func (_RootReceiver *RootReceiverCallerSession) CheckpointManager() (common.Address, error) { - return _RootReceiver.Contract.CheckpointManager(&_RootReceiver.CallOpts) -} - -// ProcessedExits is a free data retrieval call binding the contract method 0x607f2d42. -// -// Solidity: function processedExits(bytes32 ) view returns(bool) -func (_RootReceiver *RootReceiverCaller) ProcessedExits(opts *bind.CallOpts, arg0 [32]byte) (bool, error) { - var out []interface{} - err := _RootReceiver.contract.Call(opts, &out, "processedExits", arg0) - - if err != nil { - return *new(bool), err - } - - out0 := *abi.ConvertType(out[0], new(bool)).(*bool) - - return out0, err - -} - -// ProcessedExits is a free data retrieval call binding the contract method 0x607f2d42. -// -// Solidity: function processedExits(bytes32 ) view returns(bool) -func (_RootReceiver *RootReceiverSession) ProcessedExits(arg0 [32]byte) (bool, error) { - return _RootReceiver.Contract.ProcessedExits(&_RootReceiver.CallOpts, arg0) -} - -// ProcessedExits is a free data retrieval call binding the contract method 0x607f2d42. -// -// Solidity: function processedExits(bytes32 ) view returns(bool) -func (_RootReceiver *RootReceiverCallerSession) ProcessedExits(arg0 [32]byte) (bool, error) { - return _RootReceiver.Contract.ProcessedExits(&_RootReceiver.CallOpts, arg0) -} - -// Senders is a free data retrieval call binding the contract method 0x982fb9d8. -// -// Solidity: function senders(address ) view returns(uint256) -func (_RootReceiver *RootReceiverCaller) Senders(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) { - var out []interface{} - err := _RootReceiver.contract.Call(opts, &out, "senders", arg0) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Senders is a free data retrieval call binding the contract method 0x982fb9d8. -// -// Solidity: function senders(address ) view returns(uint256) -func (_RootReceiver *RootReceiverSession) Senders(arg0 common.Address) (*big.Int, error) { - return _RootReceiver.Contract.Senders(&_RootReceiver.CallOpts, arg0) -} - -// Senders is a free data retrieval call binding the contract method 0x982fb9d8. -// -// Solidity: function senders(address ) view returns(uint256) -func (_RootReceiver *RootReceiverCallerSession) Senders(arg0 common.Address) (*big.Int, error) { - return _RootReceiver.Contract.Senders(&_RootReceiver.CallOpts, arg0) -} - -// ReceiveMessage is a paid mutator transaction binding the contract method 0xf953cec7. -// -// Solidity: function receiveMessage(bytes inputData) returns() -func (_RootReceiver *RootReceiverTransactor) ReceiveMessage(opts *bind.TransactOpts, inputData []byte) (types.Transaction, error) { - return _RootReceiver.contract.Transact(opts, "receiveMessage", inputData) -} - -// ReceiveMessage is a paid mutator transaction binding the contract method 0xf953cec7. -// -// Solidity: function receiveMessage(bytes inputData) returns() -func (_RootReceiver *RootReceiverSession) ReceiveMessage(inputData []byte) (types.Transaction, error) { - return _RootReceiver.Contract.ReceiveMessage(&_RootReceiver.TransactOpts, inputData) -} - -// ReceiveMessage is a paid mutator transaction binding the contract method 0xf953cec7. -// -// Solidity: function receiveMessage(bytes inputData) returns() -func (_RootReceiver *RootReceiverTransactorSession) ReceiveMessage(inputData []byte) (types.Transaction, error) { - return _RootReceiver.Contract.ReceiveMessage(&_RootReceiver.TransactOpts, inputData) -} - -// RootReceiverReceiveMessageParams is an auto generated read-only Go binding of transcaction calldata params -type RootReceiverReceiveMessageParams struct { - Param_inputData []byte -} - -// Parse ReceiveMessage method from calldata of a transaction -// -// Solidity: function receiveMessage(bytes inputData) returns() -func ParseRootReceiverReceiveMessageParams(calldata []byte) (*RootReceiverReceiveMessageParams, error) { - if len(calldata) <= 4 { - return nil, fmt.Errorf("invalid calldata input") - } - - _abi, err := abi.JSON(strings.NewReader(RootReceiverABI)) - if err != nil { - return nil, fmt.Errorf("failed to get abi of registry metadata: %w", err) - } - - out, err := _abi.Methods["receiveMessage"].Inputs.Unpack(calldata[4:]) - if err != nil { - return nil, fmt.Errorf("failed to unpack receiveMessage params data: %w", err) - } - - var paramsResult = new(RootReceiverReceiveMessageParams) - value := reflect.ValueOf(paramsResult).Elem() - - if value.NumField() != len(out) { - return nil, fmt.Errorf("failed to match calldata with param field number") - } - - out0 := *abi.ConvertType(out[0], new([]byte)).(*[]byte) - - return &RootReceiverReceiveMessageParams{ - Param_inputData: out0, - }, nil -} - -// RootReceiverReceivedIterator is returned from FilterReceived and is used to iterate over the raw logs and unpacked data for Received events raised by the RootReceiver contract. -type RootReceiverReceivedIterator struct { - Event *RootReceiverReceived // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *RootReceiverReceivedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(RootReceiverReceived) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(RootReceiverReceived) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *RootReceiverReceivedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *RootReceiverReceivedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// RootReceiverReceived represents a Received event raised by the RootReceiver contract. -type RootReceiverReceived struct { - Source common.Address - Amount *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -func (_RootReceiver *RootReceiverFilterer) ReceivedEventID() common.Hash { - return common.HexToHash("0xf11e547d796cc64acdf758e7cee90439494fd886a19159454aa61e473fdbafef") -} - -// FilterReceived is a free log retrieval operation binding the contract event 0xf11e547d796cc64acdf758e7cee90439494fd886a19159454aa61e473fdbafef. -// -// Solidity: event received(address _source, uint256 _amount) -func (_RootReceiver *RootReceiverFilterer) FilterReceived(opts *bind.FilterOpts) (*RootReceiverReceivedIterator, error) { - - logs, sub, err := _RootReceiver.contract.FilterLogs(opts, "received") - if err != nil { - return nil, err - } - return &RootReceiverReceivedIterator{contract: _RootReceiver.contract, event: "received", logs: logs, sub: sub}, nil -} - -// WatchReceived is a free log subscription operation binding the contract event 0xf11e547d796cc64acdf758e7cee90439494fd886a19159454aa61e473fdbafef. -// -// Solidity: event received(address _source, uint256 _amount) -func (_RootReceiver *RootReceiverFilterer) WatchReceived(opts *bind.WatchOpts, sink chan<- *RootReceiverReceived) (event.Subscription, error) { - - logs, sub, err := _RootReceiver.contract.WatchLogs(opts, "received") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(RootReceiverReceived) - if err := _RootReceiver.contract.UnpackLog(event, "received", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseReceived is a log parse operation binding the contract event 0xf11e547d796cc64acdf758e7cee90439494fd886a19159454aa61e473fdbafef. -// -// Solidity: event received(address _source, uint256 _amount) -func (_RootReceiver *RootReceiverFilterer) ParseReceived(log types.Log) (*RootReceiverReceived, error) { - event := new(RootReceiverReceived) - if err := _RootReceiver.contract.UnpackLog(event, "received", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/cmd/devnet/contracts/gen_rootsender.go b/cmd/devnet/contracts/gen_rootsender.go deleted file mode 100644 index 631f1b45622..00000000000 --- a/cmd/devnet/contracts/gen_rootsender.go +++ /dev/null @@ -1,282 +0,0 @@ -// Code generated by abigen. DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package contracts - -import ( - "fmt" - "math/big" - "reflect" - "strings" - - ethereum "github.com/erigontech/erigon" - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon/execution/abi" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/execution/types" - "github.com/erigontech/erigon/p2p/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription - _ = fmt.Errorf - _ = reflect.ValueOf -) - -// RootSenderABI is the input ABI used to generate the binding from. -const RootSenderABI = "[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"stateSender_\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"childStateReceiver_\",\"type\":\"address\"}],\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"sendToChild\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"sent\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"}]" - -// RootSenderBin is the compiled bytecode used for deploying new contracts. -var RootSenderBin = "0x608060405234801561001057600080fd5b506040516102fb3803806102fb83398101604081905261002f9161007c565b600080546001600160a01b039384166001600160a01b031991821617909155600180549290931691161790556100af565b80516001600160a01b038116811461007757600080fd5b919050565b6000806040838503121561008f57600080fd5b61009883610060565b91506100a660208401610060565b90509250929050565b61023d806100be6000396000f3fe608060405234801561001057600080fd5b50600436106100365760003560e01c8063513e29ff1461003b5780637bf786f814610050575b600080fd5b61004e610049366004610139565b610082565b005b61007061005e366004610152565b60026020526000908152604090205481565b60405190815260200160405180910390f35b3360009081526002602052604090205461009c8282610182565b33600081815260026020908152604080832094909455905460015484519283019390935281840186905283518083038501815260608301948590526316f1983160e01b9094526001600160a01b03908116936316f1983193610103939216916064016101a9565b600060405180830381600087803b15801561011d57600080fd5b505af1158015610131573d6000803e3d6000fd5b505050505050565b60006020828403121561014b57600080fd5b5035919050565b60006020828403121561016457600080fd5b81356001600160a01b038116811461017b57600080fd5b9392505050565b808201808211156101a357634e487b7160e01b600052601160045260246000fd5b92915050565b60018060a01b038316815260006020604081840152835180604085015260005b818110156101e5578581018301518582016060015282016101c9565b506000606082860101526060601f19601f83011685010192505050939250505056fea2646970667358221220fa5fa4e9dd64f8da1ad4844228b4671828b48d8de1f8d3f92ba0e5551ce1e47c64736f6c63430008140033" - -// DeployRootSender deploys a new Ethereum contract, binding an instance of RootSender to it. -func DeployRootSender(auth *bind.TransactOpts, backend bind.ContractBackend, stateSender_ common.Address, childStateReceiver_ common.Address) (common.Address, types.Transaction, *RootSender, error) { - parsed, err := abi.JSON(strings.NewReader(RootSenderABI)) - if err != nil { - return common.Address{}, nil, nil, err - } - - address, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(RootSenderBin), backend, stateSender_, childStateReceiver_) - if err != nil { - return common.Address{}, nil, nil, err - } - return address, tx, &RootSender{RootSenderCaller: RootSenderCaller{contract: contract}, RootSenderTransactor: RootSenderTransactor{contract: contract}, RootSenderFilterer: RootSenderFilterer{contract: contract}}, nil -} - -// RootSender is an auto generated Go binding around an Ethereum contract. -type RootSender struct { - RootSenderCaller // Read-only binding to the contract - RootSenderTransactor // Write-only binding to the contract - RootSenderFilterer // Log filterer for contract events -} - -// RootSenderCaller is an auto generated read-only Go binding around an Ethereum contract. -type RootSenderCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// RootSenderTransactor is an auto generated write-only Go binding around an Ethereum contract. -type RootSenderTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// RootSenderFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type RootSenderFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// RootSenderSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type RootSenderSession struct { - Contract *RootSender // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// RootSenderCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type RootSenderCallerSession struct { - Contract *RootSenderCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// RootSenderTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type RootSenderTransactorSession struct { - Contract *RootSenderTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// RootSenderRaw is an auto generated low-level Go binding around an Ethereum contract. -type RootSenderRaw struct { - Contract *RootSender // Generic contract binding to access the raw methods on -} - -// RootSenderCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type RootSenderCallerRaw struct { - Contract *RootSenderCaller // Generic read-only contract binding to access the raw methods on -} - -// RootSenderTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type RootSenderTransactorRaw struct { - Contract *RootSenderTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewRootSender creates a new instance of RootSender, bound to a specific deployed contract. -func NewRootSender(address common.Address, backend bind.ContractBackend) (*RootSender, error) { - contract, err := bindRootSender(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &RootSender{RootSenderCaller: RootSenderCaller{contract: contract}, RootSenderTransactor: RootSenderTransactor{contract: contract}, RootSenderFilterer: RootSenderFilterer{contract: contract}}, nil -} - -// NewRootSenderCaller creates a new read-only instance of RootSender, bound to a specific deployed contract. -func NewRootSenderCaller(address common.Address, caller bind.ContractCaller) (*RootSenderCaller, error) { - contract, err := bindRootSender(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &RootSenderCaller{contract: contract}, nil -} - -// NewRootSenderTransactor creates a new write-only instance of RootSender, bound to a specific deployed contract. -func NewRootSenderTransactor(address common.Address, transactor bind.ContractTransactor) (*RootSenderTransactor, error) { - contract, err := bindRootSender(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &RootSenderTransactor{contract: contract}, nil -} - -// NewRootSenderFilterer creates a new log filterer instance of RootSender, bound to a specific deployed contract. -func NewRootSenderFilterer(address common.Address, filterer bind.ContractFilterer) (*RootSenderFilterer, error) { - contract, err := bindRootSender(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &RootSenderFilterer{contract: contract}, nil -} - -// bindRootSender binds a generic wrapper to an already deployed contract. -func bindRootSender(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(RootSenderABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_RootSender *RootSenderRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _RootSender.Contract.RootSenderCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_RootSender *RootSenderRaw) Transfer(opts *bind.TransactOpts) (types.Transaction, error) { - return _RootSender.Contract.RootSenderTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_RootSender *RootSenderRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (types.Transaction, error) { - return _RootSender.Contract.RootSenderTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_RootSender *RootSenderCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _RootSender.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_RootSender *RootSenderTransactorRaw) Transfer(opts *bind.TransactOpts) (types.Transaction, error) { - return _RootSender.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_RootSender *RootSenderTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (types.Transaction, error) { - return _RootSender.Contract.contract.Transact(opts, method, params...) -} - -// Sent is a free data retrieval call binding the contract method 0x7bf786f8. -// -// Solidity: function sent(address ) view returns(uint256) -func (_RootSender *RootSenderCaller) Sent(opts *bind.CallOpts, arg0 common.Address) (*big.Int, error) { - var out []interface{} - err := _RootSender.contract.Call(opts, &out, "sent", arg0) - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Sent is a free data retrieval call binding the contract method 0x7bf786f8. -// -// Solidity: function sent(address ) view returns(uint256) -func (_RootSender *RootSenderSession) Sent(arg0 common.Address) (*big.Int, error) { - return _RootSender.Contract.Sent(&_RootSender.CallOpts, arg0) -} - -// Sent is a free data retrieval call binding the contract method 0x7bf786f8. -// -// Solidity: function sent(address ) view returns(uint256) -func (_RootSender *RootSenderCallerSession) Sent(arg0 common.Address) (*big.Int, error) { - return _RootSender.Contract.Sent(&_RootSender.CallOpts, arg0) -} - -// SendToChild is a paid mutator transaction binding the contract method 0x513e29ff. -// -// Solidity: function sendToChild(uint256 amount) returns() -func (_RootSender *RootSenderTransactor) SendToChild(opts *bind.TransactOpts, amount *big.Int) (types.Transaction, error) { - return _RootSender.contract.Transact(opts, "sendToChild", amount) -} - -// SendToChild is a paid mutator transaction binding the contract method 0x513e29ff. -// -// Solidity: function sendToChild(uint256 amount) returns() -func (_RootSender *RootSenderSession) SendToChild(amount *big.Int) (types.Transaction, error) { - return _RootSender.Contract.SendToChild(&_RootSender.TransactOpts, amount) -} - -// SendToChild is a paid mutator transaction binding the contract method 0x513e29ff. -// -// Solidity: function sendToChild(uint256 amount) returns() -func (_RootSender *RootSenderTransactorSession) SendToChild(amount *big.Int) (types.Transaction, error) { - return _RootSender.Contract.SendToChild(&_RootSender.TransactOpts, amount) -} - -// RootSenderSendToChildParams is an auto generated read-only Go binding of transcaction calldata params -type RootSenderSendToChildParams struct { - Param_amount *big.Int -} - -// Parse SendToChild method from calldata of a transaction -// -// Solidity: function sendToChild(uint256 amount) returns() -func ParseRootSenderSendToChildParams(calldata []byte) (*RootSenderSendToChildParams, error) { - if len(calldata) <= 4 { - return nil, fmt.Errorf("invalid calldata input") - } - - _abi, err := abi.JSON(strings.NewReader(RootSenderABI)) - if err != nil { - return nil, fmt.Errorf("failed to get abi of registry metadata: %w", err) - } - - out, err := _abi.Methods["sendToChild"].Inputs.Unpack(calldata[4:]) - if err != nil { - return nil, fmt.Errorf("failed to unpack sendToChild params data: %w", err) - } - - var paramsResult = new(RootSenderSendToChildParams) - value := reflect.ValueOf(paramsResult).Elem() - - if value.NumField() != len(out) { - return nil, fmt.Errorf("failed to match calldata with param field number") - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return &RootSenderSendToChildParams{ - Param_amount: out0, - }, nil -} diff --git a/cmd/devnet/contracts/gen_subscription.go b/cmd/devnet/contracts/gen_subscription.go deleted file mode 100644 index a4eba7e679d..00000000000 --- a/cmd/devnet/contracts/gen_subscription.go +++ /dev/null @@ -1,343 +0,0 @@ -// Code generated - DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package contracts - -import ( - "math/big" - "strings" - - ethereum "github.com/erigontech/erigon" - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon/execution/abi" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/execution/types" - "github.com/erigontech/erigon/p2p/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription -) - -// SubscriptionABI is the input ABI used to generate the binding from. -const SubscriptionABI = "[{\"anonymous\":false,\"inputs\":[],\"name\":\"SubscriptionEvent\",\"type\":\"event\"},{\"stateMutability\":\"nonpayable\",\"type\":\"fallback\"}]" - -// SubscriptionBin is the compiled bytecode used for deploying new contracts. -var SubscriptionBin = "0x6080604052348015600f57600080fd5b50607180601d6000396000f3fe6080604052348015600f57600080fd5b506040517f67abc7edb0ab50964ef0e90541d39366b9c69f6f714520f2ff4570059ee8ad8090600090a100fea264697066735822122045a70478ef4f6a283c0e153ad72ec6731dc9ee2e1c191c7334b74dea21a92eaf64736f6c634300080c0033" - -// DeploySubscription deploys a new Ethereum contract, binding an instance of Subscription to it. -func DeploySubscription(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, types.Transaction, *Subscription, error) { - parsed, err := abi.JSON(strings.NewReader(SubscriptionABI)) - if err != nil { - return common.Address{}, nil, nil, err - } - - address, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(SubscriptionBin), backend) - if err != nil { - return common.Address{}, nil, nil, err - } - return address, tx, &Subscription{SubscriptionCaller: SubscriptionCaller{contract: contract}, SubscriptionTransactor: SubscriptionTransactor{contract: contract}, SubscriptionFilterer: SubscriptionFilterer{contract: contract}}, nil -} - -// Subscription is an auto generated Go binding around an Ethereum contract. -type Subscription struct { - SubscriptionCaller // Read-only binding to the contract - SubscriptionTransactor // Write-only binding to the contract - SubscriptionFilterer // Log filterer for contract events -} - -// SubscriptionCaller is an auto generated read-only Go binding around an Ethereum contract. -type SubscriptionCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// SubscriptionTransactor is an auto generated write-only Go binding around an Ethereum contract. -type SubscriptionTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// SubscriptionFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type SubscriptionFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// SubscriptionSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type SubscriptionSession struct { - Contract *Subscription // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// SubscriptionCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type SubscriptionCallerSession struct { - Contract *SubscriptionCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// SubscriptionTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type SubscriptionTransactorSession struct { - Contract *SubscriptionTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// SubscriptionRaw is an auto generated low-level Go binding around an Ethereum contract. -type SubscriptionRaw struct { - Contract *Subscription // Generic contract binding to access the raw methods on -} - -// SubscriptionCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type SubscriptionCallerRaw struct { - Contract *SubscriptionCaller // Generic read-only contract binding to access the raw methods on -} - -// SubscriptionTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type SubscriptionTransactorRaw struct { - Contract *SubscriptionTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewSubscription creates a new instance of Subscription, bound to a specific deployed contract. -func NewSubscription(address common.Address, backend bind.ContractBackend) (*Subscription, error) { - contract, err := bindSubscription(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &Subscription{SubscriptionCaller: SubscriptionCaller{contract: contract}, SubscriptionTransactor: SubscriptionTransactor{contract: contract}, SubscriptionFilterer: SubscriptionFilterer{contract: contract}}, nil -} - -// NewSubscriptionCaller creates a new read-only instance of Subscription, bound to a specific deployed contract. -func NewSubscriptionCaller(address common.Address, caller bind.ContractCaller) (*SubscriptionCaller, error) { - contract, err := bindSubscription(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &SubscriptionCaller{contract: contract}, nil -} - -// NewSubscriptionTransactor creates a new write-only instance of Subscription, bound to a specific deployed contract. -func NewSubscriptionTransactor(address common.Address, transactor bind.ContractTransactor) (*SubscriptionTransactor, error) { - contract, err := bindSubscription(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &SubscriptionTransactor{contract: contract}, nil -} - -// NewSubscriptionFilterer creates a new log filterer instance of Subscription, bound to a specific deployed contract. -func NewSubscriptionFilterer(address common.Address, filterer bind.ContractFilterer) (*SubscriptionFilterer, error) { - contract, err := bindSubscription(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &SubscriptionFilterer{contract: contract}, nil -} - -// bindSubscription binds a generic wrapper to an already deployed contract. -func bindSubscription(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(SubscriptionABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Subscription *SubscriptionRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Subscription.Contract.SubscriptionCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Subscription *SubscriptionRaw) Transfer(opts *bind.TransactOpts) (types.Transaction, error) { - return _Subscription.Contract.SubscriptionTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Subscription *SubscriptionRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (types.Transaction, error) { - return _Subscription.Contract.SubscriptionTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_Subscription *SubscriptionCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _Subscription.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_Subscription *SubscriptionTransactorRaw) Transfer(opts *bind.TransactOpts) (types.Transaction, error) { - return _Subscription.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_Subscription *SubscriptionTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (types.Transaction, error) { - return _Subscription.Contract.contract.Transact(opts, method, params...) -} - -// Fallback is a paid mutator transaction binding the contract fallback function. -// -// Solidity: fallback() returns() -func (_Subscription *SubscriptionTransactor) Fallback(opts *bind.TransactOpts, calldata []byte) (types.Transaction, error) { - return _Subscription.contract.RawTransact(opts, calldata) -} - -// Fallback is a paid mutator transaction binding the contract fallback function. -// -// Solidity: fallback() returns() -func (_Subscription *SubscriptionSession) Fallback(calldata []byte) (types.Transaction, error) { - return _Subscription.Contract.Fallback(&_Subscription.TransactOpts, calldata) -} - -// Fallback is a paid mutator transaction binding the contract fallback function. -// -// Solidity: fallback() returns() -func (_Subscription *SubscriptionTransactorSession) Fallback(calldata []byte) (types.Transaction, error) { - return _Subscription.Contract.Fallback(&_Subscription.TransactOpts, calldata) -} - -// SubscriptionSubscriptionEventIterator is returned from FilterSubscriptionEvent and is used to iterate over the raw logs and unpacked data for SubscriptionEvent events raised by the Subscription contract. -type SubscriptionSubscriptionEventIterator struct { - Event *SubscriptionSubscriptionEvent // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *SubscriptionSubscriptionEventIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(SubscriptionSubscriptionEvent) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(SubscriptionSubscriptionEvent) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *SubscriptionSubscriptionEventIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *SubscriptionSubscriptionEventIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// SubscriptionSubscriptionEvent represents a SubscriptionEvent event raised by the Subscription contract. -type SubscriptionSubscriptionEvent struct { - Raw types.Log // Blockchain specific contextual infos -} - -// FilterSubscriptionEvent is a free log retrieval operation binding the contract event 0x67abc7edb0ab50964ef0e90541d39366b9c69f6f714520f2ff4570059ee8ad80. -// -// Solidity: event SubscriptionEvent() -func (_Subscription *SubscriptionFilterer) FilterSubscriptionEvent(opts *bind.FilterOpts) (*SubscriptionSubscriptionEventIterator, error) { - - logs, sub, err := _Subscription.contract.FilterLogs(opts, "SubscriptionEvent") - if err != nil { - return nil, err - } - return &SubscriptionSubscriptionEventIterator{contract: _Subscription.contract, event: "SubscriptionEvent", logs: logs, sub: sub}, nil -} - -// WatchSubscriptionEvent is a free log subscription operation binding the contract event 0x67abc7edb0ab50964ef0e90541d39366b9c69f6f714520f2ff4570059ee8ad80. -// -// Solidity: event SubscriptionEvent() -func (_Subscription *SubscriptionFilterer) WatchSubscriptionEvent(opts *bind.WatchOpts, sink chan<- *SubscriptionSubscriptionEvent) (event.Subscription, error) { - - logs, sub, err := _Subscription.contract.WatchLogs(opts, "SubscriptionEvent") - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(SubscriptionSubscriptionEvent) - if err := _Subscription.contract.UnpackLog(event, "SubscriptionEvent", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseSubscriptionEvent is a log parse operation binding the contract event 0x67abc7edb0ab50964ef0e90541d39366b9c69f6f714520f2ff4570059ee8ad80. -// -// Solidity: event SubscriptionEvent() -func (_Subscription *SubscriptionFilterer) ParseSubscriptionEvent(log types.Log) (*SubscriptionSubscriptionEvent, error) { - event := new(SubscriptionSubscriptionEvent) - if err := _Subscription.contract.UnpackLog(event, "SubscriptionEvent", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/cmd/devnet/contracts/gen_testrootchain.go b/cmd/devnet/contracts/gen_testrootchain.go deleted file mode 100644 index 2cba4cee665..00000000000 --- a/cmd/devnet/contracts/gen_testrootchain.go +++ /dev/null @@ -1,1080 +0,0 @@ -// Code generated by abigen. DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package contracts - -import ( - "fmt" - "math/big" - "reflect" - "strings" - - ethereum "github.com/erigontech/erigon" - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon/execution/abi" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/execution/types" - "github.com/erigontech/erigon/p2p/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription - _ = fmt.Errorf - _ = reflect.ValueOf -) - -// TestRootChainABI is the input ABI used to generate the binding from. -const TestRootChainABI = "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"proposer\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"headerBlockId\",\"type\":\"uint256\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"reward\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"start\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"end\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"root\",\"type\":\"bytes32\"}],\"name\":\"NewHeaderBlock\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"proposer\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"headerBlockId\",\"type\":\"uint256\"}],\"name\":\"ResetHeaderBlock\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"CHAINID\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"VOTE_TYPE\",\"outputs\":[{\"internalType\":\"uint8\",\"name\":\"\",\"type\":\"uint8\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"_nextHeaderBlock\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"currentHeaderBlock\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getLastChildBlock\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"headerBlocks\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"root\",\"type\":\"bytes32\"},{\"internalType\":\"uint256\",\"name\":\"start\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"end\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"createdAt\",\"type\":\"uint256\"},{\"internalType\":\"address\",\"name\":\"proposer\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"heimdallId\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"networkId\",\"outputs\":[{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"string\",\"name\":\"_heimdallId\",\"type\":\"string\"}],\"name\":\"setHeimdallId\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"setNextHeaderBlock\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"slash\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"internalType\":\"uint256[3][]\",\"name\":\"\",\"type\":\"uint256[3][]\"}],\"name\":\"submitCheckpoint\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"},{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}],\"name\":\"submitHeaderBlock\",\"outputs\":[],\"stateMutability\":\"pure\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"numDeposits\",\"type\":\"uint256\"}],\"name\":\"updateDepositId\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"depositId\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - -// TestRootChainBin is the compiled bytecode used for deploying new contracts. -var TestRootChainBin = "0x6080604052612710600255600160035534801561001b57600080fd5b50610af88061002b6000396000f3fe608060405234801561001057600080fd5b50600436106100ea5760003560e01c8063b87e1b661161008c578063d5b844eb11610066578063d5b844eb1461020b578063ea0688b314610225578063ec7e485514610238578063fbc3dd361461024057600080fd5b8063b87e1b66146101e7578063cc79f97b146101ef578063cf24a0ea146101f857600080fd5b80635391f483116100c85780635391f483146101815780636a791f11146101a25780638d978d88146101b05780639025e64c146101b957600080fd5b80632da25de3146100ef57806341539d4a146100f15780634e43e4951461016e575b600080fd5b005b6101386100ff36600461072b565b6004602081905260009182526040909120805460018201546002830154600384015493909401549193909290916001600160a01b031685565b6040805195865260208601949094529284019190915260608301526001600160a01b0316608082015260a0015b60405180910390f35b6100ef61017c36600461078d565b610249565b61019461018f36600461072b565b61037b565b604051908152602001610165565b6100ef6100ea366004610827565b61019460025481565b6101da60405180604001604052806002815260200161053960f01b81525081565b60405161016591906108b7565b6101946104c5565b61019461053981565b6100ef61020636600461072b565b6104ea565b610213600281565b60405160ff9091168152602001610165565b6100ef610233366004610900565b6105c5565b6101946105f4565b61019460015481565b6000808080808061025c898b018b6109c9565b95509550955095509550955080610539146102b55760405162461bcd60e51b8152602060048201526014602482015273125b9d985b1a5908189bdc8818da185a5b881a5960621b60448201526064015b60405180910390fd5b6102c18686868661060b565b6103055760405162461bcd60e51b8152602060048201526015602482015274494e434f52524543545f4845414445525f4441544160581b60448201526064016102ac565b6002546040805187815260208101879052908101859052600091906001600160a01b038916907fba5de06d22af2685c6c7765f60067f7d2b08c2d29f53cdf14d67f6d1c9bfb5279060600160405180910390a4600254610367906127106106e4565b600255505060016003555050505050505050565b6005546040805162c9effd60e41b815290516000926001600160a01b031691630c9effd09160048083019260209291908290030181865afa1580156103c4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906103e89190610a15565b6001600160a01b0316336001600160a01b0316146104525760405162461bcd60e51b815260206004820152602160248201527f554e415554484f52495a45445f4445504f5349545f4d414e414745525f4f4e4c6044820152605960f81b60648201526084016102ac565b6104666003546104606105f4565b906106e4565b60035490915061047690836106e4565b600381905561271010156104c05760405162461bcd60e51b8152602060048201526011602482015270544f4f5f4d414e595f4445504f5349545360781b60448201526064016102ac565b919050565b6000600460006104d36105f4565b815260200190815260200160002060020154905090565b6104f661271082610a32565b156105335760405162461bcd60e51b815260206004820152600d60248201526c496e76616c69642076616c756560981b60448201526064016102ac565b805b60025481101561058a5760008181526004602081905260408220828155600181018390556002810183905560038101929092550180546001600160a01b031916905561058361271082610a6a565b9050610535565b5060028190556001600355604051819033907fca1d8316287f938830e225956a7bb10fd5a1a1506dd2eb3a476751a48811720590600090a350565b806040516020016105d69190610a7d565b60408051601f19818403018152919052805160209091012060015550565b60025460009061060690612710610708565b905090565b60008061271061ffff16600254111561064b576004600061062a6105f4565b81526020019081526020016000206002015460016106489190610a6a565b90505b84811461065c5760009150506106dc565b6040805160a081018252848152602080820193845281830187815242606084019081526001600160a01b038b811660808601908152600280546000908152600496879052979097209551865596516001808701919091559251958501959095555160038401559351910180546001600160a01b0319169190921617905590505b949350505050565b60006106f08284610a6a565b90508281101561070257610702610a99565b92915050565b60008282111561071a5761071a610a99565b6107248284610aaf565b9392505050565b60006020828403121561073d57600080fd5b5035919050565b60008083601f84011261075657600080fd5b50813567ffffffffffffffff81111561076e57600080fd5b60208301915083602082850101111561078657600080fd5b9250929050565b600080600080604085870312156107a357600080fd5b843567ffffffffffffffff808211156107bb57600080fd5b6107c788838901610744565b909650945060208701359150808211156107e057600080fd5b818701915087601f8301126107f457600080fd5b81358181111561080357600080fd5b88602060608302850101111561081857600080fd5b95989497505060200194505050565b6000806000806040858703121561083d57600080fd5b843567ffffffffffffffff8082111561085557600080fd5b61086188838901610744565b9096509450602087013591508082111561087a57600080fd5b5061088787828801610744565b95989497509550505050565b60005b838110156108ae578181015183820152602001610896565b50506000910152565b60208152600082518060208401526108d6816040850160208701610893565b601f01601f19169190910160400192915050565b634e487b7160e01b600052604160045260246000fd5b60006020828403121561091257600080fd5b813567ffffffffffffffff8082111561092a57600080fd5b818401915084601f83011261093e57600080fd5b813581811115610950576109506108ea565b604051601f8201601f19908116603f01168101908382118183101715610978576109786108ea565b8160405282815287602084870101111561099157600080fd5b826020860160208301376000928101602001929092525095945050505050565b6001600160a01b03811681146109c657600080fd5b50565b60008060008060008060c087890312156109e257600080fd5b86356109ed816109b1565b9860208801359850604088013597606081013597506080810135965060a00135945092505050565b600060208284031215610a2757600080fd5b8151610724816109b1565b600082610a4f57634e487b7160e01b600052601260045260246000fd5b500690565b634e487b7160e01b600052601160045260246000fd5b8082018082111561070257610702610a54565b60008251610a8f818460208701610893565b9190910192915050565b634e487b7160e01b600052600160045260246000fd5b8181038181111561070257610702610a5456fea2646970667358221220e8aee67b63507e8745850c7b73e998c6ef6b5d41b72b45f8f1316e80e79a1ec964736f6c63430008140033" - -// DeployTestRootChain deploys a new Ethereum contract, binding an instance of TestRootChain to it. -func DeployTestRootChain(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, types.Transaction, *TestRootChain, error) { - parsed, err := abi.JSON(strings.NewReader(TestRootChainABI)) - if err != nil { - return common.Address{}, nil, nil, err - } - - address, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(TestRootChainBin), backend) - if err != nil { - return common.Address{}, nil, nil, err - } - return address, tx, &TestRootChain{TestRootChainCaller: TestRootChainCaller{contract: contract}, TestRootChainTransactor: TestRootChainTransactor{contract: contract}, TestRootChainFilterer: TestRootChainFilterer{contract: contract}}, nil -} - -// TestRootChain is an auto generated Go binding around an Ethereum contract. -type TestRootChain struct { - TestRootChainCaller // Read-only binding to the contract - TestRootChainTransactor // Write-only binding to the contract - TestRootChainFilterer // Log filterer for contract events -} - -// TestRootChainCaller is an auto generated read-only Go binding around an Ethereum contract. -type TestRootChainCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// TestRootChainTransactor is an auto generated write-only Go binding around an Ethereum contract. -type TestRootChainTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// TestRootChainFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type TestRootChainFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// TestRootChainSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type TestRootChainSession struct { - Contract *TestRootChain // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// TestRootChainCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type TestRootChainCallerSession struct { - Contract *TestRootChainCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// TestRootChainTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type TestRootChainTransactorSession struct { - Contract *TestRootChainTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// TestRootChainRaw is an auto generated low-level Go binding around an Ethereum contract. -type TestRootChainRaw struct { - Contract *TestRootChain // Generic contract binding to access the raw methods on -} - -// TestRootChainCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type TestRootChainCallerRaw struct { - Contract *TestRootChainCaller // Generic read-only contract binding to access the raw methods on -} - -// TestRootChainTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type TestRootChainTransactorRaw struct { - Contract *TestRootChainTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewTestRootChain creates a new instance of TestRootChain, bound to a specific deployed contract. -func NewTestRootChain(address common.Address, backend bind.ContractBackend) (*TestRootChain, error) { - contract, err := bindTestRootChain(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &TestRootChain{TestRootChainCaller: TestRootChainCaller{contract: contract}, TestRootChainTransactor: TestRootChainTransactor{contract: contract}, TestRootChainFilterer: TestRootChainFilterer{contract: contract}}, nil -} - -// NewTestRootChainCaller creates a new read-only instance of TestRootChain, bound to a specific deployed contract. -func NewTestRootChainCaller(address common.Address, caller bind.ContractCaller) (*TestRootChainCaller, error) { - contract, err := bindTestRootChain(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &TestRootChainCaller{contract: contract}, nil -} - -// NewTestRootChainTransactor creates a new write-only instance of TestRootChain, bound to a specific deployed contract. -func NewTestRootChainTransactor(address common.Address, transactor bind.ContractTransactor) (*TestRootChainTransactor, error) { - contract, err := bindTestRootChain(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &TestRootChainTransactor{contract: contract}, nil -} - -// NewTestRootChainFilterer creates a new log filterer instance of TestRootChain, bound to a specific deployed contract. -func NewTestRootChainFilterer(address common.Address, filterer bind.ContractFilterer) (*TestRootChainFilterer, error) { - contract, err := bindTestRootChain(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &TestRootChainFilterer{contract: contract}, nil -} - -// bindTestRootChain binds a generic wrapper to an already deployed contract. -func bindTestRootChain(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(TestRootChainABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_TestRootChain *TestRootChainRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _TestRootChain.Contract.TestRootChainCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_TestRootChain *TestRootChainRaw) Transfer(opts *bind.TransactOpts) (types.Transaction, error) { - return _TestRootChain.Contract.TestRootChainTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_TestRootChain *TestRootChainRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (types.Transaction, error) { - return _TestRootChain.Contract.TestRootChainTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_TestRootChain *TestRootChainCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _TestRootChain.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_TestRootChain *TestRootChainTransactorRaw) Transfer(opts *bind.TransactOpts) (types.Transaction, error) { - return _TestRootChain.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_TestRootChain *TestRootChainTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (types.Transaction, error) { - return _TestRootChain.Contract.contract.Transact(opts, method, params...) -} - -// CHAINID is a free data retrieval call binding the contract method 0xcc79f97b. -// -// Solidity: function CHAINID() view returns(uint256) -func (_TestRootChain *TestRootChainCaller) CHAINID(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _TestRootChain.contract.Call(opts, &out, "CHAINID") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// CHAINID is a free data retrieval call binding the contract method 0xcc79f97b. -// -// Solidity: function CHAINID() view returns(uint256) -func (_TestRootChain *TestRootChainSession) CHAINID() (*big.Int, error) { - return _TestRootChain.Contract.CHAINID(&_TestRootChain.CallOpts) -} - -// CHAINID is a free data retrieval call binding the contract method 0xcc79f97b. -// -// Solidity: function CHAINID() view returns(uint256) -func (_TestRootChain *TestRootChainCallerSession) CHAINID() (*big.Int, error) { - return _TestRootChain.Contract.CHAINID(&_TestRootChain.CallOpts) -} - -// VOTETYPE is a free data retrieval call binding the contract method 0xd5b844eb. -// -// Solidity: function VOTE_TYPE() view returns(uint8) -func (_TestRootChain *TestRootChainCaller) VOTETYPE(opts *bind.CallOpts) (uint8, error) { - var out []interface{} - err := _TestRootChain.contract.Call(opts, &out, "VOTE_TYPE") - - if err != nil { - return *new(uint8), err - } - - out0 := *abi.ConvertType(out[0], new(uint8)).(*uint8) - - return out0, err - -} - -// VOTETYPE is a free data retrieval call binding the contract method 0xd5b844eb. -// -// Solidity: function VOTE_TYPE() view returns(uint8) -func (_TestRootChain *TestRootChainSession) VOTETYPE() (uint8, error) { - return _TestRootChain.Contract.VOTETYPE(&_TestRootChain.CallOpts) -} - -// VOTETYPE is a free data retrieval call binding the contract method 0xd5b844eb. -// -// Solidity: function VOTE_TYPE() view returns(uint8) -func (_TestRootChain *TestRootChainCallerSession) VOTETYPE() (uint8, error) { - return _TestRootChain.Contract.VOTETYPE(&_TestRootChain.CallOpts) -} - -// NextHeaderBlock is a free data retrieval call binding the contract method 0x8d978d88. -// -// Solidity: function _nextHeaderBlock() view returns(uint256) -func (_TestRootChain *TestRootChainCaller) NextHeaderBlock(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _TestRootChain.contract.Call(opts, &out, "_nextHeaderBlock") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// NextHeaderBlock is a free data retrieval call binding the contract method 0x8d978d88. -// -// Solidity: function _nextHeaderBlock() view returns(uint256) -func (_TestRootChain *TestRootChainSession) NextHeaderBlock() (*big.Int, error) { - return _TestRootChain.Contract.NextHeaderBlock(&_TestRootChain.CallOpts) -} - -// NextHeaderBlock is a free data retrieval call binding the contract method 0x8d978d88. -// -// Solidity: function _nextHeaderBlock() view returns(uint256) -func (_TestRootChain *TestRootChainCallerSession) NextHeaderBlock() (*big.Int, error) { - return _TestRootChain.Contract.NextHeaderBlock(&_TestRootChain.CallOpts) -} - -// CurrentHeaderBlock is a free data retrieval call binding the contract method 0xec7e4855. -// -// Solidity: function currentHeaderBlock() view returns(uint256) -func (_TestRootChain *TestRootChainCaller) CurrentHeaderBlock(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _TestRootChain.contract.Call(opts, &out, "currentHeaderBlock") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// CurrentHeaderBlock is a free data retrieval call binding the contract method 0xec7e4855. -// -// Solidity: function currentHeaderBlock() view returns(uint256) -func (_TestRootChain *TestRootChainSession) CurrentHeaderBlock() (*big.Int, error) { - return _TestRootChain.Contract.CurrentHeaderBlock(&_TestRootChain.CallOpts) -} - -// CurrentHeaderBlock is a free data retrieval call binding the contract method 0xec7e4855. -// -// Solidity: function currentHeaderBlock() view returns(uint256) -func (_TestRootChain *TestRootChainCallerSession) CurrentHeaderBlock() (*big.Int, error) { - return _TestRootChain.Contract.CurrentHeaderBlock(&_TestRootChain.CallOpts) -} - -// GetLastChildBlock is a free data retrieval call binding the contract method 0xb87e1b66. -// -// Solidity: function getLastChildBlock() view returns(uint256) -func (_TestRootChain *TestRootChainCaller) GetLastChildBlock(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _TestRootChain.contract.Call(opts, &out, "getLastChildBlock") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// GetLastChildBlock is a free data retrieval call binding the contract method 0xb87e1b66. -// -// Solidity: function getLastChildBlock() view returns(uint256) -func (_TestRootChain *TestRootChainSession) GetLastChildBlock() (*big.Int, error) { - return _TestRootChain.Contract.GetLastChildBlock(&_TestRootChain.CallOpts) -} - -// GetLastChildBlock is a free data retrieval call binding the contract method 0xb87e1b66. -// -// Solidity: function getLastChildBlock() view returns(uint256) -func (_TestRootChain *TestRootChainCallerSession) GetLastChildBlock() (*big.Int, error) { - return _TestRootChain.Contract.GetLastChildBlock(&_TestRootChain.CallOpts) -} - -// HeaderBlocks is a free data retrieval call binding the contract method 0x41539d4a. -// -// Solidity: function headerBlocks(uint256 ) view returns(bytes32 root, uint256 start, uint256 end, uint256 createdAt, address proposer) -func (_TestRootChain *TestRootChainCaller) HeaderBlocks(opts *bind.CallOpts, arg0 *big.Int) (struct { - Root [32]byte - Start *big.Int - End *big.Int - CreatedAt *big.Int - Proposer common.Address -}, error) { - var out []interface{} - err := _TestRootChain.contract.Call(opts, &out, "headerBlocks", arg0) - - outstruct := new(struct { - Root [32]byte - Start *big.Int - End *big.Int - CreatedAt *big.Int - Proposer common.Address - }) - if err != nil { - return *outstruct, err - } - - outstruct.Root = *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) - outstruct.Start = *abi.ConvertType(out[1], new(*big.Int)).(**big.Int) - outstruct.End = *abi.ConvertType(out[2], new(*big.Int)).(**big.Int) - outstruct.CreatedAt = *abi.ConvertType(out[3], new(*big.Int)).(**big.Int) - outstruct.Proposer = *abi.ConvertType(out[4], new(common.Address)).(*common.Address) - - return *outstruct, err - -} - -// HeaderBlocks is a free data retrieval call binding the contract method 0x41539d4a. -// -// Solidity: function headerBlocks(uint256 ) view returns(bytes32 root, uint256 start, uint256 end, uint256 createdAt, address proposer) -func (_TestRootChain *TestRootChainSession) HeaderBlocks(arg0 *big.Int) (struct { - Root [32]byte - Start *big.Int - End *big.Int - CreatedAt *big.Int - Proposer common.Address -}, error) { - return _TestRootChain.Contract.HeaderBlocks(&_TestRootChain.CallOpts, arg0) -} - -// HeaderBlocks is a free data retrieval call binding the contract method 0x41539d4a. -// -// Solidity: function headerBlocks(uint256 ) view returns(bytes32 root, uint256 start, uint256 end, uint256 createdAt, address proposer) -func (_TestRootChain *TestRootChainCallerSession) HeaderBlocks(arg0 *big.Int) (struct { - Root [32]byte - Start *big.Int - End *big.Int - CreatedAt *big.Int - Proposer common.Address -}, error) { - return _TestRootChain.Contract.HeaderBlocks(&_TestRootChain.CallOpts, arg0) -} - -// HeimdallId is a free data retrieval call binding the contract method 0xfbc3dd36. -// -// Solidity: function heimdallId() view returns(bytes32) -func (_TestRootChain *TestRootChainCaller) HeimdallId(opts *bind.CallOpts) ([32]byte, error) { - var out []interface{} - err := _TestRootChain.contract.Call(opts, &out, "heimdallId") - - if err != nil { - return *new([32]byte), err - } - - out0 := *abi.ConvertType(out[0], new([32]byte)).(*[32]byte) - - return out0, err - -} - -// HeimdallId is a free data retrieval call binding the contract method 0xfbc3dd36. -// -// Solidity: function heimdallId() view returns(bytes32) -func (_TestRootChain *TestRootChainSession) HeimdallId() ([32]byte, error) { - return _TestRootChain.Contract.HeimdallId(&_TestRootChain.CallOpts) -} - -// HeimdallId is a free data retrieval call binding the contract method 0xfbc3dd36. -// -// Solidity: function heimdallId() view returns(bytes32) -func (_TestRootChain *TestRootChainCallerSession) HeimdallId() ([32]byte, error) { - return _TestRootChain.Contract.HeimdallId(&_TestRootChain.CallOpts) -} - -// NetworkId is a free data retrieval call binding the contract method 0x9025e64c. -// -// Solidity: function networkId() view returns(bytes) -func (_TestRootChain *TestRootChainCaller) NetworkId(opts *bind.CallOpts) ([]byte, error) { - var out []interface{} - err := _TestRootChain.contract.Call(opts, &out, "networkId") - - if err != nil { - return *new([]byte), err - } - - out0 := *abi.ConvertType(out[0], new([]byte)).(*[]byte) - - return out0, err - -} - -// NetworkId is a free data retrieval call binding the contract method 0x9025e64c. -// -// Solidity: function networkId() view returns(bytes) -func (_TestRootChain *TestRootChainSession) NetworkId() ([]byte, error) { - return _TestRootChain.Contract.NetworkId(&_TestRootChain.CallOpts) -} - -// NetworkId is a free data retrieval call binding the contract method 0x9025e64c. -// -// Solidity: function networkId() view returns(bytes) -func (_TestRootChain *TestRootChainCallerSession) NetworkId() ([]byte, error) { - return _TestRootChain.Contract.NetworkId(&_TestRootChain.CallOpts) -} - -// SubmitHeaderBlock is a free data retrieval call binding the contract method 0x6a791f11. -// -// Solidity: function submitHeaderBlock(bytes , bytes ) pure returns() -func (_TestRootChain *TestRootChainCaller) SubmitHeaderBlock(opts *bind.CallOpts, arg0 []byte, arg1 []byte) error { - var out []interface{} - err := _TestRootChain.contract.Call(opts, &out, "submitHeaderBlock", arg0, arg1) - - if err != nil { - return err - } - - return err - -} - -// SubmitHeaderBlock is a free data retrieval call binding the contract method 0x6a791f11. -// -// Solidity: function submitHeaderBlock(bytes , bytes ) pure returns() -func (_TestRootChain *TestRootChainSession) SubmitHeaderBlock(arg0 []byte, arg1 []byte) error { - return _TestRootChain.Contract.SubmitHeaderBlock(&_TestRootChain.CallOpts, arg0, arg1) -} - -// SubmitHeaderBlock is a free data retrieval call binding the contract method 0x6a791f11. -// -// Solidity: function submitHeaderBlock(bytes , bytes ) pure returns() -func (_TestRootChain *TestRootChainCallerSession) SubmitHeaderBlock(arg0 []byte, arg1 []byte) error { - return _TestRootChain.Contract.SubmitHeaderBlock(&_TestRootChain.CallOpts, arg0, arg1) -} - -// SetHeimdallId is a paid mutator transaction binding the contract method 0xea0688b3. -// -// Solidity: function setHeimdallId(string _heimdallId) returns() -func (_TestRootChain *TestRootChainTransactor) SetHeimdallId(opts *bind.TransactOpts, _heimdallId string) (types.Transaction, error) { - return _TestRootChain.contract.Transact(opts, "setHeimdallId", _heimdallId) -} - -// SetHeimdallId is a paid mutator transaction binding the contract method 0xea0688b3. -// -// Solidity: function setHeimdallId(string _heimdallId) returns() -func (_TestRootChain *TestRootChainSession) SetHeimdallId(_heimdallId string) (types.Transaction, error) { - return _TestRootChain.Contract.SetHeimdallId(&_TestRootChain.TransactOpts, _heimdallId) -} - -// SetHeimdallId is a paid mutator transaction binding the contract method 0xea0688b3. -// -// Solidity: function setHeimdallId(string _heimdallId) returns() -func (_TestRootChain *TestRootChainTransactorSession) SetHeimdallId(_heimdallId string) (types.Transaction, error) { - return _TestRootChain.Contract.SetHeimdallId(&_TestRootChain.TransactOpts, _heimdallId) -} - -// SetNextHeaderBlock is a paid mutator transaction binding the contract method 0xcf24a0ea. -// -// Solidity: function setNextHeaderBlock(uint256 _value) returns() -func (_TestRootChain *TestRootChainTransactor) SetNextHeaderBlock(opts *bind.TransactOpts, _value *big.Int) (types.Transaction, error) { - return _TestRootChain.contract.Transact(opts, "setNextHeaderBlock", _value) -} - -// SetNextHeaderBlock is a paid mutator transaction binding the contract method 0xcf24a0ea. -// -// Solidity: function setNextHeaderBlock(uint256 _value) returns() -func (_TestRootChain *TestRootChainSession) SetNextHeaderBlock(_value *big.Int) (types.Transaction, error) { - return _TestRootChain.Contract.SetNextHeaderBlock(&_TestRootChain.TransactOpts, _value) -} - -// SetNextHeaderBlock is a paid mutator transaction binding the contract method 0xcf24a0ea. -// -// Solidity: function setNextHeaderBlock(uint256 _value) returns() -func (_TestRootChain *TestRootChainTransactorSession) SetNextHeaderBlock(_value *big.Int) (types.Transaction, error) { - return _TestRootChain.Contract.SetNextHeaderBlock(&_TestRootChain.TransactOpts, _value) -} - -// Slash is a paid mutator transaction binding the contract method 0x2da25de3. -// -// Solidity: function slash() returns() -func (_TestRootChain *TestRootChainTransactor) Slash(opts *bind.TransactOpts) (types.Transaction, error) { - return _TestRootChain.contract.Transact(opts, "slash") -} - -// Slash is a paid mutator transaction binding the contract method 0x2da25de3. -// -// Solidity: function slash() returns() -func (_TestRootChain *TestRootChainSession) Slash() (types.Transaction, error) { - return _TestRootChain.Contract.Slash(&_TestRootChain.TransactOpts) -} - -// Slash is a paid mutator transaction binding the contract method 0x2da25de3. -// -// Solidity: function slash() returns() -func (_TestRootChain *TestRootChainTransactorSession) Slash() (types.Transaction, error) { - return _TestRootChain.Contract.Slash(&_TestRootChain.TransactOpts) -} - -// SubmitCheckpoint is a paid mutator transaction binding the contract method 0x4e43e495. -// -// Solidity: function submitCheckpoint(bytes data, uint256[3][] ) returns() -func (_TestRootChain *TestRootChainTransactor) SubmitCheckpoint(opts *bind.TransactOpts, data []byte, arg1 [][3]*big.Int) (types.Transaction, error) { - return _TestRootChain.contract.Transact(opts, "submitCheckpoint", data, arg1) -} - -// SubmitCheckpoint is a paid mutator transaction binding the contract method 0x4e43e495. -// -// Solidity: function submitCheckpoint(bytes data, uint256[3][] ) returns() -func (_TestRootChain *TestRootChainSession) SubmitCheckpoint(data []byte, arg1 [][3]*big.Int) (types.Transaction, error) { - return _TestRootChain.Contract.SubmitCheckpoint(&_TestRootChain.TransactOpts, data, arg1) -} - -// SubmitCheckpoint is a paid mutator transaction binding the contract method 0x4e43e495. -// -// Solidity: function submitCheckpoint(bytes data, uint256[3][] ) returns() -func (_TestRootChain *TestRootChainTransactorSession) SubmitCheckpoint(data []byte, arg1 [][3]*big.Int) (types.Transaction, error) { - return _TestRootChain.Contract.SubmitCheckpoint(&_TestRootChain.TransactOpts, data, arg1) -} - -// UpdateDepositId is a paid mutator transaction binding the contract method 0x5391f483. -// -// Solidity: function updateDepositId(uint256 numDeposits) returns(uint256 depositId) -func (_TestRootChain *TestRootChainTransactor) UpdateDepositId(opts *bind.TransactOpts, numDeposits *big.Int) (types.Transaction, error) { - return _TestRootChain.contract.Transact(opts, "updateDepositId", numDeposits) -} - -// UpdateDepositId is a paid mutator transaction binding the contract method 0x5391f483. -// -// Solidity: function updateDepositId(uint256 numDeposits) returns(uint256 depositId) -func (_TestRootChain *TestRootChainSession) UpdateDepositId(numDeposits *big.Int) (types.Transaction, error) { - return _TestRootChain.Contract.UpdateDepositId(&_TestRootChain.TransactOpts, numDeposits) -} - -// UpdateDepositId is a paid mutator transaction binding the contract method 0x5391f483. -// -// Solidity: function updateDepositId(uint256 numDeposits) returns(uint256 depositId) -func (_TestRootChain *TestRootChainTransactorSession) UpdateDepositId(numDeposits *big.Int) (types.Transaction, error) { - return _TestRootChain.Contract.UpdateDepositId(&_TestRootChain.TransactOpts, numDeposits) -} - -// TestRootChainSetHeimdallIdParams is an auto generated read-only Go binding of transcaction calldata params -type TestRootChainSetHeimdallIdParams struct { - Param__heimdallId string -} - -// Parse SetHeimdallId method from calldata of a transaction -// -// Solidity: function setHeimdallId(string _heimdallId) returns() -func ParseTestRootChainSetHeimdallIdParams(calldata []byte) (*TestRootChainSetHeimdallIdParams, error) { - if len(calldata) <= 4 { - return nil, fmt.Errorf("invalid calldata input") - } - - _abi, err := abi.JSON(strings.NewReader(TestRootChainABI)) - if err != nil { - return nil, fmt.Errorf("failed to get abi of registry metadata: %w", err) - } - - out, err := _abi.Methods["setHeimdallId"].Inputs.Unpack(calldata[4:]) - if err != nil { - return nil, fmt.Errorf("failed to unpack setHeimdallId params data: %w", err) - } - - var paramsResult = new(TestRootChainSetHeimdallIdParams) - value := reflect.ValueOf(paramsResult).Elem() - - if value.NumField() != len(out) { - return nil, fmt.Errorf("failed to match calldata with param field number") - } - - out0 := *abi.ConvertType(out[0], new(string)).(*string) - - return &TestRootChainSetHeimdallIdParams{ - Param__heimdallId: out0, - }, nil -} - -// TestRootChainSetNextHeaderBlockParams is an auto generated read-only Go binding of transcaction calldata params -type TestRootChainSetNextHeaderBlockParams struct { - Param__value *big.Int -} - -// Parse SetNextHeaderBlock method from calldata of a transaction -// -// Solidity: function setNextHeaderBlock(uint256 _value) returns() -func ParseTestRootChainSetNextHeaderBlockParams(calldata []byte) (*TestRootChainSetNextHeaderBlockParams, error) { - if len(calldata) <= 4 { - return nil, fmt.Errorf("invalid calldata input") - } - - _abi, err := abi.JSON(strings.NewReader(TestRootChainABI)) - if err != nil { - return nil, fmt.Errorf("failed to get abi of registry metadata: %w", err) - } - - out, err := _abi.Methods["setNextHeaderBlock"].Inputs.Unpack(calldata[4:]) - if err != nil { - return nil, fmt.Errorf("failed to unpack setNextHeaderBlock params data: %w", err) - } - - var paramsResult = new(TestRootChainSetNextHeaderBlockParams) - value := reflect.ValueOf(paramsResult).Elem() - - if value.NumField() != len(out) { - return nil, fmt.Errorf("failed to match calldata with param field number") - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return &TestRootChainSetNextHeaderBlockParams{ - Param__value: out0, - }, nil -} - -// TestRootChainSubmitCheckpointParams is an auto generated read-only Go binding of transcaction calldata params -type TestRootChainSubmitCheckpointParams struct { - Param_data []byte - Param_arg1 [][3]*big.Int -} - -// Parse SubmitCheckpoint method from calldata of a transaction -// -// Solidity: function submitCheckpoint(bytes data, uint256[3][] ) returns() -func ParseTestRootChainSubmitCheckpointParams(calldata []byte) (*TestRootChainSubmitCheckpointParams, error) { - if len(calldata) <= 4 { - return nil, fmt.Errorf("invalid calldata input") - } - - _abi, err := abi.JSON(strings.NewReader(TestRootChainABI)) - if err != nil { - return nil, fmt.Errorf("failed to get abi of registry metadata: %w", err) - } - - out, err := _abi.Methods["submitCheckpoint"].Inputs.Unpack(calldata[4:]) - if err != nil { - return nil, fmt.Errorf("failed to unpack submitCheckpoint params data: %w", err) - } - - var paramsResult = new(TestRootChainSubmitCheckpointParams) - value := reflect.ValueOf(paramsResult).Elem() - - if value.NumField() != len(out) { - return nil, fmt.Errorf("failed to match calldata with param field number") - } - - out0 := *abi.ConvertType(out[0], new([]byte)).(*[]byte) - out1 := *abi.ConvertType(out[1], new([][3]*big.Int)).(*[][3]*big.Int) - - return &TestRootChainSubmitCheckpointParams{ - Param_data: out0, Param_arg1: out1, - }, nil -} - -// TestRootChainUpdateDepositIdParams is an auto generated read-only Go binding of transcaction calldata params -type TestRootChainUpdateDepositIdParams struct { - Param_numDeposits *big.Int -} - -// Parse UpdateDepositId method from calldata of a transaction -// -// Solidity: function updateDepositId(uint256 numDeposits) returns(uint256 depositId) -func ParseTestRootChainUpdateDepositIdParams(calldata []byte) (*TestRootChainUpdateDepositIdParams, error) { - if len(calldata) <= 4 { - return nil, fmt.Errorf("invalid calldata input") - } - - _abi, err := abi.JSON(strings.NewReader(TestRootChainABI)) - if err != nil { - return nil, fmt.Errorf("failed to get abi of registry metadata: %w", err) - } - - out, err := _abi.Methods["updateDepositId"].Inputs.Unpack(calldata[4:]) - if err != nil { - return nil, fmt.Errorf("failed to unpack updateDepositId params data: %w", err) - } - - var paramsResult = new(TestRootChainUpdateDepositIdParams) - value := reflect.ValueOf(paramsResult).Elem() - - if value.NumField() != len(out) { - return nil, fmt.Errorf("failed to match calldata with param field number") - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return &TestRootChainUpdateDepositIdParams{ - Param_numDeposits: out0, - }, nil -} - -// TestRootChainNewHeaderBlockIterator is returned from FilterNewHeaderBlock and is used to iterate over the raw logs and unpacked data for NewHeaderBlock events raised by the TestRootChain contract. -type TestRootChainNewHeaderBlockIterator struct { - Event *TestRootChainNewHeaderBlock // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *TestRootChainNewHeaderBlockIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(TestRootChainNewHeaderBlock) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(TestRootChainNewHeaderBlock) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *TestRootChainNewHeaderBlockIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *TestRootChainNewHeaderBlockIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// TestRootChainNewHeaderBlock represents a NewHeaderBlock event raised by the TestRootChain contract. -type TestRootChainNewHeaderBlock struct { - Proposer common.Address - HeaderBlockId *big.Int - Reward *big.Int - Start *big.Int - End *big.Int - Root [32]byte - Raw types.Log // Blockchain specific contextual infos -} - -func (_TestRootChain *TestRootChainFilterer) NewHeaderBlockEventID() common.Hash { - return common.HexToHash("0xba5de06d22af2685c6c7765f60067f7d2b08c2d29f53cdf14d67f6d1c9bfb527") -} - -// FilterNewHeaderBlock is a free log retrieval operation binding the contract event 0xba5de06d22af2685c6c7765f60067f7d2b08c2d29f53cdf14d67f6d1c9bfb527. -// -// Solidity: event NewHeaderBlock(address indexed proposer, uint256 indexed headerBlockId, uint256 indexed reward, uint256 start, uint256 end, bytes32 root) -func (_TestRootChain *TestRootChainFilterer) FilterNewHeaderBlock(opts *bind.FilterOpts, proposer []common.Address, headerBlockId []*big.Int, reward []*big.Int) (*TestRootChainNewHeaderBlockIterator, error) { - - var proposerRule []interface{} - for _, proposerItem := range proposer { - proposerRule = append(proposerRule, proposerItem) - } - var headerBlockIdRule []interface{} - for _, headerBlockIdItem := range headerBlockId { - headerBlockIdRule = append(headerBlockIdRule, headerBlockIdItem) - } - var rewardRule []interface{} - for _, rewardItem := range reward { - rewardRule = append(rewardRule, rewardItem) - } - - logs, sub, err := _TestRootChain.contract.FilterLogs(opts, "NewHeaderBlock", proposerRule, headerBlockIdRule, rewardRule) - if err != nil { - return nil, err - } - return &TestRootChainNewHeaderBlockIterator{contract: _TestRootChain.contract, event: "NewHeaderBlock", logs: logs, sub: sub}, nil -} - -// WatchNewHeaderBlock is a free log subscription operation binding the contract event 0xba5de06d22af2685c6c7765f60067f7d2b08c2d29f53cdf14d67f6d1c9bfb527. -// -// Solidity: event NewHeaderBlock(address indexed proposer, uint256 indexed headerBlockId, uint256 indexed reward, uint256 start, uint256 end, bytes32 root) -func (_TestRootChain *TestRootChainFilterer) WatchNewHeaderBlock(opts *bind.WatchOpts, sink chan<- *TestRootChainNewHeaderBlock, proposer []common.Address, headerBlockId []*big.Int, reward []*big.Int) (event.Subscription, error) { - - var proposerRule []interface{} - for _, proposerItem := range proposer { - proposerRule = append(proposerRule, proposerItem) - } - var headerBlockIdRule []interface{} - for _, headerBlockIdItem := range headerBlockId { - headerBlockIdRule = append(headerBlockIdRule, headerBlockIdItem) - } - var rewardRule []interface{} - for _, rewardItem := range reward { - rewardRule = append(rewardRule, rewardItem) - } - - logs, sub, err := _TestRootChain.contract.WatchLogs(opts, "NewHeaderBlock", proposerRule, headerBlockIdRule, rewardRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(TestRootChainNewHeaderBlock) - if err := _TestRootChain.contract.UnpackLog(event, "NewHeaderBlock", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseNewHeaderBlock is a log parse operation binding the contract event 0xba5de06d22af2685c6c7765f60067f7d2b08c2d29f53cdf14d67f6d1c9bfb527. -// -// Solidity: event NewHeaderBlock(address indexed proposer, uint256 indexed headerBlockId, uint256 indexed reward, uint256 start, uint256 end, bytes32 root) -func (_TestRootChain *TestRootChainFilterer) ParseNewHeaderBlock(log types.Log) (*TestRootChainNewHeaderBlock, error) { - event := new(TestRootChainNewHeaderBlock) - if err := _TestRootChain.contract.UnpackLog(event, "NewHeaderBlock", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// TestRootChainResetHeaderBlockIterator is returned from FilterResetHeaderBlock and is used to iterate over the raw logs and unpacked data for ResetHeaderBlock events raised by the TestRootChain contract. -type TestRootChainResetHeaderBlockIterator struct { - Event *TestRootChainResetHeaderBlock // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *TestRootChainResetHeaderBlockIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(TestRootChainResetHeaderBlock) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(TestRootChainResetHeaderBlock) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *TestRootChainResetHeaderBlockIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *TestRootChainResetHeaderBlockIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// TestRootChainResetHeaderBlock represents a ResetHeaderBlock event raised by the TestRootChain contract. -type TestRootChainResetHeaderBlock struct { - Proposer common.Address - HeaderBlockId *big.Int - Raw types.Log // Blockchain specific contextual infos -} - -func (_TestRootChain *TestRootChainFilterer) ResetHeaderBlockEventID() common.Hash { - return common.HexToHash("0xca1d8316287f938830e225956a7bb10fd5a1a1506dd2eb3a476751a488117205") -} - -// FilterResetHeaderBlock is a free log retrieval operation binding the contract event 0xca1d8316287f938830e225956a7bb10fd5a1a1506dd2eb3a476751a488117205. -// -// Solidity: event ResetHeaderBlock(address indexed proposer, uint256 indexed headerBlockId) -func (_TestRootChain *TestRootChainFilterer) FilterResetHeaderBlock(opts *bind.FilterOpts, proposer []common.Address, headerBlockId []*big.Int) (*TestRootChainResetHeaderBlockIterator, error) { - - var proposerRule []interface{} - for _, proposerItem := range proposer { - proposerRule = append(proposerRule, proposerItem) - } - var headerBlockIdRule []interface{} - for _, headerBlockIdItem := range headerBlockId { - headerBlockIdRule = append(headerBlockIdRule, headerBlockIdItem) - } - - logs, sub, err := _TestRootChain.contract.FilterLogs(opts, "ResetHeaderBlock", proposerRule, headerBlockIdRule) - if err != nil { - return nil, err - } - return &TestRootChainResetHeaderBlockIterator{contract: _TestRootChain.contract, event: "ResetHeaderBlock", logs: logs, sub: sub}, nil -} - -// WatchResetHeaderBlock is a free log subscription operation binding the contract event 0xca1d8316287f938830e225956a7bb10fd5a1a1506dd2eb3a476751a488117205. -// -// Solidity: event ResetHeaderBlock(address indexed proposer, uint256 indexed headerBlockId) -func (_TestRootChain *TestRootChainFilterer) WatchResetHeaderBlock(opts *bind.WatchOpts, sink chan<- *TestRootChainResetHeaderBlock, proposer []common.Address, headerBlockId []*big.Int) (event.Subscription, error) { - - var proposerRule []interface{} - for _, proposerItem := range proposer { - proposerRule = append(proposerRule, proposerItem) - } - var headerBlockIdRule []interface{} - for _, headerBlockIdItem := range headerBlockId { - headerBlockIdRule = append(headerBlockIdRule, headerBlockIdItem) - } - - logs, sub, err := _TestRootChain.contract.WatchLogs(opts, "ResetHeaderBlock", proposerRule, headerBlockIdRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(TestRootChainResetHeaderBlock) - if err := _TestRootChain.contract.UnpackLog(event, "ResetHeaderBlock", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseResetHeaderBlock is a log parse operation binding the contract event 0xca1d8316287f938830e225956a7bb10fd5a1a1506dd2eb3a476751a488117205. -// -// Solidity: event ResetHeaderBlock(address indexed proposer, uint256 indexed headerBlockId) -func (_TestRootChain *TestRootChainFilterer) ParseResetHeaderBlock(log types.Log) (*TestRootChainResetHeaderBlock, error) { - event := new(TestRootChainResetHeaderBlock) - if err := _TestRootChain.contract.UnpackLog(event, "ResetHeaderBlock", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/cmd/devnet/contracts/gen_teststatesender.go b/cmd/devnet/contracts/gen_teststatesender.go deleted file mode 100644 index c8547505775..00000000000 --- a/cmd/devnet/contracts/gen_teststatesender.go +++ /dev/null @@ -1,865 +0,0 @@ -// Code generated by abigen. DO NOT EDIT. -// This file is a generated binding and any manual changes will be lost. - -package contracts - -import ( - "fmt" - "math/big" - "reflect" - "strings" - - ethereum "github.com/erigontech/erigon" - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon/execution/abi" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/execution/types" - "github.com/erigontech/erigon/p2p/event" -) - -// Reference imports to suppress errors if they are not otherwise used. -var ( - _ = big.NewInt - _ = strings.NewReader - _ = ethereum.NotFound - _ = bind.Bind - _ = common.Big1 - _ = types.BloomLookup - _ = event.NewSubscription - _ = fmt.Errorf - _ = reflect.ValueOf -) - -// TestStateSenderABI is the input ABI used to generate the binding from. -const TestStateSenderABI = "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"user\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"}],\"name\":\"NewRegistration\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"address\",\"name\":\"user\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"}],\"name\":\"RegistrationUpdated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"internalType\":\"uint256\",\"name\":\"id\",\"type\":\"uint256\"},{\"indexed\":true,\"internalType\":\"address\",\"name\":\"contractAddress\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"StateSynced\",\"type\":\"event\"},{\"inputs\":[],\"name\":\"counter\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"sender\",\"type\":\"address\"},{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"}],\"name\":\"register\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"registrations\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"internalType\":\"address\",\"name\":\"receiver\",\"type\":\"address\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"syncState\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - -// TestStateSenderBin is the compiled bytecode used for deploying new contracts. -var TestStateSenderBin = "0x608060405234801561001057600080fd5b50610366806100206000396000f3fe608060405234801561001057600080fd5b506004361061004c5760003560e01c806316f198311461005157806361bc221a14610066578063942e6bcf14610082578063aa677354146100c3575b600080fd5b61006461005f366004610202565b6100d6565b005b61006f60005481565b6040519081526020015b60405180910390f35b6100ab610090366004610285565b6001602052600090815260409020546001600160a01b031681565b6040516001600160a01b039091168152602001610079565b6100646100d13660046102a7565b610137565b8260005460016100e691906102da565b60008190556040516001600160a01b03861691907f103fed9db65eac19c4d870f49ab7520fe03b99f1838e5996caf47e9e43308392906101299087908790610301565b60405180910390a350505050565b6001600160a01b03818116600090815260016020526040902080546001600160a01b03191691841691821790556101a7576040516001600160a01b03808316919084169033907f3f4512aacd7a664fdb321a48e8340120d63253a91c6367a143abd19ecf68aedd90600090a45050565b6040516001600160a01b03808316919084169033907fc51cb1a93ec91e927852b3445875ec77b148271953e5c0b43698c968ad6fc47d90600090a45050565b80356001600160a01b03811681146101fd57600080fd5b919050565b60008060006040848603121561021757600080fd5b610220846101e6565b9250602084013567ffffffffffffffff8082111561023d57600080fd5b818601915086601f83011261025157600080fd5b81358181111561026057600080fd5b87602082850101111561027257600080fd5b6020830194508093505050509250925092565b60006020828403121561029757600080fd5b6102a0826101e6565b9392505050565b600080604083850312156102ba57600080fd5b6102c3836101e6565b91506102d1602084016101e6565b90509250929050565b808201808211156102fb57634e487b7160e01b600052601160045260246000fd5b92915050565b60208152816020820152818360408301376000818301604090810191909152601f909201601f1916010191905056fea2646970667358221220503899fb2efad396cb70e03842531a8cc17c120a711e076fcab0878258e1c2bf64736f6c63430008140033" - -// DeployTestStateSender deploys a new Ethereum contract, binding an instance of TestStateSender to it. -func DeployTestStateSender(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, types.Transaction, *TestStateSender, error) { - parsed, err := abi.JSON(strings.NewReader(TestStateSenderABI)) - if err != nil { - return common.Address{}, nil, nil, err - } - - address, tx, contract, err := bind.DeployContract(auth, parsed, common.FromHex(TestStateSenderBin), backend) - if err != nil { - return common.Address{}, nil, nil, err - } - return address, tx, &TestStateSender{TestStateSenderCaller: TestStateSenderCaller{contract: contract}, TestStateSenderTransactor: TestStateSenderTransactor{contract: contract}, TestStateSenderFilterer: TestStateSenderFilterer{contract: contract}}, nil -} - -// TestStateSender is an auto generated Go binding around an Ethereum contract. -type TestStateSender struct { - TestStateSenderCaller // Read-only binding to the contract - TestStateSenderTransactor // Write-only binding to the contract - TestStateSenderFilterer // Log filterer for contract events -} - -// TestStateSenderCaller is an auto generated read-only Go binding around an Ethereum contract. -type TestStateSenderCaller struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// TestStateSenderTransactor is an auto generated write-only Go binding around an Ethereum contract. -type TestStateSenderTransactor struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// TestStateSenderFilterer is an auto generated log filtering Go binding around an Ethereum contract events. -type TestStateSenderFilterer struct { - contract *bind.BoundContract // Generic contract wrapper for the low level calls -} - -// TestStateSenderSession is an auto generated Go binding around an Ethereum contract, -// with pre-set call and transact options. -type TestStateSenderSession struct { - Contract *TestStateSender // Generic contract binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// TestStateSenderCallerSession is an auto generated read-only Go binding around an Ethereum contract, -// with pre-set call options. -type TestStateSenderCallerSession struct { - Contract *TestStateSenderCaller // Generic contract caller binding to set the session for - CallOpts bind.CallOpts // Call options to use throughout this session -} - -// TestStateSenderTransactorSession is an auto generated write-only Go binding around an Ethereum contract, -// with pre-set transact options. -type TestStateSenderTransactorSession struct { - Contract *TestStateSenderTransactor // Generic contract transactor binding to set the session for - TransactOpts bind.TransactOpts // Transaction auth options to use throughout this session -} - -// TestStateSenderRaw is an auto generated low-level Go binding around an Ethereum contract. -type TestStateSenderRaw struct { - Contract *TestStateSender // Generic contract binding to access the raw methods on -} - -// TestStateSenderCallerRaw is an auto generated low-level read-only Go binding around an Ethereum contract. -type TestStateSenderCallerRaw struct { - Contract *TestStateSenderCaller // Generic read-only contract binding to access the raw methods on -} - -// TestStateSenderTransactorRaw is an auto generated low-level write-only Go binding around an Ethereum contract. -type TestStateSenderTransactorRaw struct { - Contract *TestStateSenderTransactor // Generic write-only contract binding to access the raw methods on -} - -// NewTestStateSender creates a new instance of TestStateSender, bound to a specific deployed contract. -func NewTestStateSender(address common.Address, backend bind.ContractBackend) (*TestStateSender, error) { - contract, err := bindTestStateSender(address, backend, backend, backend) - if err != nil { - return nil, err - } - return &TestStateSender{TestStateSenderCaller: TestStateSenderCaller{contract: contract}, TestStateSenderTransactor: TestStateSenderTransactor{contract: contract}, TestStateSenderFilterer: TestStateSenderFilterer{contract: contract}}, nil -} - -// NewTestStateSenderCaller creates a new read-only instance of TestStateSender, bound to a specific deployed contract. -func NewTestStateSenderCaller(address common.Address, caller bind.ContractCaller) (*TestStateSenderCaller, error) { - contract, err := bindTestStateSender(address, caller, nil, nil) - if err != nil { - return nil, err - } - return &TestStateSenderCaller{contract: contract}, nil -} - -// NewTestStateSenderTransactor creates a new write-only instance of TestStateSender, bound to a specific deployed contract. -func NewTestStateSenderTransactor(address common.Address, transactor bind.ContractTransactor) (*TestStateSenderTransactor, error) { - contract, err := bindTestStateSender(address, nil, transactor, nil) - if err != nil { - return nil, err - } - return &TestStateSenderTransactor{contract: contract}, nil -} - -// NewTestStateSenderFilterer creates a new log filterer instance of TestStateSender, bound to a specific deployed contract. -func NewTestStateSenderFilterer(address common.Address, filterer bind.ContractFilterer) (*TestStateSenderFilterer, error) { - contract, err := bindTestStateSender(address, nil, nil, filterer) - if err != nil { - return nil, err - } - return &TestStateSenderFilterer{contract: contract}, nil -} - -// bindTestStateSender binds a generic wrapper to an already deployed contract. -func bindTestStateSender(address common.Address, caller bind.ContractCaller, transactor bind.ContractTransactor, filterer bind.ContractFilterer) (*bind.BoundContract, error) { - parsed, err := abi.JSON(strings.NewReader(TestStateSenderABI)) - if err != nil { - return nil, err - } - return bind.NewBoundContract(address, parsed, caller, transactor, filterer), nil -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_TestStateSender *TestStateSenderRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _TestStateSender.Contract.TestStateSenderCaller.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_TestStateSender *TestStateSenderRaw) Transfer(opts *bind.TransactOpts) (types.Transaction, error) { - return _TestStateSender.Contract.TestStateSenderTransactor.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_TestStateSender *TestStateSenderRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (types.Transaction, error) { - return _TestStateSender.Contract.TestStateSenderTransactor.contract.Transact(opts, method, params...) -} - -// Call invokes the (constant) contract method with params as input values and -// sets the output to result. The result type might be a single field for simple -// returns, a slice of interfaces for anonymous returns and a struct for named -// returns. -func (_TestStateSender *TestStateSenderCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error { - return _TestStateSender.Contract.contract.Call(opts, result, method, params...) -} - -// Transfer initiates a plain transaction to move funds to the contract, calling -// its default method if one is available. -func (_TestStateSender *TestStateSenderTransactorRaw) Transfer(opts *bind.TransactOpts) (types.Transaction, error) { - return _TestStateSender.Contract.contract.Transfer(opts) -} - -// Transact invokes the (paid) contract method with params as input values. -func (_TestStateSender *TestStateSenderTransactorRaw) Transact(opts *bind.TransactOpts, method string, params ...interface{}) (types.Transaction, error) { - return _TestStateSender.Contract.contract.Transact(opts, method, params...) -} - -// Counter is a free data retrieval call binding the contract method 0x61bc221a. -// -// Solidity: function counter() view returns(uint256) -func (_TestStateSender *TestStateSenderCaller) Counter(opts *bind.CallOpts) (*big.Int, error) { - var out []interface{} - err := _TestStateSender.contract.Call(opts, &out, "counter") - - if err != nil { - return *new(*big.Int), err - } - - out0 := *abi.ConvertType(out[0], new(*big.Int)).(**big.Int) - - return out0, err - -} - -// Counter is a free data retrieval call binding the contract method 0x61bc221a. -// -// Solidity: function counter() view returns(uint256) -func (_TestStateSender *TestStateSenderSession) Counter() (*big.Int, error) { - return _TestStateSender.Contract.Counter(&_TestStateSender.CallOpts) -} - -// Counter is a free data retrieval call binding the contract method 0x61bc221a. -// -// Solidity: function counter() view returns(uint256) -func (_TestStateSender *TestStateSenderCallerSession) Counter() (*big.Int, error) { - return _TestStateSender.Contract.Counter(&_TestStateSender.CallOpts) -} - -// Registrations is a free data retrieval call binding the contract method 0x942e6bcf. -// -// Solidity: function registrations(address ) view returns(address) -func (_TestStateSender *TestStateSenderCaller) Registrations(opts *bind.CallOpts, arg0 common.Address) (common.Address, error) { - var out []interface{} - err := _TestStateSender.contract.Call(opts, &out, "registrations", arg0) - - if err != nil { - return *new(common.Address), err - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - - return out0, err - -} - -// Registrations is a free data retrieval call binding the contract method 0x942e6bcf. -// -// Solidity: function registrations(address ) view returns(address) -func (_TestStateSender *TestStateSenderSession) Registrations(arg0 common.Address) (common.Address, error) { - return _TestStateSender.Contract.Registrations(&_TestStateSender.CallOpts, arg0) -} - -// Registrations is a free data retrieval call binding the contract method 0x942e6bcf. -// -// Solidity: function registrations(address ) view returns(address) -func (_TestStateSender *TestStateSenderCallerSession) Registrations(arg0 common.Address) (common.Address, error) { - return _TestStateSender.Contract.Registrations(&_TestStateSender.CallOpts, arg0) -} - -// Register is a paid mutator transaction binding the contract method 0xaa677354. -// -// Solidity: function register(address sender, address receiver) returns() -func (_TestStateSender *TestStateSenderTransactor) Register(opts *bind.TransactOpts, sender common.Address, receiver common.Address) (types.Transaction, error) { - return _TestStateSender.contract.Transact(opts, "register", sender, receiver) -} - -// Register is a paid mutator transaction binding the contract method 0xaa677354. -// -// Solidity: function register(address sender, address receiver) returns() -func (_TestStateSender *TestStateSenderSession) Register(sender common.Address, receiver common.Address) (types.Transaction, error) { - return _TestStateSender.Contract.Register(&_TestStateSender.TransactOpts, sender, receiver) -} - -// Register is a paid mutator transaction binding the contract method 0xaa677354. -// -// Solidity: function register(address sender, address receiver) returns() -func (_TestStateSender *TestStateSenderTransactorSession) Register(sender common.Address, receiver common.Address) (types.Transaction, error) { - return _TestStateSender.Contract.Register(&_TestStateSender.TransactOpts, sender, receiver) -} - -// SyncState is a paid mutator transaction binding the contract method 0x16f19831. -// -// Solidity: function syncState(address receiver, bytes data) returns() -func (_TestStateSender *TestStateSenderTransactor) SyncState(opts *bind.TransactOpts, receiver common.Address, data []byte) (types.Transaction, error) { - return _TestStateSender.contract.Transact(opts, "syncState", receiver, data) -} - -// SyncState is a paid mutator transaction binding the contract method 0x16f19831. -// -// Solidity: function syncState(address receiver, bytes data) returns() -func (_TestStateSender *TestStateSenderSession) SyncState(receiver common.Address, data []byte) (types.Transaction, error) { - return _TestStateSender.Contract.SyncState(&_TestStateSender.TransactOpts, receiver, data) -} - -// SyncState is a paid mutator transaction binding the contract method 0x16f19831. -// -// Solidity: function syncState(address receiver, bytes data) returns() -func (_TestStateSender *TestStateSenderTransactorSession) SyncState(receiver common.Address, data []byte) (types.Transaction, error) { - return _TestStateSender.Contract.SyncState(&_TestStateSender.TransactOpts, receiver, data) -} - -// TestStateSenderRegisterParams is an auto generated read-only Go binding of transcaction calldata params -type TestStateSenderRegisterParams struct { - Param_sender common.Address - Param_receiver common.Address -} - -// Parse Register method from calldata of a transaction -// -// Solidity: function register(address sender, address receiver) returns() -func ParseTestStateSenderRegisterParams(calldata []byte) (*TestStateSenderRegisterParams, error) { - if len(calldata) <= 4 { - return nil, fmt.Errorf("invalid calldata input") - } - - _abi, err := abi.JSON(strings.NewReader(TestStateSenderABI)) - if err != nil { - return nil, fmt.Errorf("failed to get abi of registry metadata: %w", err) - } - - out, err := _abi.Methods["register"].Inputs.Unpack(calldata[4:]) - if err != nil { - return nil, fmt.Errorf("failed to unpack register params data: %w", err) - } - - var paramsResult = new(TestStateSenderRegisterParams) - value := reflect.ValueOf(paramsResult).Elem() - - if value.NumField() != len(out) { - return nil, fmt.Errorf("failed to match calldata with param field number") - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - out1 := *abi.ConvertType(out[1], new(common.Address)).(*common.Address) - - return &TestStateSenderRegisterParams{ - Param_sender: out0, Param_receiver: out1, - }, nil -} - -// TestStateSenderSyncStateParams is an auto generated read-only Go binding of transcaction calldata params -type TestStateSenderSyncStateParams struct { - Param_receiver common.Address - Param_data []byte -} - -// Parse SyncState method from calldata of a transaction -// -// Solidity: function syncState(address receiver, bytes data) returns() -func ParseTestStateSenderSyncStateParams(calldata []byte) (*TestStateSenderSyncStateParams, error) { - if len(calldata) <= 4 { - return nil, fmt.Errorf("invalid calldata input") - } - - _abi, err := abi.JSON(strings.NewReader(TestStateSenderABI)) - if err != nil { - return nil, fmt.Errorf("failed to get abi of registry metadata: %w", err) - } - - out, err := _abi.Methods["syncState"].Inputs.Unpack(calldata[4:]) - if err != nil { - return nil, fmt.Errorf("failed to unpack syncState params data: %w", err) - } - - var paramsResult = new(TestStateSenderSyncStateParams) - value := reflect.ValueOf(paramsResult).Elem() - - if value.NumField() != len(out) { - return nil, fmt.Errorf("failed to match calldata with param field number") - } - - out0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address) - out1 := *abi.ConvertType(out[1], new([]byte)).(*[]byte) - - return &TestStateSenderSyncStateParams{ - Param_receiver: out0, Param_data: out1, - }, nil -} - -// TestStateSenderNewRegistrationIterator is returned from FilterNewRegistration and is used to iterate over the raw logs and unpacked data for NewRegistration events raised by the TestStateSender contract. -type TestStateSenderNewRegistrationIterator struct { - Event *TestStateSenderNewRegistration // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *TestStateSenderNewRegistrationIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(TestStateSenderNewRegistration) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(TestStateSenderNewRegistration) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *TestStateSenderNewRegistrationIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *TestStateSenderNewRegistrationIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// TestStateSenderNewRegistration represents a NewRegistration event raised by the TestStateSender contract. -type TestStateSenderNewRegistration struct { - User common.Address - Sender common.Address - Receiver common.Address - Raw types.Log // Blockchain specific contextual infos -} - -func (_TestStateSender *TestStateSenderFilterer) NewRegistrationEventID() common.Hash { - return common.HexToHash("0x3f4512aacd7a664fdb321a48e8340120d63253a91c6367a143abd19ecf68aedd") -} - -// FilterNewRegistration is a free log retrieval operation binding the contract event 0x3f4512aacd7a664fdb321a48e8340120d63253a91c6367a143abd19ecf68aedd. -// -// Solidity: event NewRegistration(address indexed user, address indexed sender, address indexed receiver) -func (_TestStateSender *TestStateSenderFilterer) FilterNewRegistration(opts *bind.FilterOpts, user []common.Address, sender []common.Address, receiver []common.Address) (*TestStateSenderNewRegistrationIterator, error) { - - var userRule []interface{} - for _, userItem := range user { - userRule = append(userRule, userItem) - } - var senderRule []interface{} - for _, senderItem := range sender { - senderRule = append(senderRule, senderItem) - } - var receiverRule []interface{} - for _, receiverItem := range receiver { - receiverRule = append(receiverRule, receiverItem) - } - - logs, sub, err := _TestStateSender.contract.FilterLogs(opts, "NewRegistration", userRule, senderRule, receiverRule) - if err != nil { - return nil, err - } - return &TestStateSenderNewRegistrationIterator{contract: _TestStateSender.contract, event: "NewRegistration", logs: logs, sub: sub}, nil -} - -// WatchNewRegistration is a free log subscription operation binding the contract event 0x3f4512aacd7a664fdb321a48e8340120d63253a91c6367a143abd19ecf68aedd. -// -// Solidity: event NewRegistration(address indexed user, address indexed sender, address indexed receiver) -func (_TestStateSender *TestStateSenderFilterer) WatchNewRegistration(opts *bind.WatchOpts, sink chan<- *TestStateSenderNewRegistration, user []common.Address, sender []common.Address, receiver []common.Address) (event.Subscription, error) { - - var userRule []interface{} - for _, userItem := range user { - userRule = append(userRule, userItem) - } - var senderRule []interface{} - for _, senderItem := range sender { - senderRule = append(senderRule, senderItem) - } - var receiverRule []interface{} - for _, receiverItem := range receiver { - receiverRule = append(receiverRule, receiverItem) - } - - logs, sub, err := _TestStateSender.contract.WatchLogs(opts, "NewRegistration", userRule, senderRule, receiverRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(TestStateSenderNewRegistration) - if err := _TestStateSender.contract.UnpackLog(event, "NewRegistration", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseNewRegistration is a log parse operation binding the contract event 0x3f4512aacd7a664fdb321a48e8340120d63253a91c6367a143abd19ecf68aedd. -// -// Solidity: event NewRegistration(address indexed user, address indexed sender, address indexed receiver) -func (_TestStateSender *TestStateSenderFilterer) ParseNewRegistration(log types.Log) (*TestStateSenderNewRegistration, error) { - event := new(TestStateSenderNewRegistration) - if err := _TestStateSender.contract.UnpackLog(event, "NewRegistration", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// TestStateSenderRegistrationUpdatedIterator is returned from FilterRegistrationUpdated and is used to iterate over the raw logs and unpacked data for RegistrationUpdated events raised by the TestStateSender contract. -type TestStateSenderRegistrationUpdatedIterator struct { - Event *TestStateSenderRegistrationUpdated // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *TestStateSenderRegistrationUpdatedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(TestStateSenderRegistrationUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(TestStateSenderRegistrationUpdated) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *TestStateSenderRegistrationUpdatedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *TestStateSenderRegistrationUpdatedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// TestStateSenderRegistrationUpdated represents a RegistrationUpdated event raised by the TestStateSender contract. -type TestStateSenderRegistrationUpdated struct { - User common.Address - Sender common.Address - Receiver common.Address - Raw types.Log // Blockchain specific contextual infos -} - -func (_TestStateSender *TestStateSenderFilterer) RegistrationUpdatedEventID() common.Hash { - return common.HexToHash("0xc51cb1a93ec91e927852b3445875ec77b148271953e5c0b43698c968ad6fc47d") -} - -// FilterRegistrationUpdated is a free log retrieval operation binding the contract event 0xc51cb1a93ec91e927852b3445875ec77b148271953e5c0b43698c968ad6fc47d. -// -// Solidity: event RegistrationUpdated(address indexed user, address indexed sender, address indexed receiver) -func (_TestStateSender *TestStateSenderFilterer) FilterRegistrationUpdated(opts *bind.FilterOpts, user []common.Address, sender []common.Address, receiver []common.Address) (*TestStateSenderRegistrationUpdatedIterator, error) { - - var userRule []interface{} - for _, userItem := range user { - userRule = append(userRule, userItem) - } - var senderRule []interface{} - for _, senderItem := range sender { - senderRule = append(senderRule, senderItem) - } - var receiverRule []interface{} - for _, receiverItem := range receiver { - receiverRule = append(receiverRule, receiverItem) - } - - logs, sub, err := _TestStateSender.contract.FilterLogs(opts, "RegistrationUpdated", userRule, senderRule, receiverRule) - if err != nil { - return nil, err - } - return &TestStateSenderRegistrationUpdatedIterator{contract: _TestStateSender.contract, event: "RegistrationUpdated", logs: logs, sub: sub}, nil -} - -// WatchRegistrationUpdated is a free log subscription operation binding the contract event 0xc51cb1a93ec91e927852b3445875ec77b148271953e5c0b43698c968ad6fc47d. -// -// Solidity: event RegistrationUpdated(address indexed user, address indexed sender, address indexed receiver) -func (_TestStateSender *TestStateSenderFilterer) WatchRegistrationUpdated(opts *bind.WatchOpts, sink chan<- *TestStateSenderRegistrationUpdated, user []common.Address, sender []common.Address, receiver []common.Address) (event.Subscription, error) { - - var userRule []interface{} - for _, userItem := range user { - userRule = append(userRule, userItem) - } - var senderRule []interface{} - for _, senderItem := range sender { - senderRule = append(senderRule, senderItem) - } - var receiverRule []interface{} - for _, receiverItem := range receiver { - receiverRule = append(receiverRule, receiverItem) - } - - logs, sub, err := _TestStateSender.contract.WatchLogs(opts, "RegistrationUpdated", userRule, senderRule, receiverRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(TestStateSenderRegistrationUpdated) - if err := _TestStateSender.contract.UnpackLog(event, "RegistrationUpdated", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseRegistrationUpdated is a log parse operation binding the contract event 0xc51cb1a93ec91e927852b3445875ec77b148271953e5c0b43698c968ad6fc47d. -// -// Solidity: event RegistrationUpdated(address indexed user, address indexed sender, address indexed receiver) -func (_TestStateSender *TestStateSenderFilterer) ParseRegistrationUpdated(log types.Log) (*TestStateSenderRegistrationUpdated, error) { - event := new(TestStateSenderRegistrationUpdated) - if err := _TestStateSender.contract.UnpackLog(event, "RegistrationUpdated", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} - -// TestStateSenderStateSyncedIterator is returned from FilterStateSynced and is used to iterate over the raw logs and unpacked data for StateSynced events raised by the TestStateSender contract. -type TestStateSenderStateSyncedIterator struct { - Event *TestStateSenderStateSynced // Event containing the contract specifics and raw log - - contract *bind.BoundContract // Generic contract to use for unpacking event data - event string // Event name to use for unpacking event data - - logs chan types.Log // Log channel receiving the found contract events - sub ethereum.Subscription // Subscription for errors, completion and termination - done bool // Whether the subscription completed delivering logs - fail error // Occurred error to stop iteration -} - -// Next advances the iterator to the subsequent event, returning whether there -// are any more events found. In case of a retrieval or parsing error, false is -// returned and Error() can be queried for the exact failure. -func (it *TestStateSenderStateSyncedIterator) Next() bool { - // If the iterator failed, stop iterating - if it.fail != nil { - return false - } - // If the iterator completed, deliver directly whatever's available - if it.done { - select { - case log := <-it.logs: - it.Event = new(TestStateSenderStateSynced) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - default: - return false - } - } - // Iterator still in progress, wait for either a data or an error event - select { - case log := <-it.logs: - it.Event = new(TestStateSenderStateSynced) - if err := it.contract.UnpackLog(it.Event, it.event, log); err != nil { - it.fail = err - return false - } - it.Event.Raw = log - return true - - case err := <-it.sub.Err(): - it.done = true - it.fail = err - return it.Next() - } -} - -// Error returns any retrieval or parsing error occurred during filtering. -func (it *TestStateSenderStateSyncedIterator) Error() error { - return it.fail -} - -// Close terminates the iteration process, releasing any pending underlying -// resources. -func (it *TestStateSenderStateSyncedIterator) Close() error { - it.sub.Unsubscribe() - return nil -} - -// TestStateSenderStateSynced represents a StateSynced event raised by the TestStateSender contract. -type TestStateSenderStateSynced struct { - Id *big.Int - ContractAddress common.Address - Data []byte - Raw types.Log // Blockchain specific contextual infos -} - -func (_TestStateSender *TestStateSenderFilterer) StateSyncedEventID() common.Hash { - return common.HexToHash("0x103fed9db65eac19c4d870f49ab7520fe03b99f1838e5996caf47e9e43308392") -} - -// FilterStateSynced is a free log retrieval operation binding the contract event 0x103fed9db65eac19c4d870f49ab7520fe03b99f1838e5996caf47e9e43308392. -// -// Solidity: event StateSynced(uint256 indexed id, address indexed contractAddress, bytes data) -func (_TestStateSender *TestStateSenderFilterer) FilterStateSynced(opts *bind.FilterOpts, id []*big.Int, contractAddress []common.Address) (*TestStateSenderStateSyncedIterator, error) { - - var idRule []interface{} - for _, idItem := range id { - idRule = append(idRule, idItem) - } - var contractAddressRule []interface{} - for _, contractAddressItem := range contractAddress { - contractAddressRule = append(contractAddressRule, contractAddressItem) - } - - logs, sub, err := _TestStateSender.contract.FilterLogs(opts, "StateSynced", idRule, contractAddressRule) - if err != nil { - return nil, err - } - return &TestStateSenderStateSyncedIterator{contract: _TestStateSender.contract, event: "StateSynced", logs: logs, sub: sub}, nil -} - -// WatchStateSynced is a free log subscription operation binding the contract event 0x103fed9db65eac19c4d870f49ab7520fe03b99f1838e5996caf47e9e43308392. -// -// Solidity: event StateSynced(uint256 indexed id, address indexed contractAddress, bytes data) -func (_TestStateSender *TestStateSenderFilterer) WatchStateSynced(opts *bind.WatchOpts, sink chan<- *TestStateSenderStateSynced, id []*big.Int, contractAddress []common.Address) (event.Subscription, error) { - - var idRule []interface{} - for _, idItem := range id { - idRule = append(idRule, idItem) - } - var contractAddressRule []interface{} - for _, contractAddressItem := range contractAddress { - contractAddressRule = append(contractAddressRule, contractAddressItem) - } - - logs, sub, err := _TestStateSender.contract.WatchLogs(opts, "StateSynced", idRule, contractAddressRule) - if err != nil { - return nil, err - } - return event.NewSubscription(func(quit <-chan struct{}) error { - defer sub.Unsubscribe() - for { - select { - case log := <-logs: - // New log arrived, parse the event and forward to the user - event := new(TestStateSenderStateSynced) - if err := _TestStateSender.contract.UnpackLog(event, "StateSynced", log); err != nil { - return err - } - event.Raw = log - - select { - case sink <- event: - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - case err := <-sub.Err(): - return err - case <-quit: - return nil - } - } - }), nil -} - -// ParseStateSynced is a log parse operation binding the contract event 0x103fed9db65eac19c4d870f49ab7520fe03b99f1838e5996caf47e9e43308392. -// -// Solidity: event StateSynced(uint256 indexed id, address indexed contractAddress, bytes data) -func (_TestStateSender *TestStateSenderFilterer) ParseStateSynced(log types.Log) (*TestStateSenderStateSynced, error) { - event := new(TestStateSenderStateSynced) - if err := _TestStateSender.contract.UnpackLog(event, "StateSynced", log); err != nil { - return nil, err - } - event.Raw = log - return event, nil -} diff --git a/cmd/devnet/contracts/lib/exitpayloadreader.sol b/cmd/devnet/contracts/lib/exitpayloadreader.sol deleted file mode 100644 index 3a59a3429d1..00000000000 --- a/cmd/devnet/contracts/lib/exitpayloadreader.sol +++ /dev/null @@ -1,159 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import {RLPReader} from "./rlpreader.sol"; - -library ExitPayloadReader { - using RLPReader for bytes; - using RLPReader for RLPReader.RLPItem; - - uint8 constant WORD_SIZE = 32; - - struct ExitPayload { - RLPReader.RLPItem[] data; - } - - struct Receipt { - RLPReader.RLPItem[] data; - bytes raw; - uint256 logIndex; - } - - struct Log { - RLPReader.RLPItem data; - RLPReader.RLPItem[] list; - } - - struct LogTopics { - RLPReader.RLPItem[] data; - } - - // copy paste of private copy() from RLPReader to avoid changing of existing contracts - function copy(uint256 src, uint256 dest, uint256 len) private pure { - if (len == 0) return; - - // copy as many word sizes as possible - for (; len >= WORD_SIZE; len -= WORD_SIZE) { - assembly { - mstore(dest, mload(src)) - } - - src += WORD_SIZE; - dest += WORD_SIZE; - } - - if (len == 0) return; - - // left over bytes. Mask is used to remove unwanted bytes from the word - uint256 mask = 256 ** (WORD_SIZE - len) - 1; - assembly { - let srcpart := and(mload(src), not(mask)) // zero out src - let destpart := and(mload(dest), mask) // retrieve the bytes - mstore(dest, or(destpart, srcpart)) - } - } - - function toExitPayload(bytes memory data) internal pure returns (ExitPayload memory) { - RLPReader.RLPItem[] memory payloadData = data.toRlpItem().toList(); - - return ExitPayload(payloadData); - } - - function getHeaderNumber(ExitPayload memory payload) internal pure returns (uint256) { - return payload.data[0].toUint(); - } - - function getBlockProof(ExitPayload memory payload) internal pure returns (bytes memory) { - return payload.data[1].toBytes(); - } - - function getBlockNumber(ExitPayload memory payload) internal pure returns (uint256) { - return payload.data[2].toUint(); - } - - function getBlockTime(ExitPayload memory payload) internal pure returns (uint256) { - return payload.data[3].toUint(); - } - - function getTxRoot(ExitPayload memory payload) internal pure returns (bytes32) { - return bytes32(payload.data[4].toUint()); - } - - function getReceiptRoot(ExitPayload memory payload) internal pure returns (bytes32) { - return bytes32(payload.data[5].toUint()); - } - - function getReceipt(ExitPayload memory payload) internal pure returns (Receipt memory receipt) { - receipt.raw = payload.data[6].toBytes(); - RLPReader.RLPItem memory receiptItem = receipt.raw.toRlpItem(); - - if (receiptItem.isList()) { - // legacy tx - receipt.data = receiptItem.toList(); - } else { - // pop first byte before parsing receipt - bytes memory typedBytes = receipt.raw; - bytes memory result = new bytes(typedBytes.length - 1); - uint256 srcPtr; - uint256 destPtr; - assembly { - srcPtr := add(33, typedBytes) - destPtr := add(0x20, result) - } - - copy(srcPtr, destPtr, result.length); - receipt.data = result.toRlpItem().toList(); - } - - receipt.logIndex = getReceiptLogIndex(payload); - return receipt; - } - - function getReceiptProof(ExitPayload memory payload) internal pure returns (bytes memory) { - return payload.data[7].toBytes(); - } - - function getBranchMaskAsBytes(ExitPayload memory payload) internal pure returns (bytes memory) { - return payload.data[8].toBytes(); - } - - function getBranchMaskAsUint(ExitPayload memory payload) internal pure returns (uint256) { - return payload.data[8].toUint(); - } - - function getReceiptLogIndex(ExitPayload memory payload) internal pure returns (uint256) { - return payload.data[9].toUint(); - } - - // Receipt methods - function toBytes(Receipt memory receipt) internal pure returns (bytes memory) { - return receipt.raw; - } - - function getLog(Receipt memory receipt) internal pure returns (Log memory) { - RLPReader.RLPItem memory logData = receipt.data[3].toList()[receipt.logIndex]; - return Log(logData, logData.toList()); - } - - // Log methods - function getEmitter(Log memory log) internal pure returns (address) { - return RLPReader.toAddress(log.list[0]); - } - - function getTopics(Log memory log) internal pure returns (LogTopics memory) { - return LogTopics(log.list[1].toList()); - } - - function getData(Log memory log) internal pure returns (bytes memory) { - return log.list[2].toBytes(); - } - - function toRlpBytes(Log memory log) internal pure returns (bytes memory) { - return log.data.toRlpBytes(); - } - - // LogTopics methods - function getField(LogTopics memory topics, uint256 index) internal pure returns (RLPReader.RLPItem memory) { - return topics.data[index]; - } -} \ No newline at end of file diff --git a/cmd/devnet/contracts/lib/merkle.sol b/cmd/devnet/contracts/lib/merkle.sol deleted file mode 100644 index 876988ce2d7..00000000000 --- a/cmd/devnet/contracts/lib/merkle.sol +++ /dev/null @@ -1,34 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -library Merkle { - function checkMembership( - bytes32 leaf, - uint256 index, - bytes32 rootHash, - bytes memory proof - ) internal pure returns (bool) { - require(proof.length % 32 == 0, "Invalid proof length"); - uint256 proofHeight = proof.length / 32; - // Proof of size n means, height of the tree is n+1. - // In a tree of height n+1, max #leafs possible is 2 ^ n - require(index < 2 ** proofHeight, "Leaf index is too big"); - - bytes32 proofElement; - bytes32 computedHash = leaf; - for (uint256 i = 32; i <= proof.length; i += 32) { - assembly { - proofElement := mload(add(proof, i)) - } - - if (index % 2 == 0) { - computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); - } else { - computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); - } - - index = index / 2; - } - return computedHash == rootHash; - } -} \ No newline at end of file diff --git a/cmd/devnet/contracts/lib/merklepatriciaproof.sol b/cmd/devnet/contracts/lib/merklepatriciaproof.sol deleted file mode 100644 index 41dbc50cce7..00000000000 --- a/cmd/devnet/contracts/lib/merklepatriciaproof.sol +++ /dev/null @@ -1,137 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import {RLPReader} from "./RLPReader.sol"; - -library MerklePatriciaProof { - /* - * @dev Verifies a merkle patricia proof. - * @param value The terminating value in the trie. - * @param encodedPath The path in the trie leading to value. - * @param rlpParentNodes The rlp encoded stack of nodes. - * @param root The root hash of the trie. - * @return The boolean validity of the proof. - */ - function verify( - bytes memory value, - bytes memory encodedPath, - bytes memory rlpParentNodes, - bytes32 root - ) internal pure returns (bool verified) { - RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes); - RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item); - - bytes memory currentNode; - RLPReader.RLPItem[] memory currentNodeList; - - bytes32 nodeKey = root; - uint256 pathPtr = 0; - - bytes memory path = _getNibbleArray(encodedPath); - if (path.length == 0) { - return false; - } - - for (uint256 i = 0; i < parentNodes.length; i++) { - if (pathPtr > path.length) { - return false; - } - - currentNode = RLPReader.toRlpBytes(parentNodes[i]); - if (nodeKey != keccak256(currentNode)) { - return false; - } - currentNodeList = RLPReader.toList(parentNodes[i]); - - if (currentNodeList.length == 17) { - if (pathPtr == path.length) { - if (keccak256(RLPReader.toBytes(currentNodeList[16])) == keccak256(value)) { - return true; - } else { - return false; - } - } - - uint8 nextPathNibble = uint8(path[pathPtr]); - if (nextPathNibble > 16) { - return false; - } - nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[nextPathNibble])); - pathPtr += 1; - } else if (currentNodeList.length == 2) { - uint256 traversed = _nibblesToTraverse(RLPReader.toBytes(currentNodeList[0]), path, pathPtr); - if (pathPtr + traversed == path.length) { - //leaf node - if (keccak256(RLPReader.toBytes(currentNodeList[1])) == keccak256(value)) { - return true; - } else { - return false; - } - } - - //extension node - if (traversed == 0) { - return false; - } - - pathPtr += traversed; - nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1])); - } else { - return false; - } - } - } - - function _nibblesToTraverse( - bytes memory encodedPartialPath, - bytes memory path, - uint256 pathPtr - ) private pure returns (uint256) { - uint256 len = 0; - // encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath - // and slicedPath have elements that are each one hex character (1 nibble) - bytes memory partialPath = _getNibbleArray(encodedPartialPath); - bytes memory slicedPath = new bytes(partialPath.length); - - // pathPtr counts nibbles in path - // partialPath.length is a number of nibbles - for (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) { - bytes1 pathNibble = path[i]; - slicedPath[i - pathPtr] = pathNibble; - } - - if (keccak256(partialPath) == keccak256(slicedPath)) { - len = partialPath.length; - } else { - len = 0; - } - return len; - } - - // bytes b must be hp encoded - function _getNibbleArray(bytes memory b) internal pure returns (bytes memory) { - bytes memory nibbles = ""; - if (b.length > 0) { - uint8 offset; - uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b)); - if (hpNibble == 1 || hpNibble == 3) { - nibbles = new bytes(b.length * 2 - 1); - bytes1 oddNibble = _getNthNibbleOfBytes(1, b); - nibbles[0] = oddNibble; - offset = 1; - } else { - nibbles = new bytes(b.length * 2 - 2); - offset = 0; - } - - for (uint256 i = offset; i < nibbles.length; i++) { - nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b); - } - } - return nibbles; - } - - function _getNthNibbleOfBytes(uint256 n, bytes memory str) private pure returns (bytes1) { - return bytes1(n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10); - } -} \ No newline at end of file diff --git a/cmd/devnet/contracts/lib/rlpreader.sol b/cmd/devnet/contracts/lib/rlpreader.sol deleted file mode 100644 index 9dad9a6658e..00000000000 --- a/cmd/devnet/contracts/lib/rlpreader.sol +++ /dev/null @@ -1,339 +0,0 @@ -// SPDX-License-Identifier: Apache-2.0 - -/* - * @author Hamdi Allam hamdi.allam97@gmail.com - * Please reach out with any questions or concerns - */ - -pragma solidity ^0.8.0; - -library RLPReader { - uint8 constant STRING_SHORT_START = 0x80; - uint8 constant STRING_LONG_START = 0xb8; - uint8 constant LIST_SHORT_START = 0xc0; - uint8 constant LIST_LONG_START = 0xf8; - uint8 constant WORD_SIZE = 32; - - struct RLPItem { - uint256 len; - uint256 memPtr; - } - - struct Iterator { - RLPItem item; // Item that's being iterated over. - uint256 nextPtr; // Position of the next item in the list. - } - - /* - * @dev Returns the next element in the iteration. Reverts if it has not next element. - * @param self The iterator. - * @return The next element in the iteration. - */ - function next(Iterator memory self) internal pure returns (RLPItem memory) { - require(hasNext(self)); - - uint256 ptr = self.nextPtr; - uint256 itemLength = _itemLength(ptr); - self.nextPtr = ptr + itemLength; - - return RLPItem(itemLength, ptr); - } - - /* - * @dev Returns true if the iteration has more elements. - * @param self The iterator. - * @return true if the iteration has more elements. - */ - function hasNext(Iterator memory self) internal pure returns (bool) { - RLPItem memory item = self.item; - return self.nextPtr < item.memPtr + item.len; - } - - /* - * @param item RLP encoded bytes - */ - function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { - uint256 memPtr; - assembly { - memPtr := add(item, 0x20) - } - - return RLPItem(item.length, memPtr); - } - - /* - * @dev Create an iterator. Reverts if item is not a list. - * @param self The RLP item. - * @return An 'Iterator' over the item. - */ - function iterator(RLPItem memory self) internal pure returns (Iterator memory) { - require(isList(self)); - - uint256 ptr = self.memPtr + _payloadOffset(self.memPtr); - return Iterator(self, ptr); - } - - /* - * @param item RLP encoded bytes - */ - function rlpLen(RLPItem memory item) internal pure returns (uint256) { - return item.len; - } - - /* - * @param item RLP encoded bytes - */ - function payloadLen(RLPItem memory item) internal pure returns (uint256) { - return item.len - _payloadOffset(item.memPtr); - } - - /* - * @param item RLP encoded list in bytes - */ - function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { - require(isList(item)); - - uint256 items = numItems(item); - RLPItem[] memory result = new RLPItem[](items); - - uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); - uint256 dataLen; - for (uint256 i = 0; i < items; i++) { - dataLen = _itemLength(memPtr); - result[i] = RLPItem(dataLen, memPtr); - memPtr = memPtr + dataLen; - } - - return result; - } - - // @return indicator whether encoded payload is a list. negate this function call for isData. - function isList(RLPItem memory item) internal pure returns (bool) { - if (item.len == 0) return false; - - uint8 byte0; - uint256 memPtr = item.memPtr; - assembly { - byte0 := byte(0, mload(memPtr)) - } - - if (byte0 < LIST_SHORT_START) return false; - return true; - } - - /* - * @dev A cheaper version of keccak256(toRlpBytes(item)) that avoids copying memory. - * @return keccak256 hash of RLP encoded bytes. - */ - function rlpBytesKeccak256(RLPItem memory item) internal pure returns (bytes32) { - uint256 ptr = item.memPtr; - uint256 len = item.len; - bytes32 result; - assembly { - result := keccak256(ptr, len) - } - return result; - } - - function payloadLocation(RLPItem memory item) internal pure returns (uint256, uint256) { - uint256 offset = _payloadOffset(item.memPtr); - uint256 memPtr = item.memPtr + offset; - uint256 len = item.len - offset; // data length - return (memPtr, len); - } - - /* - * @dev A cheaper version of keccak256(toBytes(item)) that avoids copying memory. - * @return keccak256 hash of the item payload. - */ - function payloadKeccak256(RLPItem memory item) internal pure returns (bytes32) { - (uint256 memPtr, uint256 len) = payloadLocation(item); - bytes32 result; - assembly { - result := keccak256(memPtr, len) - } - return result; - } - - /** RLPItem conversions into data types **/ - - // @returns raw rlp encoding in bytes - function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { - bytes memory result = new bytes(item.len); - if (result.length == 0) return result; - - uint256 ptr; - assembly { - ptr := add(0x20, result) - } - - copy(item.memPtr, ptr, item.len); - return result; - } - - // any non-zero byte < 128 is considered true - function toBoolean(RLPItem memory item) internal pure returns (bool) { - require(item.len == 1); - uint256 result; - uint256 memPtr = item.memPtr; - assembly { - result := byte(0, mload(memPtr)) - } - - return result == 0 ? false : true; - } - - function toAddress(RLPItem memory item) internal pure returns (address) { - // 1 byte for the length prefix - require(item.len == 21); - - return address(uint160(toUint(item))); - } - - function toUint(RLPItem memory item) internal pure returns (uint256) { - require(item.len > 0 && item.len <= 33); - - uint256 offset = _payloadOffset(item.memPtr); - uint256 len = item.len - offset; - - uint256 result; - uint256 memPtr = item.memPtr + offset; - assembly { - result := mload(memPtr) - - // shift to the correct location if necessary - if lt(len, 32) { - result := div(result, exp(256, sub(32, len))) - } - } - - return result; - } - - // enforces 32 byte length - function toUintStrict(RLPItem memory item) internal pure returns (uint256) { - // one byte prefix - require(item.len == 33); - - uint256 result; - uint256 memPtr = item.memPtr + 1; - assembly { - result := mload(memPtr) - } - - return result; - } - - function toBytes(RLPItem memory item) internal pure returns (bytes memory) { - require(item.len > 0); - - uint256 offset = _payloadOffset(item.memPtr); - uint256 len = item.len - offset; // data length - bytes memory result = new bytes(len); - - uint256 destPtr; - assembly { - destPtr := add(0x20, result) - } - - copy(item.memPtr + offset, destPtr, len); - return result; - } - - /* - * Private Helpers - */ - - // @return number of payload items inside an encoded list. - function numItems(RLPItem memory item) private pure returns (uint256) { - if (item.len == 0) return 0; - - uint256 count = 0; - uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); - uint256 endPtr = item.memPtr + item.len; - while (currPtr < endPtr) { - currPtr = currPtr + _itemLength(currPtr); // skip over an item - count++; - } - - return count; - } - - // @return entire rlp item byte length - function _itemLength(uint256 memPtr) private pure returns (uint256) { - uint256 itemLen; - uint256 byte0; - assembly { - byte0 := byte(0, mload(memPtr)) - } - - if (byte0 < STRING_SHORT_START) itemLen = 1; - else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; - else if (byte0 < LIST_SHORT_START) { - assembly { - let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is - memPtr := add(memPtr, 1) // skip over the first byte - /* 32 byte word size */ - let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len - itemLen := add(dataLen, add(byteLen, 1)) - } - } else if (byte0 < LIST_LONG_START) { - itemLen = byte0 - LIST_SHORT_START + 1; - } else { - assembly { - let byteLen := sub(byte0, 0xf7) - memPtr := add(memPtr, 1) - - let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length - itemLen := add(dataLen, add(byteLen, 1)) - } - } - - return itemLen; - } - - // @return number of bytes until the data - function _payloadOffset(uint256 memPtr) private pure returns (uint256) { - uint256 byte0; - assembly { - byte0 := byte(0, mload(memPtr)) - } - - if (byte0 < STRING_SHORT_START) return 0; - else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; - else if (byte0 < LIST_SHORT_START) - // being explicit - return byte0 - (STRING_LONG_START - 1) + 1; - else return byte0 - (LIST_LONG_START - 1) + 1; - } - - /* - * @param src Pointer to source - * @param dest Pointer to destination - * @param len Amount of memory to copy from the source - */ - function copy(uint256 src, uint256 dest, uint256 len) private pure { - if (len == 0) return; - - // copy as many word sizes as possible - for (; len >= WORD_SIZE; len -= WORD_SIZE) { - assembly { - mstore(dest, mload(src)) - } - - src += WORD_SIZE; - dest += WORD_SIZE; - } - - if (len == 0) return; - - // left over bytes. Mask is used to remove unwanted bytes from the word - uint256 mask = 256 ** (WORD_SIZE - len) - 1; - - assembly { - let srcpart := and(mload(src), not(mask)) // zero out src - let destpart := and(mload(dest), mask) // retrieve the bytes - mstore(dest, or(destpart, srcpart)) - } - } -} \ No newline at end of file diff --git a/cmd/devnet/contracts/lib/safemath.sol b/cmd/devnet/contracts/lib/safemath.sol deleted file mode 100644 index 0a83a12b8ba..00000000000 --- a/cmd/devnet/contracts/lib/safemath.sol +++ /dev/null @@ -1,50 +0,0 @@ -// SPDX-License-Identifier: MIT -// https://github.com/ConsenSysMesh/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol -pragma solidity ^0.8.0; - - -/** - * @title SafeMath - * @dev Math operations with safety checks that throw on error - */ -library SafeMath { - - /** - * @dev Multiplies two numbers, throws on overflow. - */ - function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { - if (a == 0) { - return 0; - } - c = a * b; - assert(c / a == b); - return c; - } - - /** - * @dev Integer division of two numbers, truncating the quotient. - */ - function div(uint256 a, uint256 b) internal pure returns (uint256) { - // assert(b > 0); // Solidity automatically throws when dividing by 0 - // uint256 c = a / b; - // assert(a == b * c + a % b); // There is no case in which this doesn't hold - return a / b; - } - - /** - * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). - */ - function sub(uint256 a, uint256 b) internal pure returns (uint256) { - assert(b <= a); - return a - b; - } - - /** - * @dev Adds two numbers, throws on overflow. - */ - function add(uint256 a, uint256 b) internal pure returns (uint256 c) { - c = a + b; - assert(c >= a); - return c; - } -} diff --git a/cmd/devnet/contracts/rootreceiver.sol b/cmd/devnet/contracts/rootreceiver.sol deleted file mode 100644 index 855b042af1b..00000000000 --- a/cmd/devnet/contracts/rootreceiver.sol +++ /dev/null @@ -1,154 +0,0 @@ -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import {RLPReader} from "lib/rlpreader.sol"; -import {MerklePatriciaProof} from "lib/merklepatriciaproof.sol"; -import {Merkle} from "lib/Merkle.sol"; -import "lib/exitpayloadreader.sol"; - -contract ICheckpointManager { - struct HeaderBlock { - bytes32 root; - uint256 start; - uint256 end; - uint256 createdAt; - address proposer; - } - - /** - * @notice mapping of checkpoint header numbers to block details - * @dev These checkpoints are submited by plasma contracts - */ - mapping(uint256 => HeaderBlock) public headerBlocks; -} - -contract RootReceiver { - using RLPReader for RLPReader.RLPItem; - using Merkle for bytes32; - using ExitPayloadReader for bytes; - using ExitPayloadReader for ExitPayloadReader.ExitPayload; - using ExitPayloadReader for ExitPayloadReader.Log; - using ExitPayloadReader for ExitPayloadReader.LogTopics; - using ExitPayloadReader for ExitPayloadReader.Receipt; - - // keccak256(MessageSent(bytes)) - bytes32 public constant SEND_MESSAGE_EVENT_SIG = 0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036; - - // root chain manager - ICheckpointManager public checkpointManager; - - // storage to avoid duplicate exits - mapping(bytes32 => bool) public processedExits; - mapping(address => uint) public senders; - - event received(address _source, uint256 _amount); - - constructor(address _checkpointManager) { - checkpointManager = ICheckpointManager(_checkpointManager); - } - - function _validateAndExtractMessage(bytes memory inputData) internal returns (address, bytes memory) { - ExitPayloadReader.ExitPayload memory payload = inputData.toExitPayload(); - - bytes memory branchMaskBytes = payload.getBranchMaskAsBytes(); - uint256 blockNumber = payload.getBlockNumber(); - // checking if exit has already been processed - // unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex) - bytes32 exitHash = keccak256( - abi.encodePacked( - blockNumber, - // first 2 nibbles are dropped while generating nibble array - // this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only) - // so converting to nibble array and then hashing it - MerklePatriciaProof._getNibbleArray(branchMaskBytes), - payload.getReceiptLogIndex() - ) - ); - require(processedExits[exitHash] == false, "FxRootTunnel: EXIT_ALREADY_PROCESSED"); - processedExits[exitHash] = true; - - ExitPayloadReader.Receipt memory receipt = payload.getReceipt(); - ExitPayloadReader.Log memory log = receipt.getLog(); - - // check child tunnel - //require(fxChildTunnel == log.getEmitter(), "FxRootTunnel: INVALID_FX_CHILD_TUNNEL"); - - bytes32 receiptRoot = payload.getReceiptRoot(); - // verify receipt inclusion - require( - MerklePatriciaProof.verify(receipt.toBytes(), branchMaskBytes, payload.getReceiptProof(), receiptRoot), - "RootTunnel: INVALID_RECEIPT_PROOF" - ); - - // verify checkpoint inclusion - _checkBlockMembershipInCheckpoint( - blockNumber, - payload.getBlockTime(), - payload.getTxRoot(), - receiptRoot, - payload.getHeaderNumber(), - payload.getBlockProof() - ); - - ExitPayloadReader.LogTopics memory topics = log.getTopics(); - - require( - bytes32(topics.getField(0).toUint()) == SEND_MESSAGE_EVENT_SIG, // topic0 is event sig - "FxRootTunnel: INVALID_SIGNATURE" - ); - - // received message data - bytes memory message = abi.decode(log.getData(), (bytes)); // event decodes params again, so decoding bytes to get message - return (log.getEmitter(), message); - } - - function _checkBlockMembershipInCheckpoint( - uint256 blockNumber, - uint256 blockTime, - bytes32 txRoot, - bytes32 receiptRoot, - uint256 headerNumber, - bytes memory blockProof - ) private view { - (bytes32 headerRoot, uint256 startBlock, , , ) = checkpointManager.headerBlocks(headerNumber); - - require( - keccak256(abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot)).checkMembership( - blockNumber - startBlock, - headerRoot, - blockProof - ), - "FxRootTunnel: INVALID_HEADER" - ); - } - - /** - * @notice receive message from L2 to L1, validated by proof - * @dev This function verifies if the transaction actually happened on child chain - * - * @param inputData RLP encoded data of the reference tx containing following list of fields - * 0 - headerNumber - Checkpoint header block number containing the reference tx - * 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root - * 2 - blockNumber - Block number containing the reference tx on child chain - * 3 - blockTime - Reference tx block time - * 4 - txRoot - Transactions root of block - * 5 - receiptRoot - Receipts root of block - * 6 - receipt - Receipt of the reference transaction - * 7 - receiptProof - Merkle proof of the reference receipt - * 8 - branchMask - 32 bits denoting the path of receipt in merkle tree - * 9 - receiptLogIndex - Log Index to read from the receipt - */ - function receiveMessage(bytes memory inputData) public virtual { - (address sender, bytes memory message) = _validateAndExtractMessage(inputData); - _processMessageFromChild(sender, message); - } - - function _processMessageFromChild(address /*sender*/, bytes memory data) internal { - (address receiver, address from, uint amount) = abi.decode(data, (address, address, uint)); - require(receiver == address(this), "Invalid receiver"); - uint total = senders[from]; - senders[from] = total + amount; - - emit received(from, amount); - } -} \ No newline at end of file diff --git a/cmd/devnet/contracts/rootsender.sol b/cmd/devnet/contracts/rootsender.sol deleted file mode 100644 index afd15bd48f7..00000000000 --- a/cmd/devnet/contracts/rootsender.sol +++ /dev/null @@ -1,29 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0 - -pragma solidity ^0.8.6; - -import { TestStateSender } from "./teststatesender.sol"; - -contract RootSender { - TestStateSender stateSender; - address childStateReceiver; - mapping(address => uint) public sent; - - constructor( - address stateSender_, - address childStateReceiver_ - ) { - stateSender = TestStateSender(stateSender_); - childStateReceiver = childStateReceiver_; - } - - function sendToChild(uint amount) external { - uint total = sent[msg.sender]; - sent[msg.sender] = total + amount; - - stateSender.syncState( - childStateReceiver, - abi.encode(msg.sender, amount) - ); - } -} \ No newline at end of file diff --git a/cmd/devnet/contracts/steps/l1l2transfers.go b/cmd/devnet/contracts/steps/l1l2transfers.go deleted file mode 100644 index 7d56969cf28..00000000000 --- a/cmd/devnet/contracts/steps/l1l2transfers.go +++ /dev/null @@ -1,525 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package contracts_steps - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "math" - "math/big" - - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon/cmd/devnet/accounts" - "github.com/erigontech/erigon/cmd/devnet/blocks" - "github.com/erigontech/erigon/cmd/devnet/contracts" - "github.com/erigontech/erigon/cmd/devnet/devnet" - "github.com/erigontech/erigon/cmd/devnet/scenarios" - "github.com/erigontech/erigon/cmd/devnet/services" - "github.com/erigontech/erigon/execution/abi" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/execution/chain/networkname" - "github.com/erigontech/erigon/rpc" - "github.com/erigontech/erigon/rpc/ethapi" - "github.com/erigontech/erigon/rpc/requests" -) - -func init() { - scenarios.MustRegisterStepHandlers( - scenarios.StepHandler(DeployChildChainReceiver), - scenarios.StepHandler(DeployRootChainSender), - scenarios.StepHandler(GenerateSyncEvents), - scenarios.StepHandler(ProcessRootTransfers), - scenarios.StepHandler(BatchProcessRootTransfers), - ) -} - -func GenerateSyncEvents(ctx context.Context, senderName string, numberOfTransfers int, minTransfer int, maxTransfer int) error { - sender := accounts.GetAccount(senderName) - ctx = devnet.WithCurrentNetwork(ctx, networkname.Dev) - - auth, err := contracts.TransactOpts(ctx, sender.Address) - - if err != nil { - return err - } - - heimdall := services.Heimdall(ctx) - - stateSender := heimdall.StateSenderContract() - - receiver, _ := scenarios.Param[*contracts.ChildReceiver](ctx, "childReceiver") - receiverAddress, _ := scenarios.Param[common.Address](ctx, "childReceiverAddress") - - receivedChan := make(chan *contracts.ChildReceiverReceived) - receiverSubscription, err := receiver.WatchReceived(&bind.WatchOpts{}, receivedChan) - - if err != nil { - return fmt.Errorf("Receiver subscription failed: %w", err) - } - - defer receiverSubscription.Unsubscribe() - - Uint256, _ := abi.NewType("uint256", "", nil) - Address, _ := abi.NewType("address", "", nil) - - args := abi.Arguments{ - {Name: "from", Type: Address}, - {Name: "amount", Type: Uint256}, - } - - for i := 0; i < numberOfTransfers; i++ { - err := func() error { - sendData, err := args.Pack(sender.Address, big.NewInt(int64(minTransfer))) - - if err != nil { - return err - } - - waiter, cancel := blocks.BlockWaiter(ctx, contracts.DeploymentChecker) - defer cancel() - - transaction, err := stateSender.SyncState(auth, receiverAddress, sendData) - - if err != nil { - return err - } - - block, err := waiter.Await(transaction.Hash()) - - if err != nil { - return fmt.Errorf("Failed to wait for sync block: %w", err) - } - - blockNum := block.Number.Uint64() - - logs, err := stateSender.FilterStateSynced(&bind.FilterOpts{ - Start: blockNum, - End: &blockNum, - }, nil, nil) - - if err != nil { - return fmt.Errorf("Failed to get post sync logs: %w", err) - } - - sendConfirmed := false - - for logs.Next() { - if logs.Event.ContractAddress != receiverAddress { - return fmt.Errorf("Receiver address mismatched: expected: %s, got: %s", receiverAddress, logs.Event.ContractAddress) - } - - if !bytes.Equal(logs.Event.Data, sendData) { - return fmt.Errorf("Send data mismatched: expected: %s, got: %s", sendData, logs.Event.Data) - } - - sendConfirmed = true - } - - if !sendConfirmed { - return errors.New("No post sync log received") - } - - auth.Nonce = (&big.Int{}).Add(auth.Nonce, big.NewInt(1)) - - return nil - }() - - if err != nil { - return err - } - } - - receivedCount := 0 - - devnet.Logger(ctx).Info("Waiting for receive events") - - for received := range receivedChan { - if received.Source != sender.Address { - return fmt.Errorf("Source address mismatched: expected: %s, got: %s", sender.Address, received.Source) - } - - if received.Amount.Cmp(big.NewInt(int64(minTransfer))) != 0 { - return fmt.Errorf("Amount mismatched: expected: %s, got: %s", big.NewInt(int64(minTransfer)), received.Amount) - } - - receivedCount++ - if receivedCount == numberOfTransfers { - break - } - } - - return nil -} - -func DeployRootChainSender(ctx context.Context, deployerName string) (context.Context, error) { - deployer := accounts.GetAccount(deployerName) - ctx = devnet.WithCurrentNetwork(ctx, networkname.Dev) - - auth, backend, err := contracts.DeploymentTransactor(ctx, deployer.Address) - - if err != nil { - return nil, err - } - - receiverAddress, _ := scenarios.Param[common.Address](ctx, "childReceiverAddress") - - heimdall := services.Heimdall(ctx) - - waiter, cancel := blocks.BlockWaiter(ctx, contracts.DeploymentChecker) - defer cancel() - - address, transaction, contract, err := contracts.DeployRootSender(auth, backend, heimdall.StateSenderAddress(), receiverAddress) - - if err != nil { - return nil, err - } - - block, err := waiter.Await(transaction.Hash()) - - if err != nil { - return nil, err - } - - devnet.Logger(ctx).Info("RootSender deployed", "chain", networkname.Dev, "block", block.Number, "addr", address) - - return scenarios.WithParam(ctx, "rootSenderAddress", address). - WithParam("rootSender", contract), nil -} - -func DeployChildChainReceiver(ctx context.Context, deployerName string) (context.Context, error) { - deployer := accounts.GetAccount(deployerName) - ctx = devnet.WithCurrentNetwork(ctx, networkname.BorDevnet) - - waiter, cancel := blocks.BlockWaiter(ctx, contracts.DeploymentChecker) - defer cancel() - - address, transaction, contract, err := contracts.Deploy(ctx, deployer.Address, contracts.DeployChildReceiver) - - if err != nil { - return nil, err - } - - block, err := waiter.Await(transaction.Hash()) - - if err != nil { - return nil, err - } - - devnet.Logger(ctx).Info("ChildReceiver deployed", "chain", networkname.BorDevnet, "block", block.Number, "addr", address) - - return scenarios.WithParam(ctx, "childReceiverAddress", address). - WithParam("childReceiver", contract), nil -} - -func ProcessRootTransfers(ctx context.Context, sourceName string, numberOfTransfers int, minTransfer int, maxTransfer int) error { - source := accounts.GetAccount(sourceName) - ctx = devnet.WithCurrentNetwork(ctx, networkname.Dev) - - auth, err := contracts.TransactOpts(ctx, source.Address) - - if err != nil { - return err - } - - sender, _ := scenarios.Param[*contracts.RootSender](ctx, "rootSender") - stateSender := services.Heimdall(ctx).StateSenderContract() - - receiver, _ := scenarios.Param[*contracts.ChildReceiver](ctx, "childReceiver") - receiverAddress, _ := scenarios.Param[common.Address](ctx, "childReceiverAddress") - - receivedChan := make(chan *contracts.ChildReceiverReceived) - receiverSubscription, err := receiver.WatchReceived(&bind.WatchOpts{}, receivedChan) - - if err != nil { - return fmt.Errorf("Receiver subscription failed: %w", err) - } - - defer receiverSubscription.Unsubscribe() - - Uint256, _ := abi.NewType("uint256", "", nil) - Address, _ := abi.NewType("address", "", nil) - - args := abi.Arguments{ - {Name: "from", Type: Address}, - {Name: "amount", Type: Uint256}, - } - - for i := 0; i < numberOfTransfers; i++ { - amount := accounts.EtherAmount(float64(minTransfer)) - - err = func() error { - waiter, cancel := blocks.BlockWaiter(ctx, blocks.CompletionChecker) - defer cancel() - - transaction, err := sender.SendToChild(auth, amount) - - if err != nil { - return err - } - - block, terr := waiter.Await(transaction.Hash()) - - if terr != nil { - node := devnet.SelectBlockProducer(ctx) - - traceResults, err := node.TraceTransaction(transaction.Hash()) - - if err != nil { - return fmt.Errorf("Send transaction failure: transaction trace failed: %w", err) - } - - for _, traceResult := range traceResults { - callResults, err := node.TraceCall(rpc.AsBlockReference(block.Number), ethapi.CallArgs{ - From: &traceResult.Action.From, - To: &traceResult.Action.To, - Data: &traceResult.Action.Input, - }, requests.TraceOpts.StateDiff, requests.TraceOpts.Trace, requests.TraceOpts.VmTrace) - - if err != nil { - return fmt.Errorf("Send transaction failure: trace call failed: %w", err) - } - - results, _ := json.MarshalIndent(callResults, " ", " ") - fmt.Println(string(results)) - } - - return terr - } - - blockNum := block.Number.Uint64() - - logs, err := stateSender.FilterStateSynced(&bind.FilterOpts{ - Start: blockNum, - End: &blockNum, - }, nil, nil) - - if err != nil { - return fmt.Errorf("Failed to get post sync logs: %w", err) - } - - for logs.Next() { - if logs.Event.ContractAddress != receiverAddress { - return fmt.Errorf("Receiver address mismatched: expected: %s, got: %s", receiverAddress, logs.Event.ContractAddress) - } - - values, err := args.Unpack(logs.Event.Data) - - if err != nil { - return fmt.Errorf("Failed unpack log args: %w", err) - } - - sender, ok := values[0].(common.Address) - - if !ok { - return fmt.Errorf("Unexpected arg type: expected: %T, got %T", common.Address{}, values[0]) - } - - sentAmount, ok := values[1].(*big.Int) - - if !ok { - return fmt.Errorf("Unexpected arg type: expected: %T, got %T", &big.Int{}, values[1]) - } - - if sender != source.Address { - return fmt.Errorf("Unexpected sender: expected: %s, got %s", source.Address, sender) - } - - if amount.Cmp(sentAmount) != 0 { - return fmt.Errorf("Unexpected sent amount: expected: %s, got %s", amount, sentAmount) - } - } - - return nil - }() - - if err != nil { - return err - } - - auth.Nonce = (&big.Int{}).Add(auth.Nonce, big.NewInt(1)) - } - - receivedCount := 0 - - devnet.Logger(ctx).Info("Waiting for receive events") - - for received := range receivedChan { - if received.Source != source.Address { - return fmt.Errorf("Source address mismatched: expected: %s, got: %s", source.Address, received.Source) - } - - if received.Amount.Cmp(accounts.EtherAmount(float64(minTransfer))) != 0 { - return fmt.Errorf("Amount mismatched: expected: %s, got: %s", accounts.EtherAmount(float64(minTransfer)), received.Amount) - } - - receivedCount++ - if receivedCount == numberOfTransfers { - break - } - } - - return nil -} - -func BatchProcessRootTransfers(ctx context.Context, sourceName string, batches int, transfersPerBatch, minTransfer int, maxTransfer int) error { - source := accounts.GetAccount(sourceName) - ctx = devnet.WithCurrentNetwork(ctx, networkname.Dev) - - auth, err := contracts.TransactOpts(ctx, source.Address) - - if err != nil { - return err - } - - sender, _ := scenarios.Param[*contracts.RootSender](ctx, "rootSender") - stateSender := services.Heimdall(ctx).StateSenderContract() - - receiver, _ := scenarios.Param[*contracts.ChildReceiver](ctx, "childReceiver") - receiverAddress, _ := scenarios.Param[common.Address](ctx, "childReceiverAddress") - - receivedChan := make(chan *contracts.ChildReceiverReceived) - receiverSubscription, err := receiver.WatchReceived(&bind.WatchOpts{}, receivedChan) - - if err != nil { - return fmt.Errorf("Receiver subscription failed: %w", err) - } - - defer receiverSubscription.Unsubscribe() - - Uint256, _ := abi.NewType("uint256", "", nil) - Address, _ := abi.NewType("address", "", nil) - - args := abi.Arguments{ - {Name: "from", Type: Address}, - {Name: "amount", Type: Uint256}, - } - - for b := 0; b < batches; b++ { - - hashes := make([]common.Hash, transfersPerBatch) - - waiter, cancel := blocks.BlockWaiter(ctx, blocks.CompletionChecker) - defer cancel() - - amount := accounts.EtherAmount(float64(minTransfer)) - - for i := 0; i < transfersPerBatch; i++ { - - transaction, err := sender.SendToChild(auth, amount) - - if err != nil { - return err - } - - hashes[i] = transaction.Hash() - auth.Nonce = (&big.Int{}).Add(auth.Nonce, big.NewInt(1)) - } - - blocks, err := waiter.AwaitMany(hashes...) - - if err != nil { - return err - } - - startBlock := uint64(math.MaxUint64) - endBlock := uint64(0) - - for _, block := range blocks { - blockNum := block.Number.Uint64() - - if blockNum < startBlock { - startBlock = blockNum - } - if blockNum > endBlock { - endBlock = blockNum - } - } - - logs, err := stateSender.FilterStateSynced(&bind.FilterOpts{ - Start: startBlock, - End: &endBlock, - }, nil, nil) - - if err != nil { - return fmt.Errorf("Failed to get post sync logs: %w", err) - } - - receivedCount := 0 - - for logs.Next() { - if logs.Event.ContractAddress != receiverAddress { - return fmt.Errorf("Receiver address mismatched: expected: %s, got: %s", receiverAddress, logs.Event.ContractAddress) - } - - values, err := args.Unpack(logs.Event.Data) - - if err != nil { - return fmt.Errorf("Failed unpack log args: %w", err) - } - - sender, ok := values[0].(common.Address) - - if !ok { - return fmt.Errorf("Unexpected arg type: expected: %T, got %T", common.Address{}, values[0]) - } - - sentAmount, ok := values[1].(*big.Int) - - if !ok { - return fmt.Errorf("Unexpected arg type: expected: %T, got %T", &big.Int{}, values[1]) - } - - if sender != source.Address { - return fmt.Errorf("Unexpected sender: expected: %s, got %s", source.Address, sender) - } - - if amount.Cmp(sentAmount) != 0 { - return fmt.Errorf("Unexpected sent amount: expected: %s, got %s", amount, sentAmount) - } - - receivedCount++ - } - - if receivedCount != transfersPerBatch { - return fmt.Errorf("Expected %d, got: %d", transfersPerBatch, receivedCount) - } - } - - receivedCount := 0 - - devnet.Logger(ctx).Info("Waiting for receive events") - - for received := range receivedChan { - if received.Source != source.Address { - return fmt.Errorf("Source address mismatched: expected: %s, got: %s", source.Address, received.Source) - } - - if received.Amount.Cmp(accounts.EtherAmount(float64(minTransfer))) != 0 { - return fmt.Errorf("Amount mismatched: expected: %s, got: %s", accounts.EtherAmount(float64(minTransfer)), received.Amount) - } - - receivedCount++ - if receivedCount == batches*transfersPerBatch { - break - } - } - - return nil -} diff --git a/cmd/devnet/contracts/steps/l2l1transfers.go b/cmd/devnet/contracts/steps/l2l1transfers.go deleted file mode 100644 index a63cfae3ff9..00000000000 --- a/cmd/devnet/contracts/steps/l2l1transfers.go +++ /dev/null @@ -1,313 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package contracts_steps - -import ( - "context" - "encoding/json" - "fmt" - "math/big" - - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon/cmd/devnet/accounts" - "github.com/erigontech/erigon/cmd/devnet/blocks" - "github.com/erigontech/erigon/cmd/devnet/contracts" - "github.com/erigontech/erigon/cmd/devnet/devnet" - "github.com/erigontech/erigon/cmd/devnet/scenarios" - "github.com/erigontech/erigon/cmd/devnet/services" - "github.com/erigontech/erigon/execution/abi" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/execution/chain/networkname" - "github.com/erigontech/erigon/rpc" - "github.com/erigontech/erigon/rpc/ethapi" - "github.com/erigontech/erigon/rpc/requests" -) - -func init() { - scenarios.MustRegisterStepHandlers( - scenarios.StepHandler(DeployChildChainSender), - scenarios.StepHandler(DeployRootChainReceiver), - scenarios.StepHandler(ProcessChildTransfers), - ) -} - -func DeployChildChainSender(ctx context.Context, deployerName string) (context.Context, error) { - deployer := accounts.GetAccount(deployerName) - ctx = devnet.WithCurrentNetwork(ctx, networkname.BorDevnet) - - auth, backend, err := contracts.DeploymentTransactor(ctx, deployer.Address) - - if err != nil { - return nil, err - } - - receiverAddress, _ := scenarios.Param[common.Address](ctx, "rootReceiverAddress") - - waiter, cancel := blocks.BlockWaiter(ctx, contracts.DeploymentChecker) - defer cancel() - - address, transaction, contract, err := contracts.DeployChildSender(auth, backend, receiverAddress) - - if err != nil { - return nil, err - } - - block, err := waiter.Await(transaction.Hash()) - - if err != nil { - return nil, err - } - - devnet.Logger(ctx).Info("ChildSender deployed", "chain", networkname.BorDevnet, "block", block.Number, "addr", address) - - return scenarios.WithParam(ctx, "childSenderAddress", address). - WithParam("childSender", contract), nil -} - -func DeployRootChainReceiver(ctx context.Context, deployerName string) (context.Context, error) { - deployer := accounts.GetAccount(deployerName) - ctx = devnet.WithCurrentNetwork(ctx, networkname.Dev) - - auth, backend, err := contracts.DeploymentTransactor(ctx, deployer.Address) - - if err != nil { - return nil, err - } - - waiter, cancel := blocks.BlockWaiter(ctx, contracts.DeploymentChecker) - defer cancel() - - heimdall := services.Heimdall(ctx) - - address, transaction, contract, err := contracts.DeployChildSender(auth, backend, heimdall.RootChainAddress()) - - if err != nil { - return nil, err - } - - block, err := waiter.Await(transaction.Hash()) - - if err != nil { - return nil, err - } - - devnet.Logger(ctx).Info("RootReceiver deployed", "chain", networkname.BorDevnet, "block", block.Number, "addr", address) - - return scenarios.WithParam(ctx, "rootReceiverAddress", address). - WithParam("rootReceiver", contract), nil -} - -func ProcessChildTransfers(ctx context.Context, sourceName string, numberOfTransfers int, minTransfer int, maxTransfer int) error { - source := accounts.GetAccount(sourceName) - ctx = devnet.WithCurrentNetwork(ctx, networkname.Dev) - - auth, err := contracts.TransactOpts(ctx, source.Address) - - if err != nil { - return err - } - - sender, _ := scenarios.Param[*contracts.ChildSender](ctx, "childSender") - - receiver, _ := scenarios.Param[*contracts.RootReceiver](ctx, "rootReceiver") - receiverAddress, _ := scenarios.Param[common.Address](ctx, "rootReceiverAddress") - - receivedChan := make(chan *contracts.RootReceiverReceived) - receiverSubscription, err := receiver.WatchReceived(&bind.WatchOpts{}, receivedChan) - - if err != nil { - return fmt.Errorf("Receiver subscription failed: %w", err) - } - - defer receiverSubscription.Unsubscribe() - - Uint256, _ := abi.NewType("uint256", "", nil) - Address, _ := abi.NewType("address", "", nil) - - args := abi.Arguments{ - {Name: "from", Type: Address}, - {Name: "amount", Type: Uint256}, - } - - heimdall := services.Heimdall(ctx) - proofGenerator := services.ProofGenerator(ctx) - - var sendTxHashes []common.Hash - var lastTxBlockNum *big.Int - var receiptTopic common.Hash - - zeroHash := common.Hash{} - - for i := 0; i < numberOfTransfers; i++ { - amount := accounts.EtherAmount(float64(minTransfer)) - - err = func() error { - waiter, cancel := blocks.BlockWaiter(ctx, blocks.CompletionChecker) - defer cancel() - - transaction, err := sender.SendToRoot(auth, amount) - - if err != nil { - return err - } - - block, terr := waiter.Await(transaction.Hash()) - - if terr != nil { - node := devnet.SelectBlockProducer(ctx) - - traceResults, err := node.TraceTransaction(transaction.Hash()) - - if err != nil { - return fmt.Errorf("Send transaction failure: transaction trace failed: %w", err) - } - - for _, traceResult := range traceResults { - callResults, err := node.TraceCall(rpc.AsBlockReference(block.Number), ethapi.CallArgs{ - From: &traceResult.Action.From, - To: &traceResult.Action.To, - Data: &traceResult.Action.Input, - }, requests.TraceOpts.StateDiff, requests.TraceOpts.Trace, requests.TraceOpts.VmTrace) - - if err != nil { - return fmt.Errorf("Send transaction failure: trace call failed: %w", err) - } - - results, _ := json.MarshalIndent(callResults, " ", " ") - fmt.Println(string(results)) - } - - return terr - } - - sendTxHashes = append(sendTxHashes, transaction.Hash()) - lastTxBlockNum = block.Number - - blockNum := block.Number.Uint64() - - logs, err := sender.FilterMessageSent(&bind.FilterOpts{ - Start: blockNum, - End: &blockNum, - }) - - if err != nil { - return fmt.Errorf("Failed to get post sync logs: %w", err) - } - - for logs.Next() { - values, err := args.Unpack(logs.Event.Message) - - if err != nil { - return fmt.Errorf("Failed unpack log args: %w", err) - } - - recceiverAddressValue, ok := values[0].(common.Address) - - if !ok { - return fmt.Errorf("Unexpected arg type: expected: %T, got %T", common.Address{}, values[0]) - } - - sender, ok := values[1].(common.Address) - - if !ok { - return fmt.Errorf("Unexpected arg type: expected: %T, got %T", common.Address{}, values[0]) - } - - sentAmount, ok := values[1].(*big.Int) - - if !ok { - return fmt.Errorf("Unexpected arg type: expected: %T, got %T", &big.Int{}, values[1]) - } - - if recceiverAddressValue != receiverAddress { - return fmt.Errorf("Unexpected sender: expected: %s, got %s", receiverAddress, recceiverAddressValue) - } - - if sender != source.Address { - return fmt.Errorf("Unexpected sender: expected: %s, got %s", source.Address, sender) - } - - if amount.Cmp(sentAmount) != 0 { - return fmt.Errorf("Unexpected sent amount: expected: %s, got %s", amount, sentAmount) - } - - if receiptTopic == zeroHash { - receiptTopic = logs.Event.Raw.Topics[0] - } - } - - return nil - }() - - if err != nil { - return err - } - - auth.Nonce = (&big.Int{}).Add(auth.Nonce, big.NewInt(1)) - } - - devnet.Logger(ctx).Info("Waiting for checkpoint") - - err = heimdall.AwaitCheckpoint(ctx, lastTxBlockNum) - - if err != nil { - return err - } - - for _, hash := range sendTxHashes { - payload, err := proofGenerator.GenerateExitPayload(ctx, hash, receiptTopic, 0) - - waiter, cancel := blocks.BlockWaiter(ctx, blocks.CompletionChecker) - defer cancel() - - if err != nil { - return err - } - - transaction, err := receiver.ReceiveMessage(auth, payload) - - if err != nil { - return err - } - - if _, err := waiter.Await(transaction.Hash()); err != nil { - return err - } - - } - - receivedCount := 0 - - devnet.Logger(ctx).Info("Waiting for receive events") - - for received := range receivedChan { - if received.Source != source.Address { - return fmt.Errorf("Source address mismatched: expected: %s, got: %s", source.Address, received.Source) - } - - if received.Amount.Cmp(accounts.EtherAmount(float64(minTransfer))) != 0 { - return fmt.Errorf("Amount mismatched: expected: %s, got: %s", accounts.EtherAmount(float64(minTransfer)), received.Amount) - } - - receivedCount++ - if receivedCount == numberOfTransfers { - break - } - } - - return nil -} diff --git a/cmd/devnet/contracts/steps/subscriber.go b/cmd/devnet/contracts/steps/subscriber.go deleted file mode 100644 index 9e9c51f8fc6..00000000000 --- a/cmd/devnet/contracts/steps/subscriber.go +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package contracts_steps - -import ( - "context" - "fmt" - "math/big" - - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon-lib/common/hexutil" - "github.com/erigontech/erigon-lib/log/v3" - - ethereum "github.com/erigontech/erigon" - "github.com/erigontech/erigon/cmd/devnet/accounts" - "github.com/erigontech/erigon/cmd/devnet/contracts" - "github.com/erigontech/erigon/cmd/devnet/devnet" - "github.com/erigontech/erigon/cmd/devnet/devnetutils" - "github.com/erigontech/erigon/cmd/devnet/scenarios" - "github.com/erigontech/erigon/cmd/devnet/transactions" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/execution/types" - "github.com/erigontech/erigon/rpc" - "github.com/erigontech/erigon/rpc/requests" -) - -func init() { - scenarios.MustRegisterStepHandlers( - scenarios.StepHandler(DeployAndCallLogSubscriber), - ) -} - -func DeployAndCallLogSubscriber(ctx context.Context, deployer string) (*common.Hash, error) { - logger := devnet.Logger(ctx) - - node := devnet.SelectNode(ctx) - - deployerAddress := common.HexToAddress(deployer) - - // subscriptionContract is the handler to the contract for further operations - tx, address, subscriptionContract, transactOpts, err := DeploySubsriptionContract(node, deployerAddress) - - if err != nil { - logger.Error("failed to create transaction", "error", err) - return nil, err - } - - hash := tx.Hash() - - eventHash, err := EmitFallbackEvent(node, subscriptionContract, transactOpts, logger) - - if err != nil { - logger.Error("failed to emit events", "error", err) - return nil, err - } - - txToBlockMap, err := transactions.AwaitTransactions(ctx, hash, eventHash) - - if err != nil { - return nil, fmt.Errorf("failed to call contract tx: %v", err) - } - - blockNum := txToBlockMap[eventHash] - - block, err := node.GetBlockByNumber(ctx, rpc.AsBlockNumber(blockNum), true) - - if err != nil { - return nil, err - } - - logs, err := node.FilterLogs(ctx, ethereum.FilterQuery{ - FromBlock: big.NewInt(0), - ToBlock: new(big.Int).SetUint64(blockNum), - Addresses: []common.Address{address}}) - - if err != nil || len(logs) == 0 { - return nil, fmt.Errorf("failed to get logs: %v", err) - } - - // compare the log events - errs, ok := requests.Compare(requests.NewLog(eventHash, blockNum, address, - devnetutils.GenerateTopic("SubscriptionEvent()"), hexutil.Bytes{}, 1, - block.Hash, hexutil.Uint(0), false), logs[0]) - - if !ok { - logger.Error("Log result is incorrect", "errors", errs) - return nil, fmt.Errorf("incorrect logs: %v", errs) - } - - logger.Info("SUCCESS => Logs compared successfully, no discrepancies") - - return &hash, nil -} - -// DeploySubsriptionContract creates and signs a transaction using the developer address, returns the contract and the signed transaction -func DeploySubsriptionContract(node devnet.Node, deployer common.Address) (types.Transaction, common.Address, *contracts.Subscription, *bind.TransactOpts, error) { - // initialize transactOpts - transactOpts, err := initializeTransactOps(node, deployer) - - if err != nil { - return nil, common.Address{}, nil, nil, fmt.Errorf("failed to initialize transactOpts: %v", err) - } - - // deploy the contract and get the contract handler - address, tx, subscriptionContract, err := contracts.DeploySubscription(transactOpts, contracts.NewBackend(node)) - - if err != nil { - return nil, common.Address{}, nil, nil, fmt.Errorf("failed to deploy subscription: %v", err) - } - - return tx, address, subscriptionContract, transactOpts, nil -} - -// EmitFallbackEvent emits an event from the contract using the fallback method -func EmitFallbackEvent(node devnet.Node, subContract *contracts.Subscription, opts *bind.TransactOpts, logger log.Logger) (common.Hash, error) { - logger.Info("EMITTING EVENT FROM FALLBACK...") - - // adding one to the nonce before initiating another transaction - opts.Nonce.Add(opts.Nonce, big.NewInt(1)) - - tx, err := subContract.Fallback(opts, []byte{}) - if err != nil { - return common.Hash{}, fmt.Errorf("failed to emit event from fallback: %v", err) - } - - return tx.Hash(), nil -} - -// initializeTransactOps initializes the transactOpts object for a contract transaction -func initializeTransactOps(node devnet.Node, transactor common.Address) (*bind.TransactOpts, error) { - count, err := node.GetTransactionCount(transactor, rpc.LatestBlock) - - if err != nil { - return nil, fmt.Errorf("failed to get transaction count for address 0x%x: %v", transactor, err) - } - - transactOpts, err := bind.NewKeyedTransactorWithChainID(accounts.SigKey(transactor), node.ChainID()) - - if err != nil { - return nil, fmt.Errorf("cannot create transactor with chainID %d, error: %v", node.ChainID(), err) - } - - transactOpts.GasLimit = uint64(200_000) - transactOpts.GasPrice = big.NewInt(880_000_000) - transactOpts.Nonce = count - - return transactOpts, nil -} diff --git a/cmd/devnet/contracts/subscription.sol b/cmd/devnet/contracts/subscription.sol deleted file mode 100644 index 092d4470feb..00000000000 --- a/cmd/devnet/contracts/subscription.sol +++ /dev/null @@ -1,10 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0 - -pragma solidity ^0.8.0; - -contract Subscription { - event SubscriptionEvent(); - fallback() external { - emit SubscriptionEvent(); - } -} diff --git a/cmd/devnet/contracts/testrootchain.sol b/cmd/devnet/contracts/testrootchain.sol deleted file mode 100644 index 1e11bf8c233..00000000000 --- a/cmd/devnet/contracts/testrootchain.sol +++ /dev/null @@ -1,329 +0,0 @@ - -// SPDX-License-Identifier: MIT -pragma solidity ^0.8.0; - -import {RLPReader} from "lib/rlpreader.sol"; -import {SafeMath} from "lib/safemath.sol"; - -interface IRootChain { - function slash() external; - - function submitHeaderBlock(bytes calldata data, bytes calldata sigs) - external; - - function submitCheckpoint(bytes calldata data, uint[3][] calldata sigs) - external; - - function getLastChildBlock() external view returns (uint256); - - function currentHeaderBlock() external view returns (uint256); -} - -contract RootChainHeader { - event NewHeaderBlock( - address indexed proposer, - uint256 indexed headerBlockId, - uint256 indexed reward, - uint256 start, - uint256 end, - bytes32 root - ); - // housekeeping event - event ResetHeaderBlock(address indexed proposer, uint256 indexed headerBlockId); - struct HeaderBlock { - bytes32 root; - uint256 start; - uint256 end; - uint256 createdAt; - address proposer; - } -} - -contract ProxyStorage { - address internal proxyTo; -} - -contract ChainIdMixin { - bytes constant public networkId = hex"0539"; - uint256 constant public CHAINID = 1337; -} - -interface IGovernance { - function update(address target, bytes calldata data) external; -} - -contract Governable { - IGovernance public governance; - - constructor(address _governance) { - governance = IGovernance(_governance); - } - - modifier onlyGovernance() { - _assertGovernance(); - _; - } - - function _assertGovernance() private view { - require( - msg.sender == address(governance), - "Only governance contract is authorized" - ); - } -} - -contract Registry is Governable { - // @todo hardcode constants - bytes32 private constant WETH_TOKEN = keccak256("wethToken"); - bytes32 private constant DEPOSIT_MANAGER = keccak256("depositManager"); - bytes32 private constant STAKE_MANAGER = keccak256("stakeManager"); - bytes32 private constant VALIDATOR_SHARE = keccak256("validatorShare"); - bytes32 private constant WITHDRAW_MANAGER = keccak256("withdrawManager"); - bytes32 private constant CHILD_CHAIN = keccak256("childChain"); - bytes32 private constant STATE_SENDER = keccak256("stateSender"); - bytes32 private constant SLASHING_MANAGER = keccak256("slashingManager"); - - address public erc20Predicate; - address public erc721Predicate; - - mapping(bytes32 => address) public contractMap; - mapping(address => address) public rootToChildToken; - mapping(address => address) public childToRootToken; - mapping(address => bool) public proofValidatorContracts; - mapping(address => bool) public isERC721; - - enum Type {Invalid, ERC20, ERC721, Custom} - struct Predicate { - Type _type; - } - mapping(address => Predicate) public predicates; - - event TokenMapped(address indexed rootToken, address indexed childToken); - event ProofValidatorAdded(address indexed validator, address indexed from); - event ProofValidatorRemoved(address indexed validator, address indexed from); - event PredicateAdded(address indexed predicate, address indexed from); - event PredicateRemoved(address indexed predicate, address indexed from); - event ContractMapUpdated(bytes32 indexed key, address indexed previousContract, address indexed newContract); - - constructor(address _governance) Governable(_governance) {} - - function updateContractMap(bytes32 _key, address _address) external onlyGovernance { - emit ContractMapUpdated(_key, contractMap[_key], _address); - contractMap[_key] = _address; - } - - /** - * @dev Map root token to child token - * @param _rootToken Token address on the root chain - * @param _childToken Token address on the child chain - * @param _isERC721 Is the token being mapped ERC721 - */ - function mapToken( - address _rootToken, - address _childToken, - bool _isERC721 - ) external onlyGovernance { - require(_rootToken != address(0x0) && _childToken != address(0x0), "INVALID_TOKEN_ADDRESS"); - rootToChildToken[_rootToken] = _childToken; - childToRootToken[_childToken] = _rootToken; - isERC721[_rootToken] = _isERC721; - //IWithdrawManager(contractMap[WITHDRAW_MANAGER]).createExitQueue(_rootToken); - emit TokenMapped(_rootToken, _childToken); - } - - function addErc20Predicate(address predicate) public onlyGovernance { - require(predicate != address(0x0), "Can not add null address as predicate"); - erc20Predicate = predicate; - addPredicate(predicate, Type.ERC20); - } - - function addErc721Predicate(address predicate) public onlyGovernance { - erc721Predicate = predicate; - addPredicate(predicate, Type.ERC721); - } - - function addPredicate(address predicate, Type _type) public onlyGovernance { - require(predicates[predicate]._type == Type.Invalid, "Predicate already added"); - predicates[predicate]._type = _type; - emit PredicateAdded(predicate, msg.sender); - } - - function removePredicate(address predicate) public onlyGovernance { - require(predicates[predicate]._type != Type.Invalid, "Predicate does not exist"); - delete predicates[predicate]; - emit PredicateRemoved(predicate, msg.sender); - } - - function getValidatorShareAddress() public view returns (address) { - return contractMap[VALIDATOR_SHARE]; - } - - function getWethTokenAddress() public view returns (address) { - return contractMap[WETH_TOKEN]; - } - - function getDepositManagerAddress() public view returns (address) { - return contractMap[DEPOSIT_MANAGER]; - } - - function getStakeManagerAddress() public view returns (address) { - return contractMap[STAKE_MANAGER]; - } - - function getSlashingManagerAddress() public view returns (address) { - return contractMap[SLASHING_MANAGER]; - } - - function getWithdrawManagerAddress() public view returns (address) { - return contractMap[WITHDRAW_MANAGER]; - } - - function getChildChainAndStateSender() public view returns (address, address) { - return (contractMap[CHILD_CHAIN], contractMap[STATE_SENDER]); - } - - function isTokenMapped(address _token) public view returns (bool) { - return rootToChildToken[_token] != address(0x0); - } - - function isTokenMappedAndIsErc721(address _token) public view returns (bool) { - require(isTokenMapped(_token), "TOKEN_NOT_MAPPED"); - return isERC721[_token]; - } - - function isTokenMappedAndGetPredicate(address _token) public view returns (address) { - if (isTokenMappedAndIsErc721(_token)) { - return erc721Predicate; - } - return erc20Predicate; - } - - function isChildTokenErc721(address childToken) public view returns (bool) { - address rootToken = childToRootToken[childToken]; - require(rootToken != address(0x0), "Child token is not mapped"); - return isERC721[rootToken]; - } -} - -contract RootChainStorage is ProxyStorage, RootChainHeader, ChainIdMixin { - bytes32 public heimdallId; - uint8 public constant VOTE_TYPE = 2; - - uint16 internal constant MAX_DEPOSITS = 10000; - uint256 public _nextHeaderBlock = MAX_DEPOSITS; - uint256 internal _blockDepositId = 1; - mapping(uint256 => HeaderBlock) public headerBlocks; - Registry internal registry; -} - -contract TestRootChain is RootChainStorage, IRootChain { - using SafeMath for uint256; - using RLPReader for bytes; - using RLPReader for RLPReader.RLPItem; - - modifier onlyDepositManager() { - require(msg.sender == registry.getDepositManagerAddress(), "UNAUTHORIZED_DEPOSIT_MANAGER_ONLY"); - _; - } - - function submitHeaderBlock(bytes calldata /*data*/, bytes calldata /*sigs*/) external pure { - revert(); - } - - function submitCheckpoint(bytes calldata data, uint[3][] calldata /*sigs*/) external { - (address proposer, uint256 start, uint256 end, bytes32 rootHash, bytes32 accountHash, uint256 borChainID) = - abi.decode(data, (address, uint256, uint256, bytes32, bytes32, uint256)); - require(CHAINID == borChainID, "Invalid bor chain id"); - - require(_buildHeaderBlock(proposer, start, end, rootHash), "INCORRECT_HEADER_DATA"); - - // check if it is better to keep it in local storage instead - /*IStakeManager stakeManager = IStakeManager(registry.getStakeManagerAddress()); - uint256 _reward = stakeManager.checkSignatures( - end.sub(start).add(1), - *//** - prefix 01 to data - 01 represents positive vote on data and 00 is negative vote - malicious validator can try to send 2/3 on negative vote so 01 is appended - *//* - keccak256(abi.encodePacked(bytes(hex"01"), data)), - accountHash, - proposer, - sigs - );*/ - - //require(_reward != 0, "Invalid checkpoint"); - emit NewHeaderBlock(proposer, _nextHeaderBlock, 0 /*_reward*/, start, end, rootHash); - _nextHeaderBlock = _nextHeaderBlock.add(MAX_DEPOSITS); - _blockDepositId = 1; - } - - function updateDepositId(uint256 numDeposits) external onlyDepositManager returns (uint256 depositId) { - depositId = currentHeaderBlock().add(_blockDepositId); - // deposit ids will be (_blockDepositId, _blockDepositId + 1, .... _blockDepositId + numDeposits - 1) - _blockDepositId = _blockDepositId.add(numDeposits); - require( - // Since _blockDepositId is initialized to 1; only (MAX_DEPOSITS - 1) deposits per header block are allowed - _blockDepositId <= MAX_DEPOSITS, - "TOO_MANY_DEPOSITS" - ); - } - - function getLastChildBlock() external view returns (uint256) { - return headerBlocks[currentHeaderBlock()].end; - } - - function slash() external { - //TODO: future implementation - } - - function currentHeaderBlock() public view returns (uint256) { - return _nextHeaderBlock.sub(MAX_DEPOSITS); - } - - function _buildHeaderBlock( - address proposer, - uint256 start, - uint256 end, - bytes32 rootHash - ) private returns (bool) { - uint256 nextChildBlock; - /* - The ID of the 1st header block is MAX_DEPOSITS. - if _nextHeaderBlock == MAX_DEPOSITS, then the first header block is yet to be submitted, hence nextChildBlock = 0 - */ - if (_nextHeaderBlock > MAX_DEPOSITS) { - nextChildBlock = headerBlocks[currentHeaderBlock()].end + 1; - } - if (nextChildBlock != start) { - return false; - } - - HeaderBlock memory headerBlock = HeaderBlock({ - root: rootHash, - start: nextChildBlock, - end: end, - createdAt: block.timestamp, - proposer: proposer - }); - - headerBlocks[_nextHeaderBlock] = headerBlock; - return true; - } - - // Housekeeping function. @todo remove later - function setNextHeaderBlock(uint256 _value) public /*onlyOwner*/ { - require(_value % MAX_DEPOSITS == 0, "Invalid value"); - for (uint256 i = _value; i < _nextHeaderBlock; i += MAX_DEPOSITS) { - delete headerBlocks[i]; - } - _nextHeaderBlock = _value; - _blockDepositId = 1; - emit ResetHeaderBlock(msg.sender, _nextHeaderBlock); - } - - // Housekeeping function. @todo remove later - function setHeimdallId(string memory _heimdallId) public /*onlyOwner*/ { - heimdallId = keccak256(abi.encodePacked(_heimdallId)); - } -} diff --git a/cmd/devnet/contracts/teststatesender.sol b/cmd/devnet/contracts/teststatesender.sol deleted file mode 100644 index 7c8cb2bebb9..00000000000 --- a/cmd/devnet/contracts/teststatesender.sol +++ /dev/null @@ -1,48 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0 - -pragma solidity ^0.8.2; - -contract TestStateSender { - - uint256 public counter; - mapping(address => address) public registrations; - - event NewRegistration( - address indexed user, - address indexed sender, - address indexed receiver - ); - event RegistrationUpdated( - address indexed user, - address indexed sender, - address indexed receiver - ); - event StateSynced( - uint256 indexed id, - address indexed contractAddress, - bytes data - ); - - modifier onlyRegistered(address receiver) { - //require(registrations[receiver] == msg.sender, "Invalid sender"); - _; - } - - function syncState(address receiver, bytes calldata data) - external - onlyRegistered(receiver) - { - counter = counter = counter + 1; - emit StateSynced(counter, receiver, data); - } - - // register new contract for state sync - function register(address sender, address receiver) public { - registrations[receiver] = sender; - if (registrations[receiver] == address(0)) { - emit NewRegistration(msg.sender, sender, receiver); - } else { - emit RegistrationUpdated(msg.sender, sender, receiver); - } - } -} \ No newline at end of file diff --git a/cmd/devnet/contracts/util.go b/cmd/devnet/contracts/util.go deleted file mode 100644 index 33d2f0d65a2..00000000000 --- a/cmd/devnet/contracts/util.go +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package contracts - -import ( - "context" - - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon/cmd/devnet/accounts" - "github.com/erigontech/erigon/cmd/devnet/blocks" - "github.com/erigontech/erigon/cmd/devnet/devnet" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/execution/types" - "github.com/erigontech/erigon/rpc" - "github.com/erigontech/erigon/rpc/ethapi" - "github.com/erigontech/erigon/rpc/requests" -) - -func TransactOpts(ctx context.Context, sender common.Address) (*bind.TransactOpts, error) { - node := devnet.SelectNode(ctx) - - transactOpts, err := bind.NewKeyedTransactorWithChainID(accounts.SigKey(sender), node.ChainID()) - - if err != nil { - return nil, err - } - - count, err := node.GetTransactionCount(sender, rpc.PendingBlock) - - if err != nil { - return nil, err - } - - transactOpts.Nonce = count - - return transactOpts, nil -} - -func DeploymentTransactor(ctx context.Context, deployer common.Address) (*bind.TransactOpts, bind.ContractBackend, error) { - node := devnet.SelectNode(ctx) - - transactOpts, err := TransactOpts(ctx, deployer) - - if err != nil { - return nil, nil, err - } - - return transactOpts, NewBackend(node), nil -} - -func Deploy[C any](ctx context.Context, deployer common.Address, deploy func(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, types.Transaction, *C, error)) (common.Address, types.Transaction, *C, error) { - transactOpts, err := bind.NewKeyedTransactorWithChainID(accounts.SigKey(deployer), devnet.CurrentChainID(ctx)) - - if err != nil { - return common.Address{}, nil, nil, err - } - - return DeployWithOps[C](ctx, transactOpts, deploy) -} - -func DeployWithOps[C any](ctx context.Context, auth *bind.TransactOpts, deploy func(auth *bind.TransactOpts, backend bind.ContractBackend) (common.Address, types.Transaction, *C, error)) (common.Address, types.Transaction, *C, error) { - node := devnet.SelectNode(ctx) - - count, err := node.GetTransactionCount(auth.From, rpc.PendingBlock) - - if err != nil { - return common.Address{}, nil, nil, err - } - - auth.Nonce = count - - // deploy the contract and get the contract handler - address, tx, contract, err := deploy(auth, NewBackend(node)) - - return address, tx, contract, err -} - -var DeploymentChecker = blocks.BlockHandlerFunc( - func(ctx context.Context, node devnet.Node, block *requests.Block, transaction *ethapi.RPCTransaction) error { - if err := blocks.CompletionChecker(ctx, node, block, transaction); err != nil { - return nil - } - - return nil - }) diff --git a/cmd/devnet/devnet/context.go b/cmd/devnet/devnet/context.go deleted file mode 100644 index 46a308ceb0b..00000000000 --- a/cmd/devnet/devnet/context.go +++ /dev/null @@ -1,257 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package devnet - -import ( - "context" - "math/big" - - "github.com/erigontech/erigon-lib/log/v3" -) - -type ctxKey int - -const ( - ckLogger ctxKey = iota - ckNetwork - ckNode - ckDevnet -) - -type Context interface { - context.Context - WithValue(key, value interface{}) Context - WithCurrentNetwork(selector interface{}) Context - WithCurrentNode(selector interface{}) Context -} - -type devnetContext struct { - context.Context -} - -func (c devnetContext) WithValue(key, value interface{}) Context { - return devnetContext{context.WithValue(c, key, value)} -} - -func (c devnetContext) WithCurrentNetwork(selector interface{}) Context { - return WithCurrentNetwork(c, selector) -} - -func (c devnetContext) WithCurrentNode(selector interface{}) Context { - return WithCurrentNode(c, selector) -} - -func WithNetwork(ctx context.Context, nw *Network) Context { - return devnetContext{context.WithValue(context.WithValue(ctx, ckNetwork, nw), ckLogger, nw.Logger)} -} - -func AsContext(ctx context.Context) Context { - if ctx, ok := ctx.(Context); ok { - return ctx - } - - return devnetContext{ctx} -} - -func Logger(ctx context.Context) log.Logger { - if logger, ok := ctx.Value(ckLogger).(log.Logger); ok { - return logger - } - - return log.Root() -} - -type cnode struct { - selector interface{} - node Node -} - -type cnet struct { - selector interface{} - network *Network -} - -func WithDevnet(ctx context.Context, devnet Devnet, logger log.Logger) Context { - ctx = context.WithValue(ctx, ckDevnet, devnet) - ctx = context.WithValue(ctx, ckLogger, logger) - return devnetContext{ctx} -} - -func WithCurrentNetwork(ctx context.Context, selector interface{}) Context { - if current := CurrentNetwork(ctx); current != nil { - if devnet, ok := ctx.Value(ckDevnet).(Devnet); ok { - selected := devnet.SelectNetwork(ctx, selector) - - if selected == current { - if ctx, ok := ctx.(devnetContext); ok { - return ctx - } - return devnetContext{ctx} - } - } - } - - if current := CurrentNode(ctx); current != nil { - ctx = context.WithValue(ctx, ckNode, nil) - } - - return devnetContext{context.WithValue(ctx, ckNetwork, &cnet{selector: selector})} -} - -func WithCurrentNode(ctx context.Context, selector interface{}) Context { - if node, ok := selector.(Node); ok { - return devnetContext{context.WithValue(ctx, ckNode, &cnode{node: node})} - } - - return devnetContext{context.WithValue(ctx, ckNode, &cnode{selector: selector})} -} - -func CurrentChainID(ctx context.Context) *big.Int { - if network := CurrentNetwork(ctx); network != nil { - return network.ChainID() - } - - return &big.Int{} -} - -func CurrentChainName(ctx context.Context) string { - if network := CurrentNetwork(ctx); network != nil { - return network.Chain - } - - return "" -} - -func Networks(ctx context.Context) []*Network { - if devnet, ok := ctx.Value(ckDevnet).(Devnet); ok { - return devnet - } - - return nil -} - -func CurrentNetwork(ctx context.Context) *Network { - if cn, ok := ctx.Value(ckNetwork).(*cnet); ok { - if cn.network == nil { - if devnet, ok := ctx.Value(ckDevnet).(Devnet); ok { - cn.network = devnet.SelectNetwork(ctx, cn.selector) - } - } - - return cn.network - } - - if cn, ok := ctx.Value(ckNode).(*cnode); ok && cn.node != nil { - return cn.node.(*devnetNode).network - } - - if devnet, ok := ctx.Value(ckDevnet).(Devnet); ok { - return devnet.SelectNetwork(ctx, 0) - } - - return nil -} - -func CurrentNode(ctx context.Context) Node { - if cn, ok := ctx.Value(ckNode).(*cnode); ok { - if cn.node == nil { - if network := CurrentNetwork(ctx); network != nil { - cn.node = network.SelectNode(ctx, cn.selector) - } - } - - return cn.node - } - - return nil -} - -func SelectNode(ctx context.Context, selector ...interface{}) Node { - if network := CurrentNetwork(ctx); network != nil { - if len(selector) > 0 { - return network.SelectNode(ctx, selector[0]) - } - - if current := CurrentNode(ctx); current != nil { - return current - } - - return network.FirstNode() - } - - return nil -} - -func SelectBlockProducer(ctx context.Context, selector ...interface{}) Node { - if network := CurrentNetwork(ctx); network != nil { - if len(selector) > 0 { - blockProducers := network.BlockProducers() - switch selector := selector[0].(type) { - case int: - if selector < len(blockProducers) { - return blockProducers[selector] - } - case NodeSelector: - for _, node := range blockProducers { - if selector.Test(ctx, node) { - return node - } - } - } - } - - if current := CurrentNode(ctx); current != nil && current.IsBlockProducer() { - return current - } - - if blockProducers := network.BlockProducers(); len(blockProducers) > 0 { - return blockProducers[0] - } - } - - return nil -} - -func SelectNonBlockProducer(ctx context.Context, selector ...interface{}) Node { - if network := CurrentNetwork(ctx); network != nil { - if len(selector) > 0 { - nonBlockProducers := network.NonBlockProducers() - switch selector := selector[0].(type) { - case int: - if selector < len(nonBlockProducers) { - return nonBlockProducers[selector] - } - case NodeSelector: - for _, node := range nonBlockProducers { - if selector.Test(ctx, node) { - return node - } - } - } - } - - if current := CurrentNode(ctx); current != nil && !current.IsBlockProducer() { - return current - } - - if nonBlockProducers := network.NonBlockProducers(); len(nonBlockProducers) > 0 { - return nonBlockProducers[0] - } - } - - return nil -} diff --git a/cmd/devnet/devnet/devnet.go b/cmd/devnet/devnet/devnet.go deleted file mode 100644 index 9f381f4cf8b..00000000000 --- a/cmd/devnet/devnet/devnet.go +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package devnet - -import ( - "context" - "math/big" - "regexp" - "sync" - - "github.com/erigontech/erigon-lib/log/v3" -) - -type Devnet []*Network - -type NetworkSelector interface { - Test(ctx context.Context, network *Network) bool -} - -type NetworkSelectorFunc func(ctx context.Context, network *Network) bool - -func (f NetworkSelectorFunc) Test(ctx context.Context, network *Network) bool { - return f(ctx, network) -} - -func (d Devnet) Start(logger log.Logger) (Context, error) { - var wg sync.WaitGroup - - errors := make(chan error, len(d)) - - runCtx := WithDevnet(context.Background(), d, logger) - - for _, network := range d { - wg.Add(1) - - go func(nw *Network) { - defer wg.Done() - errors <- nw.Start(runCtx) - }(network) - } - - wg.Wait() - - close(errors) - - for err := range errors { - if err != nil { - d.Stop() - return devnetContext{context.Background()}, err - } - } - - return runCtx, nil -} - -func (d Devnet) Stop() { - var wg sync.WaitGroup - - for _, network := range d { - wg.Add(1) - - go func(nw *Network) { - defer wg.Done() - nw.Stop() - }(network) - } - - wg.Wait() -} - -func (d Devnet) Wait() { - var wg sync.WaitGroup - - for _, network := range d { - wg.Add(1) - - go func(nw *Network) { - defer wg.Done() - nw.Wait() - }(network) - } - - wg.Wait() -} - -func (d Devnet) SelectNetwork(ctx context.Context, selector interface{}) *Network { - switch selector := selector.(type) { - case int: - if selector < len(d) { - return d[selector] - } - case string: - if exp, err := regexp.Compile("^" + selector); err == nil { - for _, network := range d { - if exp.MatchString(network.Chain) { - return network - } - } - } - case *big.Int: - for _, network := range d { - if network.ChainID().Cmp(selector) == 0 { - return network - } - } - case NetworkSelector: - for _, network := range d { - if selector.Test(ctx, network) { - return network - } - } - } - - return nil -} diff --git a/cmd/devnet/devnet/network.go b/cmd/devnet/devnet/network.go deleted file mode 100644 index cbf631821b8..00000000000 --- a/cmd/devnet/devnet/network.go +++ /dev/null @@ -1,299 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package devnet - -import ( - "context" - "fmt" - "math/big" - "os" - "reflect" - "strings" - "sync" - "time" - - "github.com/urfave/cli/v2" - - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon-lib/common/dbg" - "github.com/erigontech/erigon-lib/log/v3" - devnet_args "github.com/erigontech/erigon/cmd/devnet/args" - "github.com/erigontech/erigon/execution/types" - "github.com/erigontech/erigon/rpc/requests" - erigonapp "github.com/erigontech/erigon/turbo/app" - erigoncli "github.com/erigontech/erigon/turbo/cli" -) - -type Network struct { - DataDir string - Chain string - Logger log.Logger - BasePort int - BasePrivateApiAddr string - BaseRPCHost string - BaseRPCPort int - Snapshots bool - Nodes []Node - Services []Service - Genesis *types.Genesis - BorStateSyncDelay time.Duration - BorPeriod time.Duration - BorMinBlockSize int - wg sync.WaitGroup - peers []string - namedNodes map[string]Node - - // max number of blocks to look for a transaction in - MaxNumberOfEmptyBlockChecks int -} - -func (nw *Network) ChainID() *big.Int { - if len(nw.Nodes) > 0 { - return nw.Nodes[0].ChainID() - } - - return &big.Int{} -} - -// Start starts the process for multiple erigon nodes running on the dev chain -func (nw *Network) Start(ctx context.Context) error { - for _, service := range nw.Services { - if err := service.Start(ctx); err != nil { - nw.Stop() - return err - } - } - - baseNode := devnet_args.NodeArgs{ - DataDir: nw.DataDir, - Chain: nw.Chain, - Port: nw.BasePort, - HttpPort: nw.BaseRPCPort, - PrivateApiAddr: nw.BasePrivateApiAddr, - Snapshots: nw.Snapshots, - } - - nw.namedNodes = map[string]Node{} - - for i, nodeArgs := range nw.Nodes { - { - baseNode.StaticPeers = strings.Join(nw.peers, ",") - - err := nodeArgs.Configure(baseNode, i) - if err != nil { - nw.Stop() - return err - } - - node, err := nw.createNode(nodeArgs) - if err != nil { - nw.Stop() - return err - } - - nw.Nodes[i] = node - nw.namedNodes[node.GetName()] = node - nw.peers = append(nw.peers, nodeArgs.GetEnodeURL()) - - for _, service := range nw.Services { - service.NodeCreated(ctx, node) - } - } - } - - for _, node := range nw.Nodes { - err := nw.startNode(node) - if err != nil { - nw.Stop() - return err - } - - for _, service := range nw.Services { - service.NodeStarted(ctx, node) - } - } - - return nil -} - -var blockProducerFunds = (&big.Int{}).Mul(big.NewInt(1000), big.NewInt(common.Ether)) - -func (nw *Network) createNode(nodeArgs Node) (Node, error) { - nodeAddr := fmt.Sprintf("%s:%d", nw.BaseRPCHost, nodeArgs.GetHttpPort()) - - n := &devnetNode{ - sync.Mutex{}, - requests.NewRequestGenerator(nodeAddr, nw.Logger), - nodeArgs, - &nw.wg, - nw, - make(chan error), - nil, - nil, - nil, - } - - if n.IsBlockProducer() { - if nw.Genesis == nil { - nw.Genesis = &types.Genesis{} - } - - if nw.Genesis.Alloc == nil { - nw.Genesis.Alloc = types.GenesisAlloc{ - n.Account().Address: types.GenesisAccount{Balance: blockProducerFunds}, - } - } else { - nw.Genesis.Alloc[n.Account().Address] = types.GenesisAccount{Balance: blockProducerFunds} - } - } - - return n, nil -} - -func copyFlags(flags []cli.Flag) []cli.Flag { - copies := make([]cli.Flag, len(flags)) - - for i, flag := range flags { - flagValue := reflect.ValueOf(flag).Elem() - copyValue := reflect.New(flagValue.Type()).Elem() - - for f := 0; f < flagValue.NumField(); f++ { - if flagValue.Type().Field(f).PkgPath == "" { - copyValue.Field(f).Set(flagValue.Field(f)) - } - } - - copies[i] = copyValue.Addr().Interface().(cli.Flag) - } - - return copies -} - -// startNode starts an erigon node on the dev chain -func (nw *Network) startNode(n Node) error { - nw.wg.Add(1) - - node := n.(*devnetNode) - - args, err := devnet_args.AsArgs(node.nodeArgs) - if err != nil { - return err - } - - go func() { - nw.Logger.Info("Running node", "name", node.GetName(), "args", args) - - // catch any errors and avoid panics if an error occurs - defer func() { - panicResult := recover() - if panicResult == nil { - return - } - - nw.Logger.Error("catch panic", "node", node.GetName(), "err", panicResult, "stack", dbg.Stack()) - nw.Stop() - os.Exit(1) - }() - - // cli flags are not thread safe and assume only one copy of a flag - // variable is needed per process - which does not work here - app := erigonapp.MakeApp(node.GetName(), node.run, copyFlags(erigoncli.DefaultFlags)) - - if err := app.Run(args); err != nil { - nw.Logger.Warn("App run returned error", "node", node.GetName(), "err", err) - } - }() - - if err = <-node.startErr; err != nil { - return err - } - - return nil -} - -func (nw *Network) Stop() { - type stoppable interface { - Stop() - running() bool - } - - for i, n := range nw.Nodes { - if stoppable, ok := n.(stoppable); ok && stoppable.running() { - nw.Logger.Info("Stopping", "node", i) - go stoppable.Stop() - } - } - - nw.Logger.Info("Waiting for nodes to stop") - nw.Wait() - - nw.Logger.Info("Stopping services") - for _, service := range nw.Services { - service.Stop() - } - - // TODO should we wait for services -} - -func (nw *Network) Wait() { - nw.wg.Wait() -} - -func (nw *Network) FirstNode() Node { - return nw.Nodes[0] -} - -func (nw *Network) SelectNode(ctx context.Context, selector interface{}) Node { - switch selector := selector.(type) { - case int: - if selector < len(nw.Nodes) { - return nw.Nodes[selector] - } - case NodeSelector: - for _, node := range nw.Nodes { - if selector.Test(ctx, node) { - return node - } - } - } - - return nil -} - -func (nw *Network) BlockProducers() []Node { - var blockProducers []Node - - for _, node := range nw.Nodes { - if node.IsBlockProducer() { - blockProducers = append(blockProducers, node) - } - } - - return blockProducers -} - -func (nw *Network) NonBlockProducers() []Node { - var nonBlockProducers []Node - - for _, node := range nw.Nodes { - if !node.IsBlockProducer() { - nonBlockProducers = append(nonBlockProducers, node) - } - } - - return nonBlockProducers -} diff --git a/cmd/devnet/devnet/node.go b/cmd/devnet/devnet/node.go deleted file mode 100644 index 00b2ea94319..00000000000 --- a/cmd/devnet/devnet/node.go +++ /dev/null @@ -1,235 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package devnet - -import ( - "cmp" - "context" - "fmt" - "math/big" - "net/http" - "sync" - - "github.com/c2h5oh/datasize" - "github.com/urfave/cli/v2" - - "github.com/erigontech/erigon-lib/log/v3" - "github.com/erigontech/erigon/cmd/devnet/accounts" - "github.com/erigontech/erigon/cmd/devnet/args" - "github.com/erigontech/erigon/db/version" - "github.com/erigontech/erigon/diagnostics" - "github.com/erigontech/erigon/eth/ethconfig" - "github.com/erigontech/erigon/eth/tracers" - "github.com/erigontech/erigon/node/nodecfg" - "github.com/erigontech/erigon/rpc/requests" - "github.com/erigontech/erigon/turbo/debug" - enode "github.com/erigontech/erigon/turbo/node" -) - -type Node interface { - requests.RequestGenerator - GetName() string - ChainID() *big.Int - GetHttpPort() int - GetEnodeURL() string - Account() *accounts.Account - IsBlockProducer() bool - Configure(baseNode args.NodeArgs, nodeNumber int) error - EnableMetrics(port int) -} - -type NodeSelector interface { - Test(ctx context.Context, node Node) bool -} - -type NodeSelectorFunc func(ctx context.Context, node Node) bool - -func (f NodeSelectorFunc) Test(ctx context.Context, node Node) bool { - return f(ctx, node) -} - -func HTTPHost(n Node) string { - if n, ok := n.(*devnetNode); ok { - host := n.nodeCfg.Http.HttpListenAddress - - if host == "" { - host = "localhost" - } - - return fmt.Sprintf("%s:%d", host, n.nodeCfg.Http.HttpPort) - } - - return "" -} - -type devnetNode struct { - sync.Mutex - requests.RequestGenerator - nodeArgs Node - wg *sync.WaitGroup - network *Network - startErr chan error - nodeCfg *nodecfg.Config - ethCfg *ethconfig.Config - ethNode *enode.ErigonNode -} - -func (n *devnetNode) Stop() { - var toClose *enode.ErigonNode - - n.Lock() - if n.ethNode != nil { - toClose = n.ethNode - n.ethNode = nil - } - n.Unlock() - - if toClose != nil { - toClose.Close() - } - - n.done() -} - -func (n *devnetNode) running() bool { - n.Lock() - defer n.Unlock() - return n.startErr == nil && n.ethNode != nil -} - -func (n *devnetNode) done() { - n.Lock() - defer n.Unlock() - if n.wg != nil { - wg := n.wg - n.wg = nil - wg.Done() - } -} - -func (n *devnetNode) Configure(args.NodeArgs, int) error { - return nil -} - -func (n *devnetNode) IsBlockProducer() bool { - return n.nodeArgs.IsBlockProducer() -} - -func (n *devnetNode) Account() *accounts.Account { - return n.nodeArgs.Account() -} - -func (n *devnetNode) GetName() string { - return n.nodeArgs.GetName() -} - -func (n *devnetNode) ChainID() *big.Int { - return n.nodeArgs.ChainID() -} - -func (n *devnetNode) GetHttpPort() int { - return n.nodeArgs.GetHttpPort() -} - -func (n *devnetNode) GetEnodeURL() string { - return n.nodeArgs.GetEnodeURL() -} - -func (n *devnetNode) EnableMetrics(int) { - panic("not implemented") -} - -// run configures, creates and serves an erigon node -func (n *devnetNode) run(ctx *cli.Context) error { - var logger log.Logger - var tracer *tracers.Tracer - var err error - var metricsMux *http.ServeMux - var pprofMux *http.ServeMux - - defer n.done() - defer func() { - n.Lock() - if n.startErr != nil { - close(n.startErr) - n.startErr = nil - } - n.ethNode = nil - n.Unlock() - }() - - if logger, tracer, metricsMux, pprofMux, err = debug.Setup(ctx, false /* rootLogger */); err != nil { - return err - } - - debugMux := cmp.Or(metricsMux, pprofMux) - - logger.Info("Build info", "git_branch", version.GitBranch, "git_tag", version.GitTag, "git_commit", version.GitCommit) - - nodeConf, err := enode.NewNodConfigUrfave(ctx, debugMux, logger) - if err != nil { - return err - } - n.nodeCfg = nodeConf - n.ethCfg = enode.NewEthConfigUrfave(ctx, n.nodeCfg, logger) - - // These are set to prevent disk and page size churn which can be excessive - // when running multiple nodes - // MdbxGrowthStep impacts disk usage, MdbxDBSizeLimit impacts page file usage - n.nodeCfg.MdbxGrowthStep = 32 * datasize.MB - n.nodeCfg.MdbxDBSizeLimit = 512 * datasize.MB - - if n.network.Genesis != nil { - for addr, account := range n.network.Genesis.Alloc { - n.ethCfg.Genesis.Alloc[addr] = account - } - - if n.network.Genesis.GasLimit != 0 { - n.ethCfg.Genesis.GasLimit = n.network.Genesis.GasLimit - } - } - - if n.network.BorStateSyncDelay > 0 { - stateSyncConfirmationDelay := map[string]uint64{"0": uint64(n.network.BorStateSyncDelay.Seconds())} - logger.Warn("TODO: custom BorStateSyncDelay is not applied to BorConfig.StateSyncConfirmationDelay", "delay", stateSyncConfirmationDelay) - } - - n.ethNode, err = enode.New(ctx.Context, n.nodeCfg, n.ethCfg, logger, tracer) - - diagnostics.Setup(ctx, n.ethNode, metricsMux, pprofMux) - - n.Lock() - if n.startErr != nil { - n.startErr <- err - close(n.startErr) - n.startErr = nil - } - n.Unlock() - - if err != nil { - logger.Error("Node startup", "err", err) - return err - } - - err = n.ethNode.Serve() - - if err != nil { - logger.Error("error while serving Devnet node", "err", err) - } - - return err -} diff --git a/cmd/devnet/devnet/service.go b/cmd/devnet/devnet/service.go deleted file mode 100644 index 4154087363f..00000000000 --- a/cmd/devnet/devnet/service.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package devnet - -import "context" - -type Service interface { - Start(context context.Context) error - Stop() - - NodeCreated(ctx context.Context, node Node) - NodeStarted(ctx context.Context, node Node) -} diff --git a/cmd/devnet/devnetutils/utils.go b/cmd/devnet/devnetutils/utils.go deleted file mode 100644 index 202ee07359b..00000000000 --- a/cmd/devnet/devnetutils/utils.go +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package devnetutils - -import ( - "crypto/rand" - "encoding/binary" - "errors" - "fmt" - "net" - "os" - "path/filepath" - "strconv" - "strings" - - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon-lib/common/dir" - "github.com/erigontech/erigon-lib/crypto" - "github.com/erigontech/erigon-lib/log/v3" -) - -var ErrInvalidEnodeString = errors.New("invalid enode string") - -// ClearDevDB cleans up the dev folder used for the operations -func ClearDevDB(dataDir string, logger log.Logger) error { - logger.Info("Deleting nodes' data folders") - - files, err := dir.ReadDir(dataDir) - - if err != nil { - return err - } - - for _, file := range files { - if !file.IsDir() || file.Name() == "logs" { - continue - } - - nodeDataDir := filepath.Join(dataDir, file.Name()) - - _, err := os.Stat(nodeDataDir) - - if err != nil { - if os.IsNotExist(err) { - continue - } - return err - } - - if err := dir.RemoveAll(nodeDataDir); err != nil { - return err - } - - logger.Info("SUCCESS => Deleted", "datadir", nodeDataDir) - } - - return nil -} - -// HexToInt converts a hexadecimal string to uint64 -func HexToInt(hexStr string) uint64 { - cleaned := strings.ReplaceAll(hexStr, "0x", "") // remove the 0x prefix - result, _ := strconv.ParseUint(cleaned, 16, 64) - return result -} - -// UniqueIDFromEnode returns the unique ID from a node's enode, removing the `?discport=0` part -func UniqueIDFromEnode(enode string) (string, error) { - if len(enode) == 0 { - return "", ErrInvalidEnodeString - } - - // iterate through characters in the string until we reach '?' - // using index iteration because enode characters have single codepoints - var i int - var ati int - - for i < len(enode) && enode[i] != byte('?') { - if enode[i] == byte('@') { - ati = i - } - - i++ - } - - if ati == 0 { - return "", ErrInvalidEnodeString - } - - if _, apiPort, err := net.SplitHostPort(enode[ati+1 : i]); err != nil { - return "", ErrInvalidEnodeString - } else { - if _, err := strconv.Atoi(apiPort); err != nil { - return "", ErrInvalidEnodeString - } - } - - // if '?' is not found in the enode, return the original enode if it has a valid address - if i == len(enode) { - return enode, nil - } - - return enode[:i], nil -} - -func RandomInt(_max int) int { - if _max == 0 { - return 0 - } - - var n uint16 - binary.Read(rand.Reader, binary.LittleEndian, &n) - return int(n) % (_max + 1) -} - -// NamespaceAndSubMethodFromMethod splits a parent method into namespace and the actual method -func NamespaceAndSubMethodFromMethod(method string) (string, string, error) { - parts := strings.SplitN(method, "_", 2) - if len(parts) != 2 { - return "", "", errors.New("invalid string to split") - } - return parts[0], parts[1], nil -} - -func GenerateTopic(signature string) []common.Hash { - hashed := crypto.Keccak256([]byte(signature)) - return []common.Hash{common.BytesToHash(hashed)} -} - -// RandomNumberInRange returns a random number between min and max NOT inclusive -func RandomNumberInRange(_min, _max uint64) (uint64, error) { - if _max <= _min { - return 0, fmt.Errorf("Invalid range: upper bound %d less or equal than lower bound %d", _max, _min) - } - - return uint64(RandomInt(int(_max-_min)) + int(_min)), nil -} diff --git a/cmd/devnet/devnetutils/utils_test.go b/cmd/devnet/devnetutils/utils_test.go deleted file mode 100644 index 83a4f8ce94d..00000000000 --- a/cmd/devnet/devnetutils/utils_test.go +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package devnetutils - -import ( - "fmt" - "testing" - - "github.com/stretchr/testify/require" -) - -func TestHexToInt(t *testing.T) { - testCases := []struct { - hexStr string - expected uint64 - }{ - {"0x0", 0}, - {"0x32424", 205860}, - {"0x200", 512}, - {"0x39", 57}, - } - - for _, testCase := range testCases { - got := HexToInt(testCase.hexStr) - require.Equal(t, testCase.expected, got) - } -} - -func TestUniqueIDFromEnode(t *testing.T) { - testCases := []struct { - input string - expectedRes string - shouldError bool - }{ - { - input: "", - expectedRes: "", - shouldError: true, - }, - { - input: "enode://11c368e7a2775951d66ff155a982844ccd5219d10b53e310001e1e40c6a4e76c2f6e42f39acc1e4015cd3b7428765125214d89b07ca5fa2c19ac94746fc360b0@127.0.0.1:63380?discport=0", - expectedRes: "enode://11c368e7a2775951d66ff155a982844ccd5219d10b53e310001e1e40c6a4e76c2f6e42f39acc1e4015cd3b7428765125214d89b07ca5fa2c19ac94746fc360b0@127.0.0.1:63380", - shouldError: false, - }, - { - input: "enode://11c368e7a2775951d66ff155a982844ccd5219d10b53e310001e1e40c6a4e76c2f6e42f39acc1e4015cd3b7428765125214d89b07ca5fa2c19ac94746fc360b0@127.0.0.1:63380", - expectedRes: "enode://11c368e7a2775951d66ff155a982844ccd5219d10b53e310001e1e40c6a4e76c2f6e42f39acc1e4015cd3b7428765125214d89b07ca5fa2c19ac94746fc360b0@127.0.0.1:63380", - shouldError: false, - }, - { - input: "enode://11c368e7a2775951d66ff155a982844ccd5219d10b53e310001e1e40c6a4e76c2f6e42f39acc1e4015cd3b7428765125214d89b07ca5fa2c19ac94746fc360b0@127.0.0.1:63380discport=0", - expectedRes: "", - shouldError: true, - }, - } - - for _, testCase := range testCases { - got, err := UniqueIDFromEnode(testCase.input) - if testCase.shouldError && err == nil { - t.Errorf("expected error to happen, got no error") - } - if !testCase.shouldError && err != nil { - t.Errorf("expected no error, got %s", err) - } - require.EqualValues(t, testCase.expectedRes, got) - } -} - -func TestNamespaceAndSubMethodFromMethod(t *testing.T) { - expectedError := fmt.Errorf("invalid string to split") - - testCases := []struct { - method string - expectedNamespace string - expectedSubMethod string - shouldError bool - expectedError error - }{ - { - "eth_logs", - "eth", - "logs", - false, - nil, - }, - { - "ethNewHeads", - "", - "", - true, - expectedError, - }, - { - "", - "", - "", - true, - expectedError, - }, - } - - for _, testCase := range testCases { - namespace, subMethod, err := NamespaceAndSubMethodFromMethod(testCase.method) - require.Equal(t, testCase.expectedNamespace, namespace) - require.Equal(t, testCase.expectedSubMethod, subMethod) - require.Equal(t, testCase.expectedError, err) - if testCase.shouldError { - require.Errorf(t, testCase.expectedError, expectedError.Error()) - } - } -} - -func TestGenerateTopic(t *testing.T) { - testCases := []struct { - signature string - expected string - }{ - {"random string", "0x0d9d89437ff2d48ce95779dc9457bc48287b75a573eddbf50954efac5a97c4b9"}, - {"SubscriptionEvent()", "0x67abc7edb0ab50964ef0e90541d39366b9c69f6f714520f2ff4570059ee8ad80"}, - {"", "0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"}, - } - - for _, testCase := range testCases { - got := GenerateTopic(testCase.signature) - require.Equal(t, testCase.expected, fmt.Sprintf("%s", got[0])) - } -} diff --git a/cmd/devnet/main.go b/cmd/devnet/main.go deleted file mode 100644 index e23324c848c..00000000000 --- a/cmd/devnet/main.go +++ /dev/null @@ -1,465 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package main - -import ( - "context" - "fmt" - "os" - "os/signal" - "path/filepath" - dbg "runtime/debug" - "strconv" - "strings" - "syscall" - "time" - - "github.com/urfave/cli/v2" - - "github.com/erigontech/erigon-lib/log/v3" - "github.com/erigontech/erigon/cmd/devnet/accounts" - _ "github.com/erigontech/erigon/cmd/devnet/accounts/steps" - _ "github.com/erigontech/erigon/cmd/devnet/admin" - _ "github.com/erigontech/erigon/cmd/devnet/contracts/steps" - "github.com/erigontech/erigon/cmd/devnet/devnet" - "github.com/erigontech/erigon/cmd/devnet/devnetutils" - "github.com/erigontech/erigon/cmd/devnet/networks" - "github.com/erigontech/erigon/cmd/devnet/scenarios" - "github.com/erigontech/erigon/cmd/devnet/services" - "github.com/erigontech/erigon/cmd/devnet/services/polygon" - "github.com/erigontech/erigon/cmd/utils/flags" - "github.com/erigontech/erigon/db/version" - "github.com/erigontech/erigon/execution/chain/networkname" - "github.com/erigontech/erigon/rpc/requests" - erigon_app "github.com/erigontech/erigon/turbo/app" - "github.com/erigontech/erigon/turbo/debug" - "github.com/erigontech/erigon/turbo/logging" -) - -var ( - DataDirFlag = flags.DirectoryFlag{ - Name: "datadir", - Usage: "Data directory for the devnet", - Value: flags.DirectoryString(""), - Required: true, - } - - ChainFlag = cli.StringFlag{ - Name: "chain", - Usage: "The devnet chain to run (dev,bor-devnet)", - Value: networkname.Dev, - } - - ScenariosFlag = cli.StringFlag{ - Name: "scenarios", - Usage: "Scenarios to be run on the devnet chain", - Value: "dynamic-tx-node-0", - } - - BaseRpcHostFlag = cli.StringFlag{ - Name: "rpc.host", - Usage: "The host of the base RPC service", - Value: "localhost", - } - - BaseRpcPortFlag = cli.IntFlag{ - Name: "rpc.port", - Usage: "The port of the base RPC service", - Value: 8545, - } - - WithoutHeimdallFlag = cli.BoolFlag{ - Name: "bor.withoutheimdall", - Usage: "Run without Heimdall service", - } - - LocalHeimdallFlag = cli.BoolFlag{ - Name: "bor.localheimdall", - Usage: "Run with a devnet local Heimdall service", - } - - HeimdallURLFlag = cli.StringFlag{ - Name: "bor.heimdall", - Usage: "URL of Heimdall service", - Value: polygon.HeimdallURLDefault, - } - - BorSprintSizeFlag = cli.IntFlag{ - Name: "bor.sprintsize", - Usage: "The bor sprint size to run", - } - - MetricsEnabledFlag = cli.BoolFlag{ - Name: "metrics", - Usage: "Enable metrics collection and reporting", - } - - MetricsNodeFlag = cli.IntFlag{ - Name: "metrics.node", - Usage: "Which node of the cluster to attach to", - Value: 0, - } - - MetricsPortFlag = cli.IntFlag{ - Name: "metrics.port", - Usage: "Metrics HTTP server listening port", - Value: 6061, - } - - DiagnosticsURLFlag = cli.StringFlag{ - Name: "diagnostics.addr", - Usage: "Address of the diagnostics system provided by the support team, include unique session PIN", - } - - insecureFlag = cli.BoolFlag{ - Name: "insecure", - Usage: "Allows communication with diagnostics system using self-signed TLS certificates", - } - - metricsURLsFlag = cli.StringSliceFlag{ - Name: "debug.urls", - Usage: "internal flag", - } - - txCountFlag = cli.IntFlag{ - Name: "txcount", - Usage: "Transaction count, (scenario dependent - may be total or reoccurring)", - Value: 100, - } - - BlockProducersFlag = cli.UintFlag{ - Name: "block-producers", - Usage: "The number of block producers to instantiate in the network", - Value: 1, - } - - GasLimitFlag = cli.Uint64Flag{ - Name: "gaslimit", - Usage: "Target gas limit for mined blocks", - Value: 0, - } - - WaitFlag = cli.BoolFlag{ - Name: "wait", - Usage: "Wait until interrupted after all scenarios have run", - } -) - -type PanicHandler struct { -} - -func (ph PanicHandler) Log(r *log.Record) error { - fmt.Printf("Msg: %s\nStack: %s\n", r.Msg, dbg.Stack()) - os.Exit(2) - return nil -} - -func (ph PanicHandler) Enabled(ctx context.Context, lvl log.Lvl) bool { - return true -} - -func main() { - app := cli.NewApp() - app.Version = version.VersionWithCommit(version.GitCommit) - app.Action = mainContext - - app.Flags = []cli.Flag{ - &DataDirFlag, - &ChainFlag, - &ScenariosFlag, - &BaseRpcHostFlag, - &BaseRpcPortFlag, - &WithoutHeimdallFlag, - &LocalHeimdallFlag, - &HeimdallURLFlag, - &BorSprintSizeFlag, - &MetricsEnabledFlag, - &MetricsNodeFlag, - &MetricsPortFlag, - &DiagnosticsURLFlag, - &insecureFlag, - &metricsURLsFlag, - &WaitFlag, - &txCountFlag, - &BlockProducersFlag, - &logging.LogVerbosityFlag, - &logging.LogConsoleVerbosityFlag, - &logging.LogDirVerbosityFlag, - &GasLimitFlag, - } - - if err := app.Run(os.Args); err != nil { - _, _ = fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} - -func setupLogger(ctx *cli.Context) (log.Logger, error) { - dataDir := ctx.String(DataDirFlag.Name) - logsDir := filepath.Join(dataDir, "logs") - - if err := os.MkdirAll(logsDir, 0755); err != nil { - return nil, err - } - - logger := logging.SetupLoggerCtx("devnet", ctx, log.LvlInfo, log.LvlInfo, false /* rootLogger */) - - // Make root logger fail - log.Root().SetHandler(PanicHandler{}) - - return logger, nil -} - -func handleTerminationSignals(stopFunc func(), logger log.Logger) { - signalCh := make(chan os.Signal, 1) - signal.Notify(signalCh, syscall.SIGTERM, syscall.SIGINT) - - switch s := <-signalCh; s { - case syscall.SIGTERM: - logger.Info("Stopping networks") - stopFunc() - case syscall.SIGINT: - logger.Info("Terminating network") - os.Exit(-int(syscall.SIGINT)) - } -} - -func connectDiagnosticsIfEnabled(ctx *cli.Context, logger log.Logger) { - metricsEnabled := ctx.Bool(MetricsEnabledFlag.Name) - diagnosticsUrl := ctx.String(DiagnosticsURLFlag.Name) - if metricsEnabled && len(diagnosticsUrl) > 0 { - err := erigon_app.ConnectDiagnostics(ctx, logger) - if err != nil { - logger.Error("app.ConnectDiagnostics failed", "err", err) - } - } -} - -func mainContext(ctx *cli.Context) error { - debug.RaiseFdLimit() - - logger, err := setupLogger(ctx) - if err != nil { - return err - } - - // clear all the dev files - dataDir := ctx.String(DataDirFlag.Name) - if err := devnetutils.ClearDevDB(dataDir, logger); err != nil { - return err - } - - network, err := initDevnet(ctx, logger) - if err != nil { - return err - } - - if err = initDevnetMetrics(ctx, network); err != nil { - return err - } - - logger.Info("Starting Devnet") - runCtx, err := network.Start(logger) - if err != nil { - return fmt.Errorf("devnet start failed: %w", err) - } - - go handleTerminationSignals(network.Stop, logger) - go connectDiagnosticsIfEnabled(ctx, logger) - - enabledScenarios := strings.Split(ctx.String(ScenariosFlag.Name), ",") - - if err = allScenarios(ctx, runCtx).Run(runCtx, enabledScenarios...); err != nil { - return err - } - - if ctx.Bool(WaitFlag.Name) { - logger.Info("Waiting") - network.Wait() - } else { - logger.Info("Stopping Networks") - network.Stop() - } - - return nil -} - -func allScenarios(cliCtx *cli.Context, runCtx devnet.Context) scenarios.Scenarios { - // unsubscribe from all the subscriptions made - defer services.UnsubscribeAll() - - const recipientAddress = "0x71562b71999873DB5b286dF957af199Ec94617F7" - const sendValue uint64 = 10000 - - return scenarios.Scenarios{ - "dynamic-tx-node-0": { - Context: runCtx.WithCurrentNetwork(0).WithCurrentNode(0), - Steps: []*scenarios.Step{ - {Text: "InitSubscriptions", Args: []any{[]requests.SubMethod{requests.Methods.ETHNewHeads}}}, - {Text: "PingErigonRpc"}, - {Text: "CheckTxPoolContent", Args: []any{0, 0, 0}}, - {Text: "SendTxWithDynamicFee", Args: []any{recipientAddress, accounts.DevAddress, sendValue}}, - {Text: "AwaitBlocks", Args: []any{2 * time.Second}}, - }, - }, - "dynamic-tx-any-node": { - Context: runCtx.WithCurrentNetwork(0), - Steps: []*scenarios.Step{ - {Text: "InitSubscriptions", Args: []any{[]requests.SubMethod{requests.Methods.ETHNewHeads}}}, - {Text: "PingErigonRpc"}, - {Text: "CheckTxPoolContent", Args: []any{0, 0, 0}}, - {Text: "SendTxWithDynamicFee", Args: []any{recipientAddress, accounts.DevAddress, sendValue}}, - {Text: "AwaitBlocks", Args: []any{2 * time.Second}}, - }, - }, - "call-contract": { - Context: runCtx.WithCurrentNetwork(0), - Steps: []*scenarios.Step{ - {Text: "InitSubscriptions", Args: []any{[]requests.SubMethod{requests.Methods.ETHNewHeads}}}, - {Text: "DeployAndCallLogSubscriber", Args: []any{accounts.DevAddress}}, - }, - }, - "state-sync": { - Steps: []*scenarios.Step{ - {Text: "InitSubscriptions", Args: []any{[]requests.SubMethod{requests.Methods.ETHNewHeads}}}, - {Text: "CreateAccountWithFunds", Args: []any{networkname.Dev, "root-funder", 200.0}}, - {Text: "CreateAccountWithFunds", Args: []any{networkname.BorDevnet, "child-funder", 200.0}}, - {Text: "DeployChildChainReceiver", Args: []any{"child-funder"}}, - {Text: "DeployRootChainSender", Args: []any{"root-funder"}}, - {Text: "GenerateSyncEvents", Args: []any{"root-funder", 10, 2, 2}}, - {Text: "ProcessRootTransfers", Args: []any{"root-funder", 10, 2, 2}}, - {Text: "BatchProcessRootTransfers", Args: []any{"root-funder", 1, 10, 2, 2}}, - }, - }, - "child-chain-exit": { - Steps: []*scenarios.Step{ - {Text: "CreateAccountWithFunds", Args: []any{networkname.Dev, "root-funder", 200.0}}, - {Text: "CreateAccountWithFunds", Args: []any{networkname.BorDevnet, "child-funder", 200.0}}, - {Text: "DeployRootChainReceiver", Args: []any{"root-funder"}}, - {Text: "DeployChildChainSender", Args: []any{"child-funder"}}, - {Text: "ProcessChildTransfers", Args: []any{"child-funder", 1, 2, 2}}, - //{Text: "BatchProcessTransfers", Args: []any{"child-funder", 1, 10, 2, 2}}, - }, - }, - "block-production": { - Steps: []*scenarios.Step{ - {Text: "SendTxLoad", Args: []any{recipientAddress, accounts.DevAddress, sendValue, cliCtx.Uint(txCountFlag.Name)}}, - }, - }, - } -} - -func initDevnet(ctx *cli.Context, logger log.Logger) (devnet.Devnet, error) { - dataDir := ctx.String(DataDirFlag.Name) - chainName := ctx.String(ChainFlag.Name) - baseRpcHost := ctx.String(BaseRpcHostFlag.Name) - baseRpcPort := ctx.Int(BaseRpcPortFlag.Name) - producerCount := int(ctx.Uint(BlockProducersFlag.Name)) - gasLimit := ctx.Uint64(GasLimitFlag.Name) - - var dirLogLevel log.Lvl = log.LvlTrace - var consoleLogLevel log.Lvl = log.LvlCrit - - if ctx.IsSet(logging.LogVerbosityFlag.Name) { - lvlVal := ctx.String(logging.LogVerbosityFlag.Name) - - i, err := strconv.Atoi(lvlVal) - - lvl := log.Lvl(i) - - if err != nil { - lvl, err = log.LvlFromString(lvlVal) - } - - if err == nil { - consoleLogLevel = lvl - dirLogLevel = lvl - } - } else { - if ctx.IsSet(logging.LogConsoleVerbosityFlag.Name) { - lvlVal := ctx.String(logging.LogConsoleVerbosityFlag.Name) - - i, err := strconv.Atoi(lvlVal) - - lvl := log.Lvl(i) - - if err != nil { - lvl, err = log.LvlFromString(lvlVal) - } - - if err == nil { - consoleLogLevel = lvl - } - } - - if ctx.IsSet(logging.LogDirVerbosityFlag.Name) { - lvlVal := ctx.String(logging.LogDirVerbosityFlag.Name) - - i, err := strconv.Atoi(lvlVal) - - lvl := log.Lvl(i) - - if err != nil { - lvl, err = log.LvlFromString(lvlVal) - } - - if err == nil { - dirLogLevel = lvl - } - } - } - - switch chainName { - case networkname.BorDevnet: - if ctx.Bool(WithoutHeimdallFlag.Name) { - return networks.NewBorDevnetWithoutHeimdall(dataDir, baseRpcHost, baseRpcPort, gasLimit, logger, consoleLogLevel, dirLogLevel), nil - } else if ctx.Bool(LocalHeimdallFlag.Name) { - heimdallURL := ctx.String(HeimdallURLFlag.Name) - sprintSize := uint64(ctx.Int(BorSprintSizeFlag.Name)) - return networks.NewBorDevnetWithLocalHeimdall(dataDir, baseRpcHost, baseRpcPort, heimdallURL, sprintSize, producerCount, gasLimit, logger, consoleLogLevel, dirLogLevel), nil - } else { - return networks.NewBorDevnetWithRemoteHeimdall(dataDir, baseRpcHost, baseRpcPort, producerCount, gasLimit, logger, consoleLogLevel, dirLogLevel), nil - } - - case networkname.Dev: - return networks.NewDevDevnet(dataDir, baseRpcHost, baseRpcPort, producerCount, gasLimit, logger, consoleLogLevel, dirLogLevel), nil - - default: - return nil, fmt.Errorf("unknown network: '%s'", chainName) - } -} - -func initDevnetMetrics(ctx *cli.Context, network devnet.Devnet) error { - metricsEnabled := ctx.Bool(MetricsEnabledFlag.Name) - metricsNode := ctx.Int(MetricsNodeFlag.Name) - metricsPort := ctx.Int(MetricsPortFlag.Name) - - if !metricsEnabled { - return nil - } - - for _, nw := range network { - for i, nodeArgs := range nw.Nodes { - if metricsEnabled && (metricsNode == i) { - nodeArgs.EnableMetrics(metricsPort) - return nil - } - } - } - - return fmt.Errorf("initDevnetMetrics: not found %s=%d", MetricsNodeFlag.Name, metricsNode) -} diff --git a/cmd/devnet/networks/devnet_bor.go b/cmd/devnet/networks/devnet_bor.go deleted file mode 100644 index 358d2a188a2..00000000000 --- a/cmd/devnet/networks/devnet_bor.go +++ /dev/null @@ -1,259 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package networks - -import ( - "strconv" - "time" - - "github.com/jinzhu/copier" - - "github.com/erigontech/erigon-lib/log/v3" - "github.com/erigontech/erigon/cmd/devnet/accounts" - "github.com/erigontech/erigon/cmd/devnet/args" - "github.com/erigontech/erigon/cmd/devnet/devnet" - account_services "github.com/erigontech/erigon/cmd/devnet/services/accounts" - "github.com/erigontech/erigon/cmd/devnet/services/polygon" - "github.com/erigontech/erigon/execution/chain" - "github.com/erigontech/erigon/execution/chain/networkname" - "github.com/erigontech/erigon/execution/types" - "github.com/erigontech/erigon/polygon/bor/borcfg" - polychain "github.com/erigontech/erigon/polygon/chain" -) - -func NewBorDevnetWithoutHeimdall( - dataDir string, - baseRpcHost string, - baseRpcPort int, - gasLimit uint64, - logger log.Logger, - consoleLogLevel log.Lvl, - dirLogLevel log.Lvl, -) devnet.Devnet { - faucetSource := accounts.NewAccount("faucet-source") - - network := devnet.Network{ - DataDir: dataDir, - Chain: networkname.BorDevnet, - Logger: logger, - BasePort: 40303, - BasePrivateApiAddr: "localhost:10090", - BaseRPCHost: baseRpcHost, - BaseRPCPort: baseRpcPort, - //Snapshots: true, - Genesis: &types.Genesis{ - Alloc: types.GenesisAlloc{ - faucetSource.Address: {Balance: accounts.EtherAmount(200_000)}, - }, - GasLimit: gasLimit, - }, - Services: []devnet.Service{ - account_services.NewFaucet(networkname.BorDevnet, faucetSource), - }, - Nodes: []devnet.Node{ - &args.BlockProducer{ - NodeArgs: args.NodeArgs{ - ConsoleVerbosity: strconv.Itoa(int(consoleLogLevel)), - DirVerbosity: strconv.Itoa(int(dirLogLevel)), - WithoutHeimdall: true, - }, - AccountSlots: 200, - }, - &args.BlockConsumer{ - NodeArgs: args.NodeArgs{ - ConsoleVerbosity: strconv.Itoa(int(consoleLogLevel)), - DirVerbosity: strconv.Itoa(int(dirLogLevel)), - WithoutHeimdall: true, - }, - }, - }, - } - - return devnet.Devnet{&network} -} - -func NewBorDevnetWithHeimdall( - dataDir string, - baseRpcHost string, - baseRpcPort int, - heimdall *polygon.Heimdall, - heimdallURL string, - checkpointOwner *accounts.Account, - producerCount int, - gasLimit uint64, - logger log.Logger, - consoleLogLevel log.Lvl, - dirLogLevel log.Lvl, -) devnet.Devnet { - faucetSource := accounts.NewAccount("faucet-source") - - var services []devnet.Service - if heimdall != nil { - services = append(services, heimdall) - } - - var nodes []devnet.Node - - if producerCount == 0 { - producerCount++ - } - - for i := 0; i < producerCount; i++ { - nodes = append(nodes, &args.BlockProducer{ - NodeArgs: args.NodeArgs{ - ConsoleVerbosity: strconv.Itoa(int(consoleLogLevel)), - DirVerbosity: strconv.Itoa(int(dirLogLevel)), - HeimdallURL: heimdallURL, - }, - AccountSlots: 20000, - }) - } - - borNetwork := devnet.Network{ - DataDir: dataDir, - Chain: networkname.BorDevnet, - Logger: logger, - BasePort: 40303, - BasePrivateApiAddr: "localhost:10090", - BaseRPCHost: baseRpcHost, - BaseRPCPort: baseRpcPort, - BorStateSyncDelay: 5 * time.Second, - Services: append(services, account_services.NewFaucet(networkname.BorDevnet, faucetSource)), - Genesis: &types.Genesis{ - Alloc: types.GenesisAlloc{ - faucetSource.Address: {Balance: accounts.EtherAmount(200_000)}, - }, - GasLimit: gasLimit, - }, - Nodes: append(nodes, - &args.BlockConsumer{ - NodeArgs: args.NodeArgs{ - ConsoleVerbosity: strconv.Itoa(int(consoleLogLevel)), - DirVerbosity: strconv.Itoa(int(dirLogLevel)), - HeimdallURL: heimdallURL, - }, - }), - } - - devNetwork := devnet.Network{ - DataDir: dataDir, - Chain: networkname.Dev, - Logger: logger, - BasePort: 30403, - BasePrivateApiAddr: "localhost:10190", - BaseRPCHost: baseRpcHost, - BaseRPCPort: baseRpcPort + 1000, - Services: append(services, account_services.NewFaucet(networkname.Dev, faucetSource)), - Genesis: &types.Genesis{ - Alloc: types.GenesisAlloc{ - faucetSource.Address: {Balance: accounts.EtherAmount(200_000)}, - checkpointOwner.Address: {Balance: accounts.EtherAmount(10_000)}, - }, - }, - Nodes: []devnet.Node{ - &args.BlockProducer{ - NodeArgs: args.NodeArgs{ - ConsoleVerbosity: strconv.Itoa(int(consoleLogLevel)), - DirVerbosity: strconv.Itoa(int(dirLogLevel)), - VMDebug: true, - HttpCorsDomain: "*", - }, - DevPeriod: 5, - AccountSlots: 200, - }, - &args.BlockConsumer{ - NodeArgs: args.NodeArgs{ - ConsoleVerbosity: strconv.Itoa(int(consoleLogLevel)), - DirVerbosity: strconv.Itoa(int(dirLogLevel)), - }, - }, - }, - } - - return devnet.Devnet{ - &borNetwork, - &devNetwork, - } -} - -func NewBorDevnetWithRemoteHeimdall( - dataDir string, - baseRpcHost string, - baseRpcPort int, - producerCount int, - gasLimit uint64, - logger log.Logger, - consoleLogLevel log.Lvl, - dirLogLevel log.Lvl, -) devnet.Devnet { - heimdallURL := "" - checkpointOwner := accounts.NewAccount("checkpoint-owner") - return NewBorDevnetWithHeimdall( - dataDir, - baseRpcHost, - baseRpcPort, - nil, - heimdallURL, - checkpointOwner, - producerCount, - gasLimit, - logger, - consoleLogLevel, - dirLogLevel) -} - -func NewBorDevnetWithLocalHeimdall( - dataDir string, - baseRpcHost string, - baseRpcPort int, - heimdallURL string, - sprintSize uint64, - producerCount int, - gasLimit uint64, - logger log.Logger, - consoleLogLevel log.Lvl, - dirLogLevel log.Lvl, -) devnet.Devnet { - var config chain.Config - copier.Copy(&config, polychain.BorDevnetChainConfig) - borConfig := config.Bor.(*borcfg.BorConfig) - if sprintSize > 0 { - borConfig.Sprint = map[string]uint64{"0": sprintSize} - } - - checkpointOwner := accounts.NewAccount("checkpoint-owner") - - heimdall := polygon.NewHeimdall( - &config, - heimdallURL, - &polygon.CheckpointConfig{ - CheckpointBufferTime: 60 * time.Second, - CheckpointAccount: checkpointOwner, - }, - logger) - - return NewBorDevnetWithHeimdall( - dataDir, - baseRpcHost, - baseRpcPort, - heimdall, - heimdallURL, - checkpointOwner, - producerCount, - gasLimit, - logger, consoleLogLevel, dirLogLevel) -} diff --git a/cmd/devnet/networks/devnet_dev.go b/cmd/devnet/networks/devnet_dev.go deleted file mode 100644 index a131b66aa4a..00000000000 --- a/cmd/devnet/networks/devnet_dev.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package networks - -import ( - "strconv" - - "github.com/erigontech/erigon-lib/log/v3" - "github.com/erigontech/erigon/cmd/devnet/accounts" - "github.com/erigontech/erigon/cmd/devnet/args" - "github.com/erigontech/erigon/cmd/devnet/devnet" - account_services "github.com/erigontech/erigon/cmd/devnet/services/accounts" - "github.com/erigontech/erigon/execution/chain/networkname" - "github.com/erigontech/erigon/execution/types" -) - -func NewDevDevnet( - dataDir string, - baseRpcHost string, - baseRpcPort int, - producerCount int, - gasLimit uint64, - logger log.Logger, - consoleLogLevel log.Lvl, - dirLogLevel log.Lvl, -) devnet.Devnet { - faucetSource := accounts.NewAccount("faucet-source") - - var nodes []devnet.Node - - if producerCount == 0 { - producerCount++ - } - - for i := 0; i < producerCount; i++ { - nodes = append(nodes, &args.BlockProducer{ - NodeArgs: args.NodeArgs{ - ConsoleVerbosity: strconv.Itoa(int(consoleLogLevel)), - DirVerbosity: strconv.Itoa(int(dirLogLevel)), - }, - AccountSlots: 200, - }) - } - - network := devnet.Network{ - DataDir: dataDir, - Chain: networkname.Dev, - Logger: logger, - BasePrivateApiAddr: "localhost:10090", - BaseRPCHost: baseRpcHost, - BaseRPCPort: baseRpcPort, - Genesis: &types.Genesis{ - Alloc: types.GenesisAlloc{ - faucetSource.Address: {Balance: accounts.EtherAmount(200_000)}, - }, - GasLimit: gasLimit, - }, - Services: []devnet.Service{ - account_services.NewFaucet(networkname.Dev, faucetSource), - }, - MaxNumberOfEmptyBlockChecks: 30, - Nodes: append(nodes, - &args.BlockConsumer{ - NodeArgs: args.NodeArgs{ - ConsoleVerbosity: "0", - DirVerbosity: "5", - }, - }), - } - - return devnet.Devnet{&network} -} diff --git a/cmd/devnet/scenarios/context.go b/cmd/devnet/scenarios/context.go deleted file mode 100644 index fa7bca3bb66..00000000000 --- a/cmd/devnet/scenarios/context.go +++ /dev/null @@ -1,169 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package scenarios - -import ( - "context" - "sync" - - "github.com/erigontech/erigon/cmd/devnet/devnet" -) - -type ctxKey int - -const ( - ckParams ctxKey = iota -) - -func stepRunners(ctx context.Context) []*stepRunner { - return nil -} - -func ContextValues(ctx context.Context) []context.Context { - if ctx == nil { - return nil - } - - if compound, ok := ctx.(*CompoundContext); ok { - var contexts []context.Context - - for context := range compound.contexts { - contexts = append(contexts, context) - } - - return contexts - } - - return []context.Context{ctx} -} - -var empty struct{} - -type CompoundContext struct { - context.Context - contexts map[context.Context]struct{} - mutex sync.RWMutex -} - -func (join *CompoundContext) Err() error { - if join.Context.Err() != nil { - return join.Context.Err() - } - - join.mutex.RLock() - defer join.mutex.RUnlock() - for context := range join.contexts { - if context.Err() != nil { - return context.Err() - } - } - - return nil -} - -func (join *CompoundContext) Value(key interface{}) interface{} { - join.mutex.RLock() - defer join.mutex.RUnlock() - for context := range join.contexts { - if value := context.Value(key); value != nil { - return value - } - } - - return join.Context.Value(key) -} - -var background = context.Background() - -func JoinContexts(ctx context.Context, others ...context.Context) context.Context { - var join *CompoundContext - - if ctx != nil { - if compound, ok := ctx.(*CompoundContext); ok { - join = &CompoundContext{compound.Context, map[context.Context]struct{}{}, sync.RWMutex{}} - compound.mutex.RLock() - for context := range compound.contexts { - join.contexts[context] = empty - } - compound.mutex.RUnlock() - } else { - join = &CompoundContext{background, map[context.Context]struct{}{ctx: empty}, sync.RWMutex{}} - } - } else { - join = &CompoundContext{background, map[context.Context]struct{}{}, sync.RWMutex{}} - } - - for _, context := range others { - if compound, ok := context.(*CompoundContext); ok { - if compound.Context != background { - join.contexts[compound.Context] = empty - } - - compound.mutex.RLock() - for context := range compound.contexts { - if context != background { - join.contexts[context] = empty - } - } - compound.mutex.RUnlock() - } else if context != nil && context != background { - join.contexts[context] = empty - } - } - - return join -} - -type Context interface { - devnet.Context - WithParam(name string, value interface{}) Context -} - -type scenarioContext struct { - devnet.Context -} - -func (c scenarioContext) WithParam(name string, value interface{}) Context { - return WithParam(c, name, value) -} - -type Params map[string]interface{} - -func WithParam(ctx context.Context, name string, value interface{}) Context { - if params, ok := ctx.Value(ckParams).(Params); ok { - params[name] = value - if ctx, ok := ctx.(scenarioContext); ok { - return ctx - } - - return scenarioContext{devnet.AsContext(ctx)} - } - - ctx = context.WithValue(ctx, ckParams, Params{name: value}) - return scenarioContext{devnet.AsContext(ctx)} -} - -func Param[P any](ctx context.Context, name string) (P, bool) { - if params, ok := ctx.Value(ckParams).(Params); ok { - if param, ok := params[name]; ok { - return param.(P), true - } - } - - var p P - return p, false -} diff --git a/cmd/devnet/scenarios/errors.go b/cmd/devnet/scenarios/errors.go deleted file mode 100644 index 2e7ce7ab0f1..00000000000 --- a/cmd/devnet/scenarios/errors.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package scenarios - -import ( - "errors" - "fmt" -) - -// ErrUndefined is returned in case if step definition was not found -var ErrUndefined = errors.New("step is undefined") - -type ScenarioError struct { - error - Result ScenarioResult - Cause error -} - -func (e *ScenarioError) Unwrap() error { - return e.error -} - -func NewScenarioError(err error, result ScenarioResult, cause error) *ScenarioError { - return &ScenarioError{err, result, cause} -} - -func (e *ScenarioError) Error() string { - return fmt.Sprintf("%s: Cause: %s", e.error, e.Cause) -} diff --git a/cmd/devnet/scenarios/results.go b/cmd/devnet/scenarios/results.go deleted file mode 100644 index 9e5a036664f..00000000000 --- a/cmd/devnet/scenarios/results.go +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package scenarios - -import ( - "time" -) - -type ScenarioResult struct { - ScenarioId string - StartedAt time.Time - - StepResults []StepResult -} - -type StepResult struct { - Status StepStatus - FinishedAt time.Time - Err error - Returns []interface{} - ScenarioId string - - Step *Step -} - -func NewStepResult(scenarioId string, step *Step) StepResult { - return StepResult{FinishedAt: TimeNowFunc(), ScenarioId: scenarioId, Step: step} -} - -type StepStatus int - -const ( - Passed StepStatus = iota - Failed - Skipped - Undefined - Pending -) - -// String ... -func (st StepStatus) String() string { - switch st { - case Passed: - return "passed" - case Failed: - return "failed" - case Skipped: - return "skipped" - case Undefined: - return "undefined" - case Pending: - return "pending" - default: - return "unknown" - } -} diff --git a/cmd/devnet/scenarios/run.go b/cmd/devnet/scenarios/run.go deleted file mode 100644 index dd82918499c..00000000000 --- a/cmd/devnet/scenarios/run.go +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package scenarios - -import ( - "context" - "sync" - - "github.com/erigontech/erigon/cmd/devnet/devnetutils" -) - -type SimulationInitializer func(*SimulationContext) - -func Run(ctx context.Context, scenarios ...*Scenario) error { - if len(scenarios) == 0 { - return nil - } - - return runner{scenarios: scenarios}.runWithOptions(ctx, getDefaultOptions()) -} - -type runner struct { - randomize bool - stopOnFailure bool - - scenarios []*Scenario - - simulationInitializer SimulationInitializer -} - -func (r *runner) concurrent(ctx context.Context, rate int) (err error) { - var copyLock sync.Mutex - - queue := make(chan int, rate) - scenarios := make([]*Scenario, len(r.scenarios)) - - if r.randomize { - for i := range r.scenarios { - j := devnetutils.RandomInt(i + 1) - scenarios[i] = r.scenarios[j] - } - - } else { - copy(scenarios, r.scenarios) - } - - simulationContext := SimulationContext{ - suite: &suite{ - randomize: r.randomize, - defaultContext: ctx, - stepRunners: stepRunners(ctx), - }, - } - - for i, s := range scenarios { - scenario := *s - - queue <- i // reserve space in queue - - runScenario := func(err *error, Scenario *Scenario) { - defer func() { - <-queue // free a space in queue - }() - - if r.stopOnFailure && *err != nil { - return - } - - // Copy base suite. - suite := *simulationContext.suite - - if r.simulationInitializer != nil { - sc := SimulationContext{suite: &suite} - r.simulationInitializer(&sc) - } - - _, serr := suite.runScenario(&scenario) - if suite.shouldFail(serr) { - copyLock.Lock() - *err = serr - copyLock.Unlock() - } - } - - if rate == 1 { - // Running within the same goroutine for concurrency 1 - // to preserve original stacks and simplify debugging. - runScenario(&err, &scenario) - } else { - go runScenario(&err, &scenario) - } - } - - // wait until last are processed - for i := 0; i < rate; i++ { - queue <- i - } - - close(queue) - - return err -} - -func (runner runner) runWithOptions(ctx context.Context, opt *Options) error { - //var output io.Writer = os.Stdout - //if nil != opt.Output { - // output = opt.Output - //} - - if opt.Concurrency < 1 { - opt.Concurrency = 1 - } - - return runner.concurrent(ctx, opt.Concurrency) -} - -type Options struct { - Concurrency int -} - -func getDefaultOptions() *Options { - opt := &Options{ - Concurrency: 1, - } - return opt -} diff --git a/cmd/devnet/scenarios/scenario.go b/cmd/devnet/scenarios/scenario.go deleted file mode 100644 index 29aeace1db5..00000000000 --- a/cmd/devnet/scenarios/scenario.go +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package scenarios - -import ( - "context" - "errors" - "fmt" - "path" - "reflect" - "regexp" - "runtime" - "unicode" - - "github.com/erigontech/erigon-lib/log/v3" - "github.com/erigontech/erigon/cmd/devnet/devnet" -) - -var ( - ErrUnmatchedStepArgumentNumber = errors.New("func received more arguments than expected") - ErrCannotConvert = errors.New("cannot convert argument") - ErrUnsupportedArgumentType = errors.New("unsupported argument type") -) - -var stepRunnerRegistry = map[reflect.Value]*stepRunner{} - -type stepHandler struct { - handler reflect.Value - matchExpressions []string -} - -func RegisterStepHandlers(handlers ...stepHandler) error { - for _, h := range handlers { - var exprs []*regexp.Regexp - - if kind := h.handler.Kind(); kind != reflect.Func { - return fmt.Errorf("Can't register non-function %s as step handler", kind) - } - - if len(h.matchExpressions) == 0 { - name := path.Ext(runtime.FuncForPC(h.handler.Pointer()).Name())[1:] - - if unicode.IsLower(rune(name[0])) { - return fmt.Errorf("Can't register unexported function %s as step handler", name) - } - - h.matchExpressions = []string{ - name, - } - } - - for _, e := range h.matchExpressions { - exp, err := regexp.Compile(e) - - if err != nil { - return err - } - - exprs = append(exprs, exp) - } - - stepRunnerRegistry[h.handler] = &stepRunner{ - Handler: h.handler, - Exprs: exprs, - } - } - - return nil -} - -func MustRegisterStepHandlers(handlers ...stepHandler) { - if err := RegisterStepHandlers(handlers...); err != nil { - panic(fmt.Errorf("Step handler registration failed: %w", err)) - } -} - -func StepHandler(handler interface{}, matchExpressions ...string) stepHandler { - return stepHandler{reflect.ValueOf(handler), matchExpressions} -} - -type Scenario struct { - Context devnet.Context `json:"-"` - Id string `json:"id"` - Name string `json:"name"` - Description string `json:"description,omitempty"` - Steps []*Step `json:"steps"` -} - -type Step struct { - Id string `json:"id"` - Args []interface{} `json:"args,omitempty"` - Text string `json:"text"` - Description string `json:"description,omitempty"` -} - -type stepRunner struct { - Exprs []*regexp.Regexp - Handler reflect.Value - // multistep related - Nested bool - Undefined []string -} - -var typeOfBytes = reflect.TypeOf([]byte(nil)) - -var typeOfContext = reflect.TypeOf((*context.Context)(nil)).Elem() - -func (c *stepRunner) Run(ctx context.Context, text string, args []interface{}, logger log.Logger) (context.Context, interface{}) { - var values = make([]reflect.Value, 0, len(args)) - - typ := c.Handler.Type() - numIn := typ.NumIn() - hasCtxIn := numIn > 0 && typ.In(0).Implements(typeOfContext) - - if hasCtxIn { - values = append(values, reflect.ValueOf(ctx)) - numIn-- - } - - if len(args) < numIn { - return ctx, fmt.Errorf("Expected %d arguments, matched %d from step", typ.NumIn(), len(args)) - } - - for _, arg := range args { - values = append(values, reflect.ValueOf(arg)) - } - - handler := c.Handler.String() - logger.Info("Calling step: "+text, "handler", handler[1:len(handler)-7], "args", args) - - res := c.Handler.Call(values) - - if len(res) == 0 { - return ctx, nil - } - - r := res[0].Interface() - - if rctx, ok := r.(context.Context); ok { - if len(res) == 1 { - return rctx, nil - } - - res = res[1:] - ctx = rctx - } - - if len(res) == 1 { - return ctx, res[0].Interface() - } - - var results = make([]interface{}, 0, len(res)) - - for _, value := range res { - results = append(results, value.Interface()) - } - - return ctx, results -} - -type Scenarios map[string]*Scenario - -func (s Scenarios) Run(ctx context.Context, scenarioNames ...string) error { - var scenarios []*Scenario - - if len(scenarioNames) == 0 { - for name, scenario := range s { - scenario.Name = name - scenarios = append(scenarios, scenario) - } - } else { - for _, name := range scenarioNames { - if scenario, ok := s[name]; ok { - scenario.Name = name - scenarios = append(scenarios, scenario) - } - } - } - - return Run(ctx, scenarios...) -} diff --git a/cmd/devnet/scenarios/stack.go b/cmd/devnet/scenarios/stack.go deleted file mode 100644 index 29d407bcd54..00000000000 --- a/cmd/devnet/scenarios/stack.go +++ /dev/null @@ -1,157 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package scenarios - -import ( - "fmt" - "go/build" - "io" - "path" - "path/filepath" - "runtime" - "strings" -) - -// Frame represents a program counter inside a stack frame. -type stackFrame uintptr - -// pc returns the program counter for this frame; -// multiple frames may have the same PC value. -func (f stackFrame) pc() uintptr { return uintptr(f) - 1 } - -// file returns the full path to the file that contains the -// function for this Frame's pc. -func (f stackFrame) file() string { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return "unknown" - } - file, _ := fn.FileLine(f.pc()) - return file -} - -func trimGoPath(file string) string { - for _, p := range filepath.SplitList(build.Default.GOPATH) { - file = strings.Replace(file, filepath.Join(p, "src")+string(filepath.Separator), "", 1) - } - return file -} - -// line returns the line number of source code of the -// function for this Frame's pc. -func (f stackFrame) line() int { - fn := runtime.FuncForPC(f.pc()) - if fn == nil { - return 0 - } - _, line := fn.FileLine(f.pc()) - return line -} - -// Format formats the frame according to the fmt.Formatter interface. -// -// %s source file -// %d source line -// %n function name -// %v equivalent to %s:%d -// -// Format accepts flags that alter the printing of some verbs, as follows: -// -// %+s path of source file relative to the compile time GOPATH -// %+v equivalent to %+s:%d -func (f stackFrame) Format(s fmt.State, verb rune) { - funcname := func(name string) string { - i := strings.LastIndex(name, "/") - name = name[i+1:] - i = strings.Index(name, ".") - return name[i+1:] - } - - switch verb { - case 's': - switch { - case s.Flag('+'): - pc := f.pc() - fn := runtime.FuncForPC(pc) - if fn == nil { - io.WriteString(s, "unknown") - } else { - file, _ := fn.FileLine(pc) - fmt.Fprintf(s, "%s\n\t%s", fn.Name(), trimGoPath(file)) - } - default: - io.WriteString(s, path.Base(f.file())) - } - case 'd': - fmt.Fprintf(s, "%d", f.line()) - case 'n': - name := runtime.FuncForPC(f.pc()).Name() - io.WriteString(s, funcname(name)) - case 'v': - f.Format(s, 's') - io.WriteString(s, ":") - f.Format(s, 'd') - } -} - -// stack represents a stack of program counters. -type stack []uintptr - -func (s *stack) Format(st fmt.State, verb rune) { - switch verb { - case 'v': - switch { - case st.Flag('+'): - for _, pc := range *s { - f := stackFrame(pc) - fmt.Fprintf(st, "\n%+v", f) - } - } - } -} - -func callStack() *stack { - const depth = 32 - var pcs [depth]uintptr - n := runtime.Callers(3, pcs[:]) - var st stack = pcs[0:n] - return &st -} - -// fundamental is an error that has a message and a stack, but no caller. -type traceError struct { - msg string - *stack -} - -func (f *traceError) Error() string { return f.msg } - -func (f *traceError) Format(s fmt.State, verb rune) { - switch verb { - case 'v': - if s.Flag('+') { - io.WriteString(s, f.msg) - f.stack.Format(s, verb) - return - } - fallthrough - case 's': - io.WriteString(s, f.msg) - case 'q': - fmt.Fprintf(s, "%q", f.msg) - } -} diff --git a/cmd/devnet/scenarios/suite.go b/cmd/devnet/scenarios/suite.go deleted file mode 100644 index 87ba2d4d818..00000000000 --- a/cmd/devnet/scenarios/suite.go +++ /dev/null @@ -1,443 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package scenarios - -import ( - "context" - "errors" - "fmt" - "testing" - "time" - - "github.com/erigontech/erigon-lib/log/v3" - "github.com/erigontech/erigon/cmd/devnet/devnet" -) - -type SimulationContext struct { - suite *suite -} - -type BeforeScenarioHook func(context.Context, *Scenario) (context.Context, error) -type AfterScenarioHook func(context.Context, *Scenario, error) (context.Context, error) -type BeforeStepHook func(context.Context, *Step) (context.Context, error) -type AfterStepHook func(context.Context, *Step, StepStatus, error) (context.Context, error) - -var TimeNowFunc = time.Now - -type suite struct { - stepRunners []*stepRunner - failed bool - randomize bool - strict bool - stopOnFailure bool - testingT *testing.T - defaultContext context.Context - - // suite event handlers - beforeScenarioHandlers []BeforeScenarioHook - afterScenarioHandlers []AfterScenarioHook - beforeStepHandlers []BeforeStepHook - afterStepHandlers []AfterStepHook -} - -func (s *suite) runSteps(ctx context.Context, scenario *Scenario, steps []*Step) (context.Context, []StepResult, error) { - var results = make([]StepResult, 0, len(steps)) - var err error - - logger := devnet.Logger(ctx) - - for i, step := range steps { - isLast := i == len(steps)-1 - isFirst := i == 0 - - var stepResult StepResult - - ctx, stepResult = s.runStep(ctx, scenario, step, err, isFirst, isLast, logger) //nolint:fatcontext - - switch { - case stepResult.Err == nil: - case errors.Is(stepResult.Err, ErrUndefined): - // do not overwrite failed error - if err == nil { - err = stepResult.Err - } - default: - err = stepResult.Err - logger.Error("Step failed with error", "scenario", scenario.Name, "step", step.Text, "err", err) - } - - results = append(results, stepResult) - } - - return ctx, results, err -} - -func (s *suite) runStep(ctx context.Context, scenario *Scenario, step *Step, prevStepErr error, isFirst, isLast bool, logger log.Logger) (rctx context.Context, sr StepResult) { - var match *stepRunner - - sr = StepResult{Status: Undefined} - rctx = ctx - - // user multistep definitions may panic - defer func() { - if e := recover(); e != nil { - logger.Error("Step failed with panic", "scenario", scenario.Name, "step", step.Text, "err", e) - sr.Err = &traceError{ - msg: fmt.Sprintf("%v", e), - stack: callStack(), - } - } - - earlyReturn := prevStepErr != nil || sr.Err == ErrUndefined - - // Run after step handlers. - rctx, sr.Err = s.runAfterStepHooks(ctx, step, sr.Status, sr.Err) //nolint - - // Trigger after scenario on failing or last step to attach possible hook error to step. - if isLast || (sr.Status != Skipped && sr.Status != Undefined && sr.Err != nil) { - rctx, sr.Err = s.runAfterScenarioHooks(rctx, scenario, sr.Err) - } - - if earlyReturn { - return - } - - switch sr.Err { - case nil: - sr.Status = Passed - default: - sr.Status = Failed - } - }() - - // run before scenario handlers - if isFirst { - ctx, sr.Err = s.runBeforeScenarioHooks(ctx, scenario) - } - - // run before step handlers - ctx, sr.Err = s.runBeforeStepHooks(ctx, step, sr.Err) - - if sr.Err != nil { - sr = NewStepResult(step.Id, step) - sr.Status = Failed - return ctx, sr - } - - ctx, undef, match, err := s.maybeUndefined(ctx, step.Text, step.Args, logger) - - if err != nil { - return ctx, sr - } else if len(undef) > 0 { - sr = NewStepResult(scenario.Id, step) - sr.Status = Undefined - sr.Err = ErrUndefined - logger.Error("Step failed undefined step", "scenario", scenario.Name, "step", step.Text) - return ctx, sr - } - - if prevStepErr != nil { - sr = NewStepResult(scenario.Id, step) - sr.Status = Skipped - return ctx, sr - } - - ctx, res := match.Run(ctx, step.Text, step.Args, logger) - ctx, sr.Returns, sr.Err = s.maybeSubSteps(ctx, res, logger) - - return ctx, sr -} - -func (s *suite) maybeUndefined(ctx context.Context, text string, args []interface{}, logger log.Logger) (context.Context, []string, *stepRunner, error) { - step := s.matchStep(text) - - if nil == step { - return ctx, []string{text}, nil, nil - } - - var undefined []string - - if !step.Nested { - return ctx, undefined, step, nil - } - - ctx, steps := step.Run(ctx, text, args, logger) - - for _, next := range steps.([]Step) { - ctx, undef, _, err := s.maybeUndefined(ctx, next.Text, nil, logger) - if err != nil { - return ctx, undefined, nil, err - } - undefined = append(undefined, undef...) - } - - return ctx, undefined, nil, nil -} - -func (s *suite) matchStep(text string) *stepRunner { - var matches []*stepRunner - - for _, r := range s.stepRunners { - for _, expr := range r.Exprs { - if m := expr.FindStringSubmatch(text); len(m) > 0 { - matches = append(matches, r) - } - } - } - - if len(matches) == 1 { - return matches[0] - } - - for _, r := range matches { - for _, expr := range r.Exprs { - if m := expr.FindStringSubmatch(text); m[0] == text { - return r - } - } - } - - for _, r := range stepRunnerRegistry { - for _, expr := range r.Exprs { - if m := expr.FindStringSubmatch(text); len(m) > 0 { - matches = append(matches, r) - } - } - } - - if len(matches) == 1 { - return matches[0] - } - - for _, r := range matches { - for _, expr := range r.Exprs { - if m := expr.FindStringSubmatch(text); m[0] == text { - return r - } - } - } - - return nil -} - -func (s *suite) maybeSubSteps(ctx context.Context, result interface{}, logger log.Logger) (context.Context, []interface{}, error) { - if nil == result { - return ctx, nil, nil - } - - var steps []Step - - switch result := result.(type) { - case error: - return ctx, nil, result - case []Step: - steps = result - case []interface{}: - if len(result) == 0 { - return ctx, result, nil - } - - if err, ok := result[len(result)-1].(error); ok { - return ctx, result[0 : len(result)-1], err - } - - return ctx, result, nil - default: - return ctx, nil, fmt.Errorf("unexpected results type: %T - %+v", result, result) - } - - var err error - - for _, step := range steps { - if def := s.matchStep(step.Text); def == nil { - return ctx, nil, ErrUndefined - } else { - ctx, res := def.Run(ctx, step.Text, step.Args, logger) - if ctx, _, err = s.maybeSubSteps(ctx, res, logger); err != nil { - return ctx, nil, fmt.Errorf("%s: %+v", step.Text, err) - } - } - } - return ctx, nil, nil -} - -func (s *suite) runScenario(scenario *Scenario) (sr *ScenarioResult, err error) { - ctx := s.defaultContext - - if scenario.Context != nil { - ctx = JoinContexts(scenario.Context, ctx) - } - - if ctx == nil { - ctx = context.Background() - } - - ctx, cancel := context.WithCancel(ctx) - - defer cancel() - - if len(scenario.Steps) == 0 { - return &ScenarioResult{ScenarioId: scenario.Id, StartedAt: TimeNowFunc()}, ErrUndefined - } - - // Before scenario hooks are called in context of first evaluated step - // so that error from handler can be added to step. - - sr = &ScenarioResult{ScenarioId: scenario.Id, StartedAt: TimeNowFunc()} - - // scenario - if s.testingT != nil { - // Running scenario as a subtest. - s.testingT.Run(scenario.Name, func(t *testing.T) { - ctx, sr.StepResults, err = s.runSteps(ctx, scenario, scenario.Steps) //nolint - if s.shouldFail(err) { - t.Error(err) - } - }) - } else { - ctx, sr.StepResults, err = s.runSteps(ctx, scenario, scenario.Steps) - } - - // After scenario handlers are called in context of last evaluated step - // so that error from handler can be added to step. - - return sr, err -} - -func (s *suite) shouldFail(err error) bool { - if err == nil { - return false - } - - if errors.Is(err, ErrUndefined) { - return s.strict - } - - return true -} - -func (s *suite) runBeforeStepHooks(ctx context.Context, step *Step, err error) (context.Context, error) { - hooksFailed := false - - for _, f := range s.beforeStepHandlers { - hctx, herr := f(ctx, step) - if herr != nil { - hooksFailed = true - - if err == nil { - err = herr - } else { - err = fmt.Errorf("%v, %w", herr, err) - } - } - - if hctx != nil { - ctx = hctx //nolint - } - } - - if hooksFailed { - err = fmt.Errorf("before step hook failed: %w", err) - } - - return ctx, err -} - -func (s *suite) runAfterStepHooks(ctx context.Context, step *Step, status StepStatus, err error) (context.Context, error) { - for _, f := range s.afterStepHandlers { - hctx, herr := f(ctx, step, status, err) - - // Adding hook error to resulting error without breaking hooks loop. - if herr != nil { - if err == nil { - err = herr - } else { - err = fmt.Errorf("%v, %w", herr, err) - } - } - - if hctx != nil { - ctx = hctx //nolint - } - } - - return ctx, err -} - -func (s *suite) runBeforeScenarioHooks(ctx context.Context, scenario *Scenario) (context.Context, error) { - var err error - - // run before scenario handlers - for _, f := range s.beforeScenarioHandlers { - hctx, herr := f(ctx, scenario) - if herr != nil { - if err == nil { - err = herr - } else { - err = fmt.Errorf("%v, %w", herr, err) - } - } - - if hctx != nil { - ctx = hctx //nolint - } - } - - if err != nil { - err = fmt.Errorf("before scenario hook failed: %w", err) - } - - return ctx, err -} - -func (s *suite) runAfterScenarioHooks(ctx context.Context, scenario *Scenario, lastStepErr error) (context.Context, error) { - err := lastStepErr - - hooksFailed := false - isStepErr := true - - // run after scenario handlers - for _, f := range s.afterScenarioHandlers { - hctx, herr := f(ctx, scenario, err) - - // Adding hook error to resulting error without breaking hooks loop. - if herr != nil { - hooksFailed = true - - if err == nil { - isStepErr = false - err = herr - } else { - if isStepErr { - err = fmt.Errorf("step error: %w", err) - isStepErr = false - } - err = fmt.Errorf("%v, %w", herr, err) - } - } - - if hctx != nil { - ctx = hctx //nolint - } - } - - if hooksFailed { - err = fmt.Errorf("after scenario hook failed: %w", err) - } - - return ctx, err -} diff --git a/cmd/devnet/services/accounts/faucet.go b/cmd/devnet/services/accounts/faucet.go deleted file mode 100644 index 25b62312ec8..00000000000 --- a/cmd/devnet/services/accounts/faucet.go +++ /dev/null @@ -1,259 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package accounts - -import ( - "context" - "errors" - "fmt" - "math/big" - "strings" - "sync" - - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon/cmd/devnet/accounts" - "github.com/erigontech/erigon/cmd/devnet/blocks" - "github.com/erigontech/erigon/cmd/devnet/contracts" - "github.com/erigontech/erigon/cmd/devnet/devnet" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/rpc" -) - -type Faucet struct { - sync.Mutex - chainName string - source *accounts.Account - transactOpts *bind.TransactOpts - contractAddress common.Address - contract *contracts.Faucet - deployer *deployer -} - -type deployer struct { - sync.WaitGroup - faucet *Faucet -} - -func (d *deployer) deploy(ctx context.Context, node devnet.Node) { - logger := devnet.Logger(ctx) - - // deploy the contract and get the contract handler - deployCtx := devnet.WithCurrentNode(ctx, node) - - waiter, deployCancel := blocks.BlockWaiter(deployCtx, contracts.DeploymentChecker) - defer deployCancel() - - address, transaction, contract, err := contracts.DeployWithOps(deployCtx, d.faucet.transactOpts, contracts.DeployFaucet) - - if err != nil { - d.faucet.Lock() - defer d.faucet.Unlock() - - d.faucet.deployer = nil - d.faucet.transactOpts = nil - logger.Error("failed to deploy faucet", "chain", d.faucet.chainName, "err", err) - return - } - - block, err := waiter.Await(transaction.Hash()) - - if err != nil { - d.faucet.Lock() - defer d.faucet.Unlock() - - d.faucet.deployer = nil - d.faucet.transactOpts = nil - logger.Error("failed while waiting to deploy faucet", "chain", d.faucet.chainName, "err", err) - return - } - - logger.Info("Faucet deployed", "chain", d.faucet.chainName, "block", block.Number, "addr", address) - - d.faucet.contractAddress = address - d.faucet.contract = contract - - // make the amount received a fraction of the source - //if sbal, err := node.GetBalance(f.source, requests.BlockNumbers.Latest); err == nil { - // fmt.Println(f.source, sbal) - //} - - waiter, receiveCancel := blocks.BlockWaiter(deployCtx, blocks.CompletionChecker) - defer receiveCancel() - - received, receiveHash, err := d.faucet.Receive(deployCtx, d.faucet.source, 20000) - - if err != nil { - logger.Error("Failed to receive faucet funds", "err", err) - return - } - - block, err = waiter.Await(receiveHash) - - if err != nil { - d.faucet.Lock() - defer d.faucet.Unlock() - - d.faucet.deployer = nil - d.faucet.transactOpts = nil - logger.Error("failed while waiting to receive faucet funds", "chain", d.faucet.chainName, "err", err) - return - } - - logger.Info("Faucet funded", "chain", d.faucet.chainName, "block", block.Number, "addr", address, "received", received) - - d.faucet.Lock() - defer d.faucet.Unlock() - d.faucet.deployer = nil - d.Done() -} - -func NewFaucet(chainName string, source *accounts.Account) *Faucet { - return &Faucet{ - chainName: chainName, - source: source, - } -} - -func (f *Faucet) Start(_ context.Context) error { - return nil -} - -func (f *Faucet) Stop() {} - -func (f *Faucet) Address() common.Address { - return f.contractAddress -} - -func (f *Faucet) Contract() *contracts.Faucet { - return f.contract -} - -func (f *Faucet) Source() *accounts.Account { - return f.source -} - -func (f *Faucet) Balance(ctx context.Context) (*big.Int, error) { - f.Lock() - deployer := f.deployer - f.Unlock() - - if deployer != nil { - f.deployer.Wait() - } - - node := devnet.SelectBlockProducer(devnet.WithCurrentNetwork(ctx, f.chainName)) - - if node == nil { - return nil, fmt.Errorf("%s has no block producers", f.chainName) - } - - return node.GetBalance(f.contractAddress, rpc.LatestBlock) -} - -func (f *Faucet) Send(ctx context.Context, destination *accounts.Account, eth float64) (*big.Int, common.Hash, error) { - f.Lock() - deployer := f.deployer - f.Unlock() - - if deployer != nil { - f.deployer.Wait() - } - - if f.transactOpts == nil { - return nil, common.Hash{}, errors.New("faucet not initialized") - } - - node := devnet.SelectNode(ctx) - - count, err := node.GetTransactionCount(f.source.Address, rpc.PendingBlock) - - if err != nil { - return nil, common.Hash{}, err - } - - f.transactOpts.Nonce = count - - amount := accounts.EtherAmount(eth) - trn, err := f.contract.Send(f.transactOpts, destination.Address, amount) - - if err != nil { - return nil, common.Hash{}, err - } - - return amount, trn.Hash(), err -} - -func (f *Faucet) Receive(ctx context.Context, source *accounts.Account, eth float64) (*big.Int, common.Hash, error) { - node := devnet.SelectNode(ctx) - - transactOpts, err := bind.NewKeyedTransactorWithChainID(source.SigKey(), node.ChainID()) - - if err != nil { - return nil, common.Hash{}, err - } - - count, err := node.GetTransactionCount(f.source.Address, rpc.PendingBlock) - - if err != nil { - return nil, common.Hash{}, err - } - - transactOpts.Nonce = count - - transactOpts.Value = accounts.EtherAmount(eth) - - trn, err := (&contracts.FaucetRaw{Contract: f.contract}).Transfer(transactOpts) - - if err != nil { - return nil, common.Hash{}, err - } - - return transactOpts.Value, trn.Hash(), nil -} - -func (f *Faucet) NodeCreated(_ context.Context, _ devnet.Node) { -} - -func (f *Faucet) NodeStarted(ctx context.Context, node devnet.Node) { - logger := devnet.Logger(ctx) - - if strings.HasPrefix(node.GetName(), f.chainName) && node.IsBlockProducer() { - f.Lock() - defer f.Unlock() - - if f.transactOpts != nil { - return - } - - var err error - - f.transactOpts, err = bind.NewKeyedTransactorWithChainID(f.source.SigKey(), node.ChainID()) - - if err != nil { - logger.Error("failed to get transaction ops", "address", f.source, "err", err) - return - } - - f.deployer = &deployer{ - faucet: f, - } - - f.deployer.Add(1) - - go f.deployer.deploy(ctx, node) - } -} diff --git a/cmd/devnet/services/context.go b/cmd/devnet/services/context.go deleted file mode 100644 index 4b02d5d7067..00000000000 --- a/cmd/devnet/services/context.go +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package services - -import ( - "context" - - "github.com/erigontech/erigon/cmd/devnet/devnet" - "github.com/erigontech/erigon/cmd/devnet/services/accounts" - "github.com/erigontech/erigon/cmd/devnet/services/polygon" -) - -type ctxKey int - -const ( - ckFaucet ctxKey = iota -) - -func Faucet(ctx context.Context) *accounts.Faucet { - if network := devnet.CurrentNetwork(ctx); network != nil { - for _, service := range network.Services { - if faucet, ok := service.(*accounts.Faucet); ok { - return faucet - } - } - } - - return nil -} - -func Heimdall(ctx context.Context) *polygon.Heimdall { - if network := devnet.CurrentNetwork(ctx); network != nil { - for _, service := range network.Services { - if heimdall, ok := service.(*polygon.Heimdall); ok { - return heimdall - } - } - } - - return nil -} - -func ProofGenerator(ctx context.Context) *polygon.ProofGenerator { - if network := devnet.CurrentNetwork(ctx); network != nil { - for _, service := range network.Services { - if proofGenerator, ok := service.(*polygon.ProofGenerator); ok { - return proofGenerator - } - } - } - - return nil -} diff --git a/cmd/devnet/services/polygon/checkpoint.go b/cmd/devnet/services/polygon/checkpoint.go deleted file mode 100644 index 75e689f3c16..00000000000 --- a/cmd/devnet/services/polygon/checkpoint.go +++ /dev/null @@ -1,614 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package polygon - -import ( - "context" - "encoding/hex" - "errors" - "fmt" - "math/big" - "strconv" - "strings" - "time" - - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon-lib/common/hexutil" - "github.com/erigontech/erigon-lib/crypto" - "github.com/erigontech/erigon/cmd/devnet/accounts" - "github.com/erigontech/erigon/cmd/devnet/blocks" - "github.com/erigontech/erigon/cmd/devnet/contracts" - "github.com/erigontech/erigon/cmd/devnet/devnet" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/execution/chain/networkname" - "github.com/erigontech/erigon/execution/types" - "github.com/erigontech/erigon/polygon/heimdall" - "github.com/erigontech/erigon/rpc/requests" -) - -type CheckpointBlock struct { - Proposer common.Address `json:"proposer"` - StartBlock uint64 `json:"start_block"` - EndBlock uint64 `json:"end_block"` - RootHash common.Hash `json:"root_hash"` - AccountRootHash common.Hash `json:"account_root_hash"` - BorChainID string `json:"bor_chain_id"` -} - -func (c CheckpointBlock) GetSigners() []byte { - return c.Proposer[:] -} - -func (c CheckpointBlock) GetSignBytes() ([]byte, error) { - /*b, err := ModuleCdc.MarshalJSON(msg) - - if err != nil { - nil, err - } - - return sdk.SortJSON(b)*/ - return nil, errors.New("TODO") -} - -type CheckpointAck struct { - From common.Address `json:"from"` - Number uint64 `json:"number"` - Proposer common.Address `json:"proposer"` - StartBlock uint64 `json:"start_block"` - EndBlock uint64 `json:"end_block"` - RootHash common.Hash `json:"root_hash"` - TxHash common.Hash `json:"tx_hash"` - LogIndex uint64 `json:"log_index"` -} - -var zeroHash common.Hash -var zeroAddress common.Address - -func (c CheckpointBlock) ValidateBasic() error { - - if c.RootHash == zeroHash { - return fmt.Errorf("invalid rootHash %v", c.RootHash.String()) - } - - if c.Proposer == zeroAddress { - return fmt.Errorf("invalid proposer %v", c.Proposer.String()) - } - - if c.StartBlock >= c.EndBlock || c.EndBlock == 0 { - return fmt.Errorf("invalid startBlock %v or/and endBlock %v", c.StartBlock, c.EndBlock) - } - - return nil -} - -func (c CheckpointBlock) GetSideSignBytes() []byte { - borChainID, _ := strconv.ParseUint(c.BorChainID, 10, 64) - - return appendBytes32( - c.Proposer.Bytes(), - (&big.Int{}).SetUint64(c.StartBlock).Bytes(), - (&big.Int{}).SetUint64(c.EndBlock).Bytes(), - c.RootHash.Bytes(), - c.AccountRootHash.Bytes(), - (&big.Int{}).SetUint64(borChainID).Bytes(), - ) -} - -func appendBytes32(data ...[]byte) []byte { - var result []byte - - for _, v := range data { - l := len(v) - - var padded [32]byte - - if l > 0 && l <= 32 { - copy(padded[32-l:], v) - } - - result = append(result, padded[:]...) - } - - return result -} - -func (h *Heimdall) startChildHeaderSubscription(ctx context.Context) { - - node := devnet.SelectBlockProducer(ctx) - - var err error - - childHeaderChan := make(chan *types.Header) - h.childHeaderSub, err = node.Subscribe(ctx, requests.Methods.ETHNewHeads, childHeaderChan) - - if err != nil { - h.unsubscribe() - h.logger.Error("Failed to subscribe to child chain headers", "err", err) - } - - for childHeader := range childHeaderChan { - if err := h.handleChildHeader(ctx, childHeader); err != nil { - if errors.Is(err, errNotEnoughChildChainTxConfirmations) { - h.logger.Info("L2 header processing skipped", "header", childHeader.Number, "err", err) - } else { - h.logger.Error("L2 header processing failed", "header", childHeader.Number, "err", err) - } - } - } -} - -func (h *Heimdall) startRootHeaderBlockSubscription() { - var err error - - rootHeaderBlockChan := make(chan *contracts.TestRootChainNewHeaderBlock) - h.rootHeaderBlockSub, err = h.rootChainBinding.WatchNewHeaderBlock(&bind.WatchOpts{}, rootHeaderBlockChan, nil, nil, nil) - - if err != nil { - h.unsubscribe() - h.logger.Error("Failed to subscribe to root chain header blocks", "err", err) - } - - for rootHeaderBlock := range rootHeaderBlockChan { - if err := h.handleRootHeaderBlock(rootHeaderBlock); err != nil { - h.logger.Error("L1 header block processing failed", "block", rootHeaderBlock.HeaderBlockId, "err", err) - } - } -} - -var errNotEnoughChildChainTxConfirmations = errors.New("the chain doesn't have enough blocks for ChildChainTxConfirmations") - -func (h *Heimdall) handleChildHeader(ctx context.Context, header *types.Header) error { - - h.logger.Debug("no of checkpoint confirmations required", "childChainTxConfirmations", h.checkpointConfig.ChildChainTxConfirmations) - - latestConfirmedChildBlock := header.Number.Int64() - int64(h.checkpointConfig.ChildChainTxConfirmations) - - if latestConfirmedChildBlock <= 0 { - return errNotEnoughChildChainTxConfirmations - } - - timeStamp := uint64(time.Now().Unix()) - checkpointBufferTime := uint64(h.checkpointConfig.CheckpointBufferTime.Seconds()) - - if h.pendingCheckpoint == nil { - expectedCheckpointState, err := h.nextExpectedCheckpoint(ctx, uint64(latestConfirmedChildBlock)) - - if err != nil { - h.logger.Error("Error while calculate next expected checkpoint", "error", err) - return err - } - - h.pendingCheckpoint = &heimdall.Checkpoint{ - Fields: heimdall.WaypointFields{ - Timestamp: timeStamp, - StartBlock: new(big.Int).SetUint64(expectedCheckpointState.newStart), - EndBlock: new(big.Int).SetUint64(expectedCheckpointState.newEnd), - }, - } - } - - if header.Number.Cmp(h.pendingCheckpoint.EndBlock()) < 0 { - return nil - } - - h.pendingCheckpoint.Fields.EndBlock = header.Number - - if !(h.pendingCheckpoint.Timestamp() == 0 || - ((timeStamp > h.pendingCheckpoint.Timestamp()) && timeStamp-h.pendingCheckpoint.Timestamp() >= checkpointBufferTime)) { - h.logger.Debug("Pendiing checkpoint awaiting buffer expiry", - "start", h.pendingCheckpoint.StartBlock(), - "end", h.pendingCheckpoint.EndBlock(), - "expiry", time.Unix(int64(h.pendingCheckpoint.Timestamp()+checkpointBufferTime), 0)) - return nil - } - - start := h.pendingCheckpoint.StartBlock().Uint64() - end := h.pendingCheckpoint.EndBlock().Uint64() - - shouldSend, err := h.shouldSendCheckpoint(start, end) - - if err != nil { - return err - } - - if shouldSend { - // TODO simulate tendermint chain stats - txHash := common.Hash{} - blockHeight := int64(0) - - if err := h.createAndSendCheckpointToRootchain(ctx, start, end, blockHeight, txHash); err != nil { - h.logger.Error("Error sending checkpoint to rootchain", "error", err) - return err - } - - h.pendingCheckpoint = nil - } - - return nil -} - -type ContractCheckpoint struct { - newStart uint64 - newEnd uint64 - currentHeaderBlock *HeaderBlock -} - -type HeaderBlock struct { - start uint64 - end uint64 - number *big.Int - checkpointTime uint64 -} - -func (h *Heimdall) nextExpectedCheckpoint(ctx context.Context, latestChildBlock uint64) (*ContractCheckpoint, error) { - - // fetch current header block from mainchain contract - currentHeaderBlock, err := h.currentHeaderBlock(h.checkpointConfig.ChildBlockInterval) - - if err != nil { - h.logger.Error("Error while fetching current header block number from rootchain", "error", err) - return nil, err - } - - // current header block - currentHeaderBlockNumber := big.NewInt(0).SetUint64(currentHeaderBlock) - - // get header info - _, currentStart, currentEnd, lastCheckpointTime, _, err := h.getHeaderInfo(currentHeaderBlockNumber.Uint64()) - - if err != nil { - h.logger.Error("Error while fetching current header block object from rootchain", "error", err) - return nil, err - } - - // find next start/end - var start, end uint64 - start = currentEnd - - // add 1 if start > 0 - if start > 0 { - start = start + 1 - } - - // get diff - diff := int(latestChildBlock - start + 1) - // process if diff > 0 (positive) - if diff > 0 { - expectedDiff := diff - diff%int(h.checkpointConfig.AvgCheckpointLength) - if expectedDiff > 0 { - expectedDiff = expectedDiff - 1 - } - // cap with max checkpoint length - if expectedDiff > int(h.checkpointConfig.MaxCheckpointLength-1) { - expectedDiff = int(h.checkpointConfig.MaxCheckpointLength - 1) - } - // get end result - end = uint64(expectedDiff) + start - h.logger.Debug("Calculating checkpoint eligibility", - "latest", latestChildBlock, - "start", start, - "end", end, - ) - } - - // Handle when block producers go down - if end == 0 || end == start || (0 < diff && diff < int(h.checkpointConfig.AvgCheckpointLength)) { - h.logger.Debug("Fetching last header block to calculate time") - - currentTime := time.Now().UTC().Unix() - defaultForcePushInterval := h.checkpointConfig.MaxCheckpointLength * 2 // in seconds (1024 * 2 seconds) - - if currentTime-int64(lastCheckpointTime) > int64(defaultForcePushInterval) { - end = latestChildBlock - h.logger.Info("Force push checkpoint", - "currentTime", currentTime, - "lastCheckpointTime", lastCheckpointTime, - "defaultForcePushInterval", defaultForcePushInterval, - "start", start, - "end", end, - ) - } - } - - return &ContractCheckpoint{ - newStart: start, - newEnd: end, - currentHeaderBlock: &HeaderBlock{ - start: currentStart, - end: currentEnd, - number: currentHeaderBlockNumber, - checkpointTime: lastCheckpointTime, - }}, nil -} - -func (h *Heimdall) currentHeaderBlock(childBlockInterval uint64) (uint64, error) { - currentHeaderBlock, err := h.rootChainBinding.CurrentHeaderBlock(nil) - - if err != nil { - h.logger.Error("Could not fetch current header block from rootChain contract", "error", err) - return 0, err - } - - return currentHeaderBlock.Uint64() / childBlockInterval, nil -} - -func (h *Heimdall) fetchDividendAccountRoot() (common.Hash, error) { - //TODO - return crypto.Keccak256Hash([]byte("dividendaccountroot")), nil -} - -func (h *Heimdall) getHeaderInfo(number uint64) ( - root common.Hash, - start uint64, - end uint64, - createdAt uint64, - proposer common.Address, - err error, -) { - // get header from rootChain - checkpointBigInt := big.NewInt(0).Mul(big.NewInt(0).SetUint64(number), big.NewInt(0).SetUint64(h.checkpointConfig.ChildBlockInterval)) - - headerBlock, err := h.rootChainBinding.HeaderBlocks(nil, checkpointBigInt) - - if err != nil { - return root, start, end, createdAt, proposer, errors.New("unable to fetch checkpoint block") - } - - createdAt = headerBlock.CreatedAt.Uint64() - - if createdAt == 0 { - createdAt = uint64(h.startTime.Unix()) - } - - return headerBlock.Root, - headerBlock.Start.Uint64(), - headerBlock.End.Uint64(), - createdAt, - common.BytesToAddress(headerBlock.Proposer.Bytes()), - nil -} - -func (h *Heimdall) getRootHash(ctx context.Context, start uint64, end uint64) (common.Hash, error) { - noOfBlock := end - start + 1 - - if start > end { - return common.Hash{}, errors.New("start is greater than end") - } - - if noOfBlock > h.checkpointConfig.MaxCheckpointLength { - return common.Hash{}, errors.New("number of headers requested exceeds") - } - - return devnet.SelectBlockProducer(devnet.WithCurrentNetwork(ctx, networkname.BorDevnet)).GetRootHash(ctx, start, end) -} - -func (h *Heimdall) shouldSendCheckpoint(start uint64, end uint64) (bool, error) { - - // current child block from contract - lastChildBlock, err := h.rootChainBinding.GetLastChildBlock(nil) - - if err != nil { - h.logger.Error("Error fetching current child block", "currentChildBlock", lastChildBlock, "error", err) - return false, err - } - - h.logger.Debug("Fetched current child block", "currentChildBlock", lastChildBlock) - - currentChildBlock := lastChildBlock.Uint64() - - shouldSend := false - // validate if checkpoint needs to be pushed to rootchain and submit - h.logger.Info("Validating if checkpoint needs to be pushed", "commitedLastBlock", currentChildBlock, "startBlock", start) - // check if we need to send checkpoint or not - if ((currentChildBlock + 1) == start) || (currentChildBlock == 0 && start == 0) { - h.logger.Info("Checkpoint Valid", "startBlock", start) - - shouldSend = true - } else if currentChildBlock > start { - h.logger.Info("Start block does not match, checkpoint already sent", "commitedLastBlock", currentChildBlock, "startBlock", start) - } else if currentChildBlock > end { - h.logger.Info("Checkpoint already sent", "commitedLastBlock", currentChildBlock, "startBlock", start) - } else { - h.logger.Info("No need to send checkpoint") - } - - return shouldSend, nil -} - -func (h *Heimdall) createAndSendCheckpointToRootchain(ctx context.Context, start uint64, end uint64, height int64, txHash common.Hash) error { - h.logger.Info("Preparing checkpoint to be pushed on chain", "height", height, "txHash", txHash, "start", start, "end", end) - - /* - // proof - tx, err := helper.QueryTxWithProof(cp.cliCtx, txHash) - if err != nil { - h.logger.Error("Error querying checkpoint txn proof", "txHash", txHash) - return err - } - - // fetch side txs sigs - decoder := helper.GetTxDecoder(authTypes.ModuleCdc) - - stdTx, err := decoder(tx.Tx) - if err != nil { - h.logger.Error("Error while decoding checkpoint tx", "txHash", tx.Tx.Hash(), "error", err) - return err - } - - cmsg := stdTx.GetMsgs()[0] - - sideMsg, ok := cmsg.(hmTypes.SideTxMsg) - if !ok { - h.logger.Error("Invalid side-tx msg", "txHash", tx.Tx.Hash()) - return err - } - */ - - shouldSend, err := h.shouldSendCheckpoint(start, end) - - if err != nil { - return err - } - - if shouldSend { - accountRoot, err := h.fetchDividendAccountRoot() - - if err != nil { - return err - } - - h.pendingCheckpoint.Fields.RootHash, err = h.getRootHash(ctx, start, end) - - if err != nil { - return err - } - - checkpoint := CheckpointBlock{ - Proposer: h.checkpointConfig.CheckpointAccount.Address, - StartBlock: start, - EndBlock: end, - RootHash: h.pendingCheckpoint.RootHash(), - AccountRootHash: accountRoot, - BorChainID: h.chainConfig.ChainID.String(), - } - - // side-tx data - sideTxData := checkpoint.GetSideSignBytes() - - // get sigs - sigs /*, err*/ := [][3]*big.Int{} //helper.FetchSideTxSigs(cp.httpClient, height, tx.Tx.Hash(), sideTxData) - - /* - if err != nil { - h.logger.Error("Error fetching votes for checkpoint tx", "height", height) - return err - }*/ - - if err := h.sendCheckpoint(ctx, sideTxData, sigs); err != nil { - h.logger.Info("Error submitting checkpoint to rootchain", "error", err) - return err - } - } - - return nil -} - -func (h *Heimdall) sendCheckpoint(ctx context.Context, signedData []byte, sigs [][3]*big.Int) error { - - s := make([]string, 0) - for i := 0; i < len(sigs); i++ { - s = append(s, fmt.Sprintf("[%s,%s,%s]", sigs[i][0].String(), sigs[i][1].String(), sigs[i][2].String())) - } - - h.logger.Debug("Sending new checkpoint", - "sigs", strings.Join(s, ","), - "data", hex.EncodeToString(signedData), - ) - - node := devnet.SelectBlockProducer(ctx) - - auth, err := bind.NewKeyedTransactorWithChainID(accounts.SigKey(h.checkpointConfig.CheckpointAccount.Address), node.ChainID()) - - if err != nil { - h.logger.Error("Error while getting auth to submit checkpoint", "err", err) - return err - } - - waiter, cancel := blocks.BlockWaiter(ctx, blocks.CompletionChecker) - defer cancel() - - tx, err := h.rootChainBinding.SubmitCheckpoint(auth, signedData, sigs) - - if err != nil { - h.logger.Error("Error while submitting checkpoint", "err", err) - return err - } - - block, err := waiter.Await(tx.Hash()) - - if err != nil { - h.logger.Error("Error while submitting checkpoint", "err", err) - return err - } - - h.logger.Info("Submitted new checkpoint to rootchain successfully", "txHash", tx.Hash().String(), "block", block.Number) - - return nil -} - -func (h *Heimdall) handleRootHeaderBlock(event *contracts.TestRootChainNewHeaderBlock) error { - h.logger.Info("Received root header") - - checkpointNumber := big.NewInt(0).Div(event.HeaderBlockId, big.NewInt(0).SetUint64(h.checkpointConfig.ChildBlockInterval)) - - h.logger.Info( - "✅ Received checkpoint-ack for heimdall", - "event", "NewHeaderBlock", - "start", event.Start, - "end", event.End, - "reward", event.Reward, - "root", hexutil.Bytes(event.Root[:]), - "proposer", event.Proposer.Hex(), - "checkpointNumber", checkpointNumber, - "txHash", event.Raw.TxHash, - "logIndex", uint64(event.Raw.Index), - ) - - // event checkpoint is older than or equal to latest checkpoint - if h.latestCheckpoint != nil && h.latestCheckpoint.EndBlock >= event.End.Uint64() { - h.logger.Debug("Checkpoint ack is already submitted", "start", event.Start, "end", event.End) - return nil - } - - // create msg checkpoint ack message - ack := CheckpointAck{ - //From common.Address `json:"from"` - Number: checkpointNumber.Uint64(), - Proposer: event.Proposer, - StartBlock: event.Start.Uint64(), - EndBlock: event.End.Uint64(), - RootHash: event.Root, - TxHash: event.Raw.TxHash, - LogIndex: uint64(event.Raw.Index), - } - - if ack.StartBlock != h.pendingCheckpoint.StartBlock().Uint64() { - h.logger.Error("Invalid start block", "startExpected", h.pendingCheckpoint.StartBlock, "startReceived", ack.StartBlock) - return errors.New("invalid Checkpoint Ack: Invalid start block") - } - - // Return err if start and end matches but contract root hash doesn't match - if ack.StartBlock == h.pendingCheckpoint.StartBlock().Uint64() && - ack.EndBlock == h.pendingCheckpoint.EndBlock().Uint64() && ack.RootHash != h.pendingCheckpoint.RootHash() { - h.logger.Error("Invalid ACK", - "startExpected", h.pendingCheckpoint.StartBlock(), - "startReceived", ack.StartBlock, - "endExpected", h.pendingCheckpoint.EndBlock(), - "endReceived", ack.StartBlock, - "rootExpected", h.pendingCheckpoint.RootHash().String(), - "rootRecieved", ack.RootHash.String(), - ) - - return errors.New("invalid Checkpoint Ack: Invalid root hash") - } - - h.latestCheckpoint = &ack - - h.ackWaiter.Broadcast() - - return nil -} diff --git a/cmd/devnet/services/polygon/heimdall.go b/cmd/devnet/services/polygon/heimdall.go deleted file mode 100644 index 09488bf9408..00000000000 --- a/cmd/devnet/services/polygon/heimdall.go +++ /dev/null @@ -1,644 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package polygon - -import ( - "context" - "encoding/json" - "errors" - "math/big" - "net" - "net/http" - "strconv" - "strings" - "sync" - "time" - - "github.com/go-chi/chi/v5" - - ethereum "github.com/erigontech/erigon" - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon-lib/log/v3" - "github.com/erigontech/erigon/cmd/devnet/accounts" - "github.com/erigontech/erigon/cmd/devnet/blocks" - "github.com/erigontech/erigon/cmd/devnet/contracts" - "github.com/erigontech/erigon/cmd/devnet/devnet" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/execution/chain" - "github.com/erigontech/erigon/polygon/bor/borcfg" - - "github.com/erigontech/erigon/polygon/bridge" - "github.com/erigontech/erigon/polygon/heimdall" -) - -type BridgeEvent string - -var BridgeEvents = struct { - StakingEvent BridgeEvent - TopupEvent BridgeEvent - ClerkEvent BridgeEvent - SlashingEvent BridgeEvent -}{ - StakingEvent: "staking", - TopupEvent: "topup", - ClerkEvent: "clerk", - SlashingEvent: "slashing", -} - -type syncRecordKey struct { - hash common.Hash - index uint64 -} - -const ( - DefaultRootChainTxConfirmations uint64 = 6 - DefaultChildChainTxConfirmations uint64 = 10 - DefaultAvgCheckpointLength uint64 = 256 - DefaultMaxCheckpointLength uint64 = 1024 - DefaultChildBlockInterval uint64 = 10000 - DefaultCheckpointBufferTime time.Duration = 1000 * time.Second -) - -const HeimdallURLDefault = "http://localhost:1317" - -type CheckpointConfig struct { - RootChainTxConfirmations uint64 - ChildChainTxConfirmations uint64 - ChildBlockInterval uint64 - AvgCheckpointLength uint64 - MaxCheckpointLength uint64 - CheckpointBufferTime time.Duration - CheckpointAccount *accounts.Account -} - -type Heimdall struct { - sync.Mutex - chainConfig *chain.Config - borConfig *borcfg.BorConfig - listenAddr string - validatorSet *heimdall.ValidatorSet - pendingCheckpoint *heimdall.Checkpoint - latestCheckpoint *CheckpointAck - ackWaiter *sync.Cond - currentSpan *heimdall.Span - spans map[heimdall.SpanId]*heimdall.Span - logger log.Logger - cancelFunc context.CancelFunc - syncSenderAddress common.Address - syncSenderBinding *contracts.TestStateSender - rootChainAddress common.Address - rootChainBinding *contracts.TestRootChain - syncSubscription ethereum.Subscription - rootHeaderBlockSub ethereum.Subscription - childHeaderSub ethereum.Subscription - pendingSyncRecords map[syncRecordKey]*EventRecordWithBlock - checkpointConfig CheckpointConfig - startTime time.Time -} - -func NewHeimdall( - chainConfig *chain.Config, - serverURL string, - checkpointConfig *CheckpointConfig, - logger log.Logger, -) *Heimdall { - heimdall := &Heimdall{ - chainConfig: chainConfig, - borConfig: chainConfig.Bor.(*borcfg.BorConfig), - listenAddr: serverURL[7:], - checkpointConfig: *checkpointConfig, - spans: map[heimdall.SpanId]*heimdall.Span{}, - pendingSyncRecords: map[syncRecordKey]*EventRecordWithBlock{}, - logger: logger} - - heimdall.ackWaiter = sync.NewCond(heimdall) - - if heimdall.checkpointConfig.RootChainTxConfirmations == 0 { - heimdall.checkpointConfig.RootChainTxConfirmations = DefaultRootChainTxConfirmations - } - - if heimdall.checkpointConfig.ChildChainTxConfirmations == 0 { - heimdall.checkpointConfig.ChildChainTxConfirmations = DefaultChildChainTxConfirmations - } - - if heimdall.checkpointConfig.ChildBlockInterval == 0 { - heimdall.checkpointConfig.ChildBlockInterval = DefaultChildBlockInterval - } - - if heimdall.checkpointConfig.AvgCheckpointLength == 0 { - heimdall.checkpointConfig.AvgCheckpointLength = DefaultAvgCheckpointLength - } - - if heimdall.checkpointConfig.MaxCheckpointLength == 0 { - heimdall.checkpointConfig.MaxCheckpointLength = DefaultMaxCheckpointLength - } - - if heimdall.checkpointConfig.CheckpointBufferTime == 0 { - heimdall.checkpointConfig.CheckpointBufferTime = DefaultCheckpointBufferTime - } - - if heimdall.checkpointConfig.CheckpointAccount == nil { - heimdall.checkpointConfig.CheckpointAccount = accounts.NewAccount("checkpoint-owner") - } - - return heimdall -} - -func (h *Heimdall) FetchSpan(ctx context.Context, spanID uint64) (*heimdall.Span, error) { - h.Lock() - defer h.Unlock() - - if span, ok := h.spans[heimdall.SpanId(spanID)]; ok { - h.currentSpan = span - return span, nil - } - - var nextSpan = heimdall.Span{ - Id: heimdall.SpanId(spanID), - ValidatorSet: *h.validatorSet, - ChainID: h.chainConfig.ChainID.String(), - } - - if h.currentSpan == nil || spanID == 0 { - nextSpan.StartBlock = 1 //256 - } else { - if spanID != uint64(h.currentSpan.Id+1) { - return nil, errors.New("can't initialize span: non consecutive span") - } - - nextSpan.StartBlock = h.currentSpan.EndBlock + 1 - } - - nextSpan.EndBlock = nextSpan.StartBlock + (100 * h.borConfig.CalculateSprintLength(nextSpan.StartBlock)) - 1 - - // TODO we should use a subset here - see: https://wiki.polygon.technology/docs/pos/bor/ - - nextSpan.SelectedProducers = make([]heimdall.Validator, len(h.validatorSet.Validators)) - - for i, v := range h.validatorSet.Validators { - nextSpan.SelectedProducers[i] = *v - } - - h.currentSpan = &nextSpan - - h.spans[h.currentSpan.Id] = h.currentSpan - - return h.currentSpan, nil -} - -func (h *Heimdall) FetchSpans(ctx context.Context, page uint64, limit uint64) ([]*heimdall.Span, error) { - return nil, errors.New("TODO") -} - -func (h *Heimdall) FetchLatestSpan(ctx context.Context) (*heimdall.Span, error) { - return nil, errors.New("TODO") -} - -func (h *Heimdall) currentSprintLength() int { - if h.currentSpan != nil { - return int(h.borConfig.CalculateSprintLength(h.currentSpan.StartBlock)) - } - - return int(h.borConfig.CalculateSprintLength(256)) -} - -func (h *Heimdall) getSpanOverrideHeight() uint64 { - return 0 - //MainChain: 8664000 -} - -func (h *Heimdall) FetchStatus(ctx context.Context) (*heimdall.Status, error) { - return nil, errors.New("TODO") -} - -func (h *Heimdall) FetchCheckpoint(ctx context.Context, number int64) (*heimdall.Checkpoint, error) { - return nil, errors.New("TODO") -} - -func (h *Heimdall) FetchCheckpointCount(ctx context.Context) (int64, error) { - return 0, errors.New("TODO") -} - -func (h *Heimdall) FetchCheckpoints(ctx context.Context, page uint64, limit uint64) ([]*heimdall.Checkpoint, error) { - return nil, errors.New("TODO") -} - -func (h *Heimdall) FetchMilestone(ctx context.Context, number int64) (*heimdall.Milestone, error) { - return nil, errors.New("TODO") -} - -func (h *Heimdall) FetchMilestoneCount(ctx context.Context) (int64, error) { - return 0, errors.New("TODO") -} - -func (h *Heimdall) FetchFirstMilestoneNum(ctx context.Context) (int64, error) { - return 0, errors.New("TODO") -} - -func (h *Heimdall) FetchNoAckMilestone(ctx context.Context, milestoneID string) error { - return errors.New("TODO") -} - -func (h *Heimdall) FetchLastNoAckMilestone(ctx context.Context) (string, error) { - return "", errors.New("TODO") -} - -func (h *Heimdall) FetchMilestoneID(ctx context.Context, milestoneID string) error { - return errors.New("TODO") -} - -func (h *Heimdall) FetchStateSyncEvents(ctx context.Context, fromID uint64, to time.Time, limit int) ([]*bridge.EventRecordWithTime, error) { - return nil, errors.New("TODO") -} - -func (h *Heimdall) Close() { - h.unsubscribe() -} - -func (h *Heimdall) unsubscribe() { - h.Lock() - defer h.Unlock() - - if h.syncSubscription != nil { - syncSubscription := h.syncSubscription - h.syncSubscription = nil - syncSubscription.Unsubscribe() - } - - if h.rootHeaderBlockSub != nil { - rootHeaderBlockSub := h.rootHeaderBlockSub - h.rootHeaderBlockSub = nil - rootHeaderBlockSub.Unsubscribe() - } - - if h.childHeaderSub != nil { - childHeaderSub := h.childHeaderSub - h.childHeaderSub = nil - childHeaderSub.Unsubscribe() - } -} - -func (h *Heimdall) StateSenderAddress() common.Address { - return h.syncSenderAddress -} - -func (f *Heimdall) StateSenderContract() *contracts.TestStateSender { - return f.syncSenderBinding -} - -func (h *Heimdall) RootChainAddress() common.Address { - return h.rootChainAddress -} - -func (h *Heimdall) NodeCreated(ctx context.Context, node devnet.Node) { - h.Lock() - defer h.Unlock() - - if strings.HasPrefix(node.GetName(), "bor") && node.IsBlockProducer() && node.Account() != nil { - // TODO configurable voting power - h.addValidator(node.Account().Address, 1000, 0) - } -} - -func (h *Heimdall) NodeStarted(ctx context.Context, node devnet.Node) { - if h.validatorSet == nil { - panic("Heimdall devnet service: unexpected empty validator set! Call addValidator() before starting nodes.") - } - - if !strings.HasPrefix(node.GetName(), "bor") && node.IsBlockProducer() { - h.Lock() - defer h.Unlock() - - if h.syncSenderBinding != nil { - return - } - - h.startTime = time.Now().UTC() - - transactOpts, err := bind.NewKeyedTransactorWithChainID(accounts.SigKey(node.Account().Address), node.ChainID()) - - if err != nil { - h.Unlock() - h.unsubscribe() - h.Lock() - h.logger.Error("Failed to create transact opts for deploying state sender", "err", err) - return - } - - deployCtx := devnet.WithCurrentNode(ctx, node) - waiter, cancel := blocks.BlockWaiter(deployCtx, contracts.DeploymentChecker) - - address, syncTx, syncContract, err := contracts.DeployWithOps(deployCtx, transactOpts, contracts.DeployTestStateSender) - - if err != nil { - h.logger.Error("Failed to deploy state sender", "err", err) - cancel() - return - } - - h.syncSenderAddress = address - h.syncSenderBinding = syncContract - - address, rootChainTx, rootChainContract, err := contracts.DeployWithOps(deployCtx, transactOpts, contracts.DeployTestRootChain) - - if err != nil { - h.syncSenderBinding = nil - h.logger.Error("Failed to deploy root chain", "err", err) - cancel() - return - } - - h.rootChainAddress = address - h.rootChainBinding = rootChainContract - - go func() { - defer cancel() - blocks, err := waiter.AwaitMany(syncTx.Hash(), rootChainTx.Hash()) - - if err != nil { - h.syncSenderBinding = nil - h.logger.Error("Failed to deploy root contracts", "err", err) - return - } - - h.logger.Info("RootChain deployed", "chain", h.chainConfig.ChainName, "block", blocks[syncTx.Hash()].Number, "addr", h.rootChainAddress) - h.logger.Info("StateSender deployed", "chain", h.chainConfig.ChainName, "block", blocks[syncTx.Hash()].Number, "addr", h.syncSenderAddress) - - go h.startStateSyncSubscription() - go h.startChildHeaderSubscription(deployCtx) - go h.startRootHeaderBlockSubscription() - }() - } -} - -func (h *Heimdall) addValidator(validatorAddress common.Address, votingPower int64, proposerPriority int64) { - - if h.validatorSet == nil { - h.validatorSet = heimdall.NewValidatorSet([]*heimdall.Validator{ - { - ID: 1, - Address: validatorAddress, - VotingPower: votingPower, - ProposerPriority: proposerPriority, - }, - }) - } else { - h.validatorSet.UpdateWithChangeSet([]*heimdall.Validator{ - { - ID: uint64(len(h.validatorSet.Validators) + 1), - Address: validatorAddress, - VotingPower: votingPower, - ProposerPriority: proposerPriority, - }, - }) - } -} - -func (h *Heimdall) Start(ctx context.Context) error { - h.Lock() - if h.cancelFunc != nil { - h.Unlock() - return nil - } - ctx, h.cancelFunc = context.WithCancel(ctx) - h.Unlock() - - // if this is a restart - h.unsubscribe() - - server := &http.Server{Addr: h.listenAddr, Handler: makeHeimdallRouter(ctx, h, h)} - return startHTTPServer(ctx, server, "devnet Heimdall service", h.logger) -} - -func makeHeimdallRouter(ctx context.Context, heimdallClient heimdall.Client, bridgeClient bridge.Client) *chi.Mux { - router := chi.NewRouter() - - writeResponse := func(w http.ResponseWriter, result any, err error) { - if err != nil { - http.Error(w, http.StatusText(500), 500) - return - } - - var resultEnvelope struct { - Height string `json:"height"` - Result any `json:"result"` - } - resultEnvelope.Height = "0" - resultEnvelope.Result = result - - response, err := json.Marshal(resultEnvelope) - if err != nil { - http.Error(w, http.StatusText(500), 500) - return - } - - _, _ = w.Write(response) - } - - wrapResult := func(result any) map[string]any { - return map[string]any{ - "result": result, - } - } - - router.Get("/clerk/event-record/list", func(w http.ResponseWriter, r *http.Request) { - fromIdStr := r.URL.Query().Get("from-id") - fromId, err := strconv.ParseUint(fromIdStr, 10, 64) - if err != nil { - http.Error(w, http.StatusText(400), 400) - return - } - - toTimeStr := r.URL.Query().Get("to-time") - toTime, err := strconv.ParseInt(toTimeStr, 10, 64) - if err != nil { - http.Error(w, http.StatusText(400), 400) - return - } - - result, err := bridgeClient.FetchStateSyncEvents(ctx, fromId, time.Unix(toTime, 0), 0) - writeResponse(w, result, err) - }) - - router.Get("/bor/span/{id}", func(w http.ResponseWriter, r *http.Request) { - idStr := chi.URLParam(r, "id") - id, err := strconv.ParseUint(idStr, 10, 64) - if err != nil { - http.Error(w, http.StatusText(400), 400) - return - } - result, err := heimdallClient.FetchSpan(ctx, id) - writeResponse(w, result, err) - }) - - router.Get("/checkpoints/{number}", func(w http.ResponseWriter, r *http.Request) { - numberStr := chi.URLParam(r, "number") - number, err := strconv.ParseInt(numberStr, 10, 64) - if err != nil { - http.Error(w, http.StatusText(400), 400) - return - } - result, err := heimdallClient.FetchCheckpoint(ctx, number) - writeResponse(w, result, err) - }) - - router.Get("/checkpoints/latest", func(w http.ResponseWriter, r *http.Request) { - result, err := heimdallClient.FetchCheckpoint(ctx, -1) - writeResponse(w, result, err) - }) - - router.Get("/checkpoints/count", func(w http.ResponseWriter, r *http.Request) { - result, err := heimdallClient.FetchCheckpointCount(ctx) - writeResponse(w, wrapResult(result), err) - }) - - router.Get("/checkpoints/list", func(w http.ResponseWriter, r *http.Request) { - pageStr := r.URL.Query().Get("page") - page, err := strconv.ParseUint(pageStr, 10, 64) - if err != nil { - http.Error(w, http.StatusText(400), 400) - return - } - - limitStr := r.URL.Query().Get("limit") - limit, err := strconv.ParseUint(limitStr, 10, 64) - if err != nil { - http.Error(w, http.StatusText(400), 400) - return - } - - result, err := heimdallClient.FetchCheckpoints(ctx, page, limit) - writeResponse(w, wrapResult(result), err) - }) - - router.Get("/milestone/{number}", func(w http.ResponseWriter, r *http.Request) { - numberStr := chi.URLParam(r, "number") - number, err := strconv.ParseInt(numberStr, 10, 64) - if err != nil { - http.Error(w, http.StatusText(400), 400) - return - } - result, err := heimdallClient.FetchMilestone(ctx, number) - writeResponse(w, result, err) - }) - - router.Get("/milestone/latest", func(w http.ResponseWriter, r *http.Request) { - result, err := heimdallClient.FetchMilestone(ctx, -1) - writeResponse(w, result, err) - }) - - router.Get("/milestone/count", func(w http.ResponseWriter, r *http.Request) { - result, err := heimdallClient.FetchMilestoneCount(ctx) - writeResponse(w, heimdall.MilestoneCount{Count: result}, err) - }) - - router.Get("/milestone/noAck/{id}", func(w http.ResponseWriter, r *http.Request) { - id := chi.URLParam(r, "id") - err := heimdallClient.FetchNoAckMilestone(ctx, id) - result := err == nil - writeResponse(w, wrapResult(result), err) - }) - - router.Get("/milestone/lastNoAck", func(w http.ResponseWriter, r *http.Request) { - result, err := heimdallClient.FetchLastNoAckMilestone(ctx) - writeResponse(w, wrapResult(result), err) - }) - - router.Get("/milestone/ID/{id}", func(w http.ResponseWriter, r *http.Request) { - id := chi.URLParam(r, "id") - err := heimdallClient.FetchMilestoneID(ctx, id) - result := err == nil - writeResponse(w, wrapResult(result), err) - }) - - return router -} - -func startHTTPServer(ctx context.Context, server *http.Server, serverName string, logger log.Logger) error { - listener, err := net.Listen("tcp", server.Addr) - if err != nil { - return err - } - - go func() { - err := server.Serve(listener) - if (err != nil) && !errors.Is(err, http.ErrServerClosed) { - logger.Error("server.Serve error", "serverName", serverName, "err", err) - } - }() - - go func() { - <-ctx.Done() - _ = server.Close() - }() - - return nil -} - -func (h *Heimdall) Stop() { - var cancel context.CancelFunc - - h.Lock() - if h.cancelFunc != nil { - cancel = h.cancelFunc - h.cancelFunc = nil - } - - h.Unlock() - - if cancel != nil { - cancel() - } -} - -func (h *Heimdall) AwaitCheckpoint(ctx context.Context, blockNumber *big.Int) error { - h.Lock() - defer h.Unlock() - - if ctx.Done() != nil { - go func() { - defer h.ackWaiter.Broadcast() - <-ctx.Done() - }() - } - - for h.latestCheckpoint == nil || h.latestCheckpoint.EndBlock < blockNumber.Uint64() { - if ctx.Err() != nil { - return ctx.Err() - } - - h.ackWaiter.Wait() - } - - return nil -} - -func (h *Heimdall) isOldTx(txHash common.Hash, logIndex uint64, eventType BridgeEvent, event interface{}) (bool, error) { - - // define the endpoint based on the type of event - var status bool - - switch eventType { - case BridgeEvents.StakingEvent: - case BridgeEvents.TopupEvent: - case BridgeEvents.ClerkEvent: - _, status = h.pendingSyncRecords[syncRecordKey{txHash, logIndex}] - case BridgeEvents.SlashingEvent: - } - - return status, nil -} diff --git a/cmd/devnet/services/polygon/heimdall_test.go b/cmd/devnet/services/polygon/heimdall_test.go deleted file mode 100644 index 2d4417c6829..00000000000 --- a/cmd/devnet/services/polygon/heimdall_test.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package polygon - -import ( - "context" - "math/big" - "net/http" - "testing" - "time" - - "github.com/stretchr/testify/require" - "go.uber.org/mock/gomock" - - "github.com/erigontech/erigon/polygon/bridge" - "github.com/erigontech/erigon/polygon/heimdall" -) - -func TestHeimdallServer(t *testing.T) { - t.Skip() - - ctx := context.Background() - ctrl := gomock.NewController(t) - heimdallClient := heimdall.NewMockClient(ctrl) - bridgeClient := bridge.NewMockClient(ctrl) - - events := []*bridge.EventRecordWithTime{ - { - EventRecord: bridge.EventRecord{ - ID: 1, - ChainID: "80002", - }, - Time: time.Now(), - }, - { - EventRecord: bridge.EventRecord{ - ID: 2, - ChainID: "80002", - }, - Time: time.Now(), - }, - } - bridgeClient.EXPECT().FetchStateSyncEvents(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).AnyTimes().Return(events, nil) - - span := &heimdall.Span{ - Id: 1, - StartBlock: 1000, - EndBlock: 2000, - ChainID: "80002", - } - heimdallClient.EXPECT().FetchSpan(gomock.Any(), gomock.Any()).AnyTimes().Return(span, nil) - - checkpoint1 := &heimdall.Checkpoint{ - Fields: heimdall.WaypointFields{ - StartBlock: big.NewInt(1000), - EndBlock: big.NewInt(1999), - ChainID: "80002", - }, - } - heimdallClient.EXPECT().FetchCheckpoint(gomock.Any(), gomock.Any()).AnyTimes().Return(checkpoint1, nil) - heimdallClient.EXPECT().FetchCheckpointCount(gomock.Any()).AnyTimes().Return(int64(1), nil) - - err := http.ListenAndServe(HeimdallURLDefault[7:], makeHeimdallRouter(ctx, heimdallClient, bridgeClient)) - require.NoError(t, err) -} diff --git a/cmd/devnet/services/polygon/heimdallsim/heimdall_simulator.go b/cmd/devnet/services/polygon/heimdallsim/heimdall_simulator.go deleted file mode 100644 index bca8e12460d..00000000000 --- a/cmd/devnet/services/polygon/heimdallsim/heimdall_simulator.go +++ /dev/null @@ -1,280 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package heimdallsim - -import ( - "context" - "errors" - "os" - "time" - - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon-lib/log/v3" - "github.com/erigontech/erigon/db/snaptype" - "github.com/erigontech/erigon/eth/ethconfig" - "github.com/erigontech/erigon/execution/rlp" - "github.com/erigontech/erigon/polygon/bridge" - "github.com/erigontech/erigon/polygon/heimdall" - "github.com/erigontech/erigon/turbo/snapshotsync/freezeblocks" -) - -type HeimdallSimulator struct { - snapshots *heimdall.RoSnapshots - blockReader *freezeblocks.BlockReader - heimdallStore heimdall.Store - bridgeStore bridge.Store - iterations []uint64 // list of final block numbers for an iteration - lastAvailableBlockNumber uint64 - - logger log.Logger -} - -var _ heimdall.Client = (*HeimdallSimulator)(nil) - -type sprintLengthCalculator struct{} - -func (sprintLengthCalculator) CalculateSprintLength(number uint64) uint64 { - return 16 -} - -type noopHeimdallStore struct{} - -func (noopHeimdallStore) Checkpoints() heimdall.EntityStore[*heimdall.Checkpoint] { return nil } -func (noopHeimdallStore) Milestones() heimdall.EntityStore[*heimdall.Milestone] { return nil } -func (noopHeimdallStore) Spans() heimdall.EntityStore[*heimdall.Span] { return nil } -func (noopHeimdallStore) SpanBlockProducerSelections() heimdall.EntityStore[*heimdall.SpanBlockProducerSelection] { - return nil -} -func (noopHeimdallStore) Prepare(ctx context.Context) error { return errors.New("noop") } -func (noopHeimdallStore) Close() {} - -type noopBridgeStore struct{} - -func (noopBridgeStore) Prepare(ctx context.Context) error { - return nil -} - -func (noopBridgeStore) Close() {} - -func (noopBridgeStore) LastEventId(ctx context.Context) (uint64, error) { - return 0, errors.New("noop") -} -func (noopBridgeStore) LastEventIdWithinWindow(ctx context.Context, fromID uint64, toTime time.Time) (uint64, error) { - return 0, errors.New("noop") -} -func (noopBridgeStore) LastProcessedEventId(ctx context.Context) (uint64, error) { - return 0, errors.New("noop") -} -func (noopBridgeStore) LastProcessedBlockInfo(ctx context.Context) (bridge.ProcessedBlockInfo, bool, error) { - return bridge.ProcessedBlockInfo{}, false, errors.New("noop") -} -func (noopBridgeStore) LastFrozenEventId() uint64 { - return 0 -} -func (noopBridgeStore) LastFrozenEventBlockNum() uint64 { - return 0 -} -func (noopBridgeStore) EventTxnToBlockNum(ctx context.Context, borTxHash common.Hash) (uint64, bool, error) { - return 0, false, errors.New("noop") -} -func (noopBridgeStore) EventsByTimeframe(ctx context.Context, timeFrom, timeTo uint64) ([][]byte, []uint64, error) { - return nil, nil, errors.New("noop") -} -func (noopBridgeStore) Events(ctx context.Context, start, end uint64) ([][]byte, error) { - return nil, errors.New("noop") -} -func (noopBridgeStore) BlockEventIdsRange(ctx context.Context, blockHash common.Hash, blockNum uint64) (start uint64, end uint64, ok bool, err error) { - return 0, 0, false, errors.New("noop") -} -func (noopBridgeStore) PutEventTxnToBlockNum(ctx context.Context, eventTxnToBlockNum map[common.Hash]uint64) error { - return nil -} -func (noopBridgeStore) PutEvents(ctx context.Context, events []*bridge.EventRecordWithTime) error { - return nil -} -func (noopBridgeStore) PutBlockNumToEventId(ctx context.Context, blockNumToEventId map[uint64]uint64) error { - return nil -} -func (noopBridgeStore) PutProcessedBlockInfo(ctx context.Context, info []bridge.ProcessedBlockInfo) error { - return nil -} -func (noopBridgeStore) Unwind(ctx context.Context, blockNum uint64) error { - return nil -} -func (noopBridgeStore) BorStartEventId(ctx context.Context, hash common.Hash, blockHeight uint64) (uint64, error) { - return 0, errors.New("noop") -} -func (noopBridgeStore) EventsByBlock(ctx context.Context, hash common.Hash, blockNum uint64) ([]rlp.RawValue, error) { - return nil, errors.New("noop") -} -func (noopBridgeStore) EventsByIdFromSnapshot(from uint64, to time.Time, limit int) ([]*bridge.EventRecordWithTime, bool, error) { - return nil, false, errors.New("noop") -} -func (noopBridgeStore) PruneEvents(ctx context.Context, blocksTo uint64, blocksDeleteLimit int) (deleted int, err error) { - return 0, nil -} - -type heimdallStore struct { - spans heimdall.EntityStore[*heimdall.Span] -} - -func (heimdallStore) Checkpoints() heimdall.EntityStore[*heimdall.Checkpoint] { - return nil -} -func (heimdallStore) Milestones() heimdall.EntityStore[*heimdall.Milestone] { - return nil -} -func (hs heimdallStore) Spans() heimdall.EntityStore[*heimdall.Span] { - return hs.spans -} -func (heimdallStore) SpanBlockProducerSelections() heimdall.EntityStore[*heimdall.SpanBlockProducerSelection] { - return nil -} -func (heimdallStore) Prepare(ctx context.Context) error { - return nil -} -func (heimdallStore) Close() { -} - -func NewHeimdallSimulator(ctx context.Context, snapDir string, logger log.Logger, iterations []uint64) (*HeimdallSimulator, error) { - snapshots := heimdall.NewRoSnapshots(ethconfig.Defaults.Snapshot, snapDir, logger) - - // index local files - localFiles, err := os.ReadDir(snapDir) - if err != nil { - return nil, err - } - - for _, file := range localFiles { - info, _, _ := snaptype.ParseFileName(snapDir, file.Name()) - if info.Ext == ".seg" { - err = info.Type.BuildIndexes(ctx, info, nil, nil, snapDir, nil, log.LvlWarn, logger) - if err != nil { - return nil, err - } - } - } - - if err = snapshots.OpenFolder(); err != nil { - return nil, err - } - - h := HeimdallSimulator{ - snapshots: snapshots, - blockReader: freezeblocks.NewBlockReader(nil, snapshots), - bridgeStore: bridge.NewSnapshotStore(noopBridgeStore{}, snapshots, sprintLengthCalculator{}), - heimdallStore: heimdall.NewSnapshotStore(noopHeimdallStore{}, snapshots), - iterations: iterations, - - logger: logger, - } - - h.Next() - - return &h, nil -} - -func (h *HeimdallSimulator) Close() { - h.snapshots.Close() -} - -// Next moves to the next iteration -func (h *HeimdallSimulator) Next() { - if len(h.iterations) == 0 { - h.lastAvailableBlockNumber++ - } else { - h.lastAvailableBlockNumber = h.iterations[0] - h.iterations = h.iterations[1:] - } -} - -func (h *HeimdallSimulator) FetchLatestSpan(ctx context.Context) (*heimdall.Span, error) { - latestSpan := uint64(heimdall.SpanIdAt(h.lastAvailableBlockNumber)) - - span, _, err := h.getSpan(ctx, latestSpan) - if err != nil { - return nil, err - } - - return span, nil -} - -func (h *HeimdallSimulator) FetchSpan(ctx context.Context, spanID uint64) (*heimdall.Span, error) { - if spanID > uint64(heimdall.SpanIdAt(h.lastAvailableBlockNumber)) { - return nil, errors.New("span not found") - } - - span, _, err := h.getSpan(ctx, spanID) - if err != nil { - return nil, err - } - - return span, err -} - -func (h *HeimdallSimulator) FetchSpans(ctx context.Context, page uint64, limit uint64) ([]*heimdall.Span, error) { - return nil, errors.New("method FetchSpans is not implemented") -} - -func (h *HeimdallSimulator) FetchStateSyncEvents(_ context.Context, fromId uint64, to time.Time, limit int) ([]*bridge.EventRecordWithTime, error) { - events, _, err := h.bridgeStore.EventsByIdFromSnapshot(fromId, to, limit) - return events, err -} - -func (h *HeimdallSimulator) FetchStatus(ctx context.Context) (*heimdall.Status, error) { - return nil, errors.New("method FetchStatus not implemented") -} - -func (h *HeimdallSimulator) FetchCheckpoint(ctx context.Context, number int64) (*heimdall.Checkpoint, error) { - return nil, errors.New("method FetchCheckpoint not implemented") -} - -func (h *HeimdallSimulator) FetchCheckpointCount(ctx context.Context) (int64, error) { - return 0, errors.New("method FetchCheckpointCount not implemented") -} - -func (h *HeimdallSimulator) FetchCheckpoints(ctx context.Context, page uint64, limit uint64) ([]*heimdall.Checkpoint, error) { - return nil, errors.New("method FetchCheckpoints not implemented") -} - -func (h *HeimdallSimulator) FetchMilestone(ctx context.Context, number int64) (*heimdall.Milestone, error) { - return nil, errors.New("method FetchMilestone not implemented") -} - -func (h *HeimdallSimulator) FetchMilestoneCount(ctx context.Context) (int64, error) { - return 0, errors.New("method FetchMilestoneCount not implemented") -} - -func (h *HeimdallSimulator) FetchFirstMilestoneNum(ctx context.Context) (int64, error) { - return 0, errors.New("method FetchFirstMilestoneNum not implemented") -} - -func (h *HeimdallSimulator) FetchNoAckMilestone(ctx context.Context, milestoneID string) error { - return errors.New("method FetchNoAckMilestone not implemented") -} - -func (h *HeimdallSimulator) FetchLastNoAckMilestone(ctx context.Context) (string, error) { - return "", errors.New("method FetchLastNoAckMilestone not implemented") -} - -func (h *HeimdallSimulator) FetchMilestoneID(ctx context.Context, milestoneID string) error { - return errors.New("method FetchMilestoneID not implemented") -} - -func (h *HeimdallSimulator) getSpan(ctx context.Context, spanId uint64) (*heimdall.Span, bool, error) { - return h.heimdallStore.Spans().Entity(ctx, spanId) -} diff --git a/cmd/devnet/services/polygon/heimdallsim/heimdall_simulator_test.go b/cmd/devnet/services/polygon/heimdallsim/heimdall_simulator_test.go deleted file mode 100644 index 8223cddf696..00000000000 --- a/cmd/devnet/services/polygon/heimdallsim/heimdall_simulator_test.go +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package heimdallsim_test - -import ( - "context" - _ "embed" - "os" - "path/filepath" - "runtime" - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/erigontech/erigon-lib/log/v3" - "github.com/erigontech/erigon/cmd/devnet/services/polygon/heimdallsim" - "github.com/erigontech/erigon/db/snaptype" - "github.com/erigontech/erigon/polygon/heimdall" -) - -//go:embed testdata/v1.0-000000-000500-borevents.seg -var events []byte - -//go:embed testdata/v1.0-000500-001000-borevents.seg -var events2 []byte - -//go:embed testdata/v1.0-000000-000500-borspans.seg -var spans []byte - -func createFiles(dataDir string, logger log.Logger) error { - destPath := filepath.Join(dataDir) - err := os.MkdirAll(destPath, 0755) - if err != nil { - return err - } - - if _, err = snaptype.LoadSalt(dataDir, true, logger); err != nil { - return err - } - - destFile := filepath.Join(destPath, "v1.0-000000-000500-borevents.seg") - err = os.WriteFile(destFile, events, 0755) - if err != nil { - return err - } - - destFile = filepath.Join(destPath, "v1.0-000500-001000-borevents.seg") - err = os.WriteFile(destFile, events2, 0755) - if err != nil { - return err - } - - destFile = filepath.Join(destPath, "v1.0-000000-000500-borspans.seg") - err = os.WriteFile(destFile, spans, 0755) - if err != nil { - return err - } - - return nil -} - -func setup(t *testing.T, ctx context.Context, iterations []uint64) *heimdallsim.HeimdallSimulator { - logger := log.New() - // logger.SetHandler(log.StdoutHandler) - dataDir := t.TempDir() - - err := createFiles(dataDir, logger) - if err != nil { - t.Fatal(err) - } - - sim, err := heimdallsim.NewHeimdallSimulator(ctx, dataDir, logger, iterations) - if err != nil { - t.Fatal(err) - } - t.Cleanup(sim.Close) - - return sim -} - -func TestSimulatorEvents(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("fix me on win") - } - - // the number of events included in v1.0-000000-000500-borevents.seg - eventsCount := 100 - - ctx := t.Context() - - sim := setup(t, ctx, []uint64{1_000_000}) - - res, err := sim.FetchStateSyncEvents(ctx, 0, time.Now(), 100) - require.NoError(t, err) - assert.Len(t, res, eventsCount) - - resLimit, err := sim.FetchStateSyncEvents(ctx, 0, time.Now(), 2) - require.NoError(t, err) - assert.Len(t, resLimit, 2) - assert.Equal(t, res[:2], resLimit) - - resStart, err := sim.FetchStateSyncEvents(ctx, 10, time.Now(), 5) - require.NoError(t, err) - assert.Len(t, resStart, 5) - assert.Equal(t, uint64(10), resStart[0].ID) - assert.Equal(t, res[9:14], resStart) - - lastTime := res[len(res)-1].Time - resTime, err := sim.FetchStateSyncEvents(ctx, 0, lastTime.Add(-1*time.Second), 100) - require.NoError(t, err) - assert.Len(t, resTime, eventsCount-1) - assert.Equal(t, res[:len(res)-1], resTime) -} - -func TestSimulatorSpans(t *testing.T) { - t.Skip("skipping because sim.FetchLatestSpan(ctx) returns nil") - ctx := t.Context() - - sim := setup(t, ctx, []uint64{100_000, 205_055}) - - // should have the final span from first iteration - span, err := sim.FetchLatestSpan(ctx) - require.NoError(t, err) - assert.Equal(t, heimdall.SpanIdAt(100_000), span.Id) - assert.Equal(t, uint64(96_256), span.StartBlock) - assert.Equal(t, uint64(102_655), span.EndBlock) - - // get the last span - span2, err := sim.FetchSpan(ctx, uint64(heimdall.SpanIdAt(100_000))) - require.NoError(t, err) - assert.Equal(t, span, span2) - - // check if we are in the next iteration - sim.Next() - span3, err := sim.FetchLatestSpan(ctx) - require.NoError(t, err) - assert.Equal(t, heimdall.SpanIdAt(205_055), span3.Id) - assert.Equal(t, uint64(198_656), span3.StartBlock) - assert.Equal(t, uint64(205_055), span3.EndBlock) - - // higher spans should not be available - _, err = sim.FetchSpan(ctx, uint64(heimdall.SpanIdAt(205_055)+1)) - assert.Error(t, err, "span not found") - - // move to next iteration (should be +1 block since we have no more iterations defined) - sim.Next() - span5, err := sim.FetchLatestSpan(ctx) - require.NoError(t, err) - assert.Equal(t, heimdall.SpanIdAt(205_056), span5.Id) - assert.Equal(t, uint64(205_056), span5.StartBlock) - assert.Equal(t, uint64(211_455), span5.EndBlock) -} diff --git a/cmd/devnet/services/polygon/heimdallsim/testdata/v1.0-000000-000500-borevents.seg b/cmd/devnet/services/polygon/heimdallsim/testdata/v1.0-000000-000500-borevents.seg deleted file mode 100644 index f8d6af3bad3..00000000000 Binary files a/cmd/devnet/services/polygon/heimdallsim/testdata/v1.0-000000-000500-borevents.seg and /dev/null differ diff --git a/cmd/devnet/services/polygon/heimdallsim/testdata/v1.0-000000-000500-borspans.seg b/cmd/devnet/services/polygon/heimdallsim/testdata/v1.0-000000-000500-borspans.seg deleted file mode 100644 index 095da9e2416..00000000000 Binary files a/cmd/devnet/services/polygon/heimdallsim/testdata/v1.0-000000-000500-borspans.seg and /dev/null differ diff --git a/cmd/devnet/services/polygon/heimdallsim/testdata/v1.0-000500-001000-borevents.seg b/cmd/devnet/services/polygon/heimdallsim/testdata/v1.0-000500-001000-borevents.seg deleted file mode 100644 index f4e50af84db..00000000000 Binary files a/cmd/devnet/services/polygon/heimdallsim/testdata/v1.0-000500-001000-borevents.seg and /dev/null differ diff --git a/cmd/devnet/services/polygon/proofgenerator.go b/cmd/devnet/services/polygon/proofgenerator.go deleted file mode 100644 index 479d79fe8a6..00000000000 --- a/cmd/devnet/services/polygon/proofgenerator.go +++ /dev/null @@ -1,611 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package polygon - -import ( - "bytes" - "context" - "errors" - "fmt" - "math" - "math/big" - "strings" - "sync" - - "golang.org/x/sync/errgroup" - - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon-lib/common/hexutil" - "github.com/erigontech/erigon-lib/crypto" - "github.com/erigontech/erigon/cl/merkle_tree" - "github.com/erigontech/erigon/cmd/devnet/devnet" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/execution/chain/networkname" - "github.com/erigontech/erigon/execution/rlp" - "github.com/erigontech/erigon/execution/trie" - "github.com/erigontech/erigon/execution/types" - bortypes "github.com/erigontech/erigon/polygon/bor/types" - "github.com/erigontech/erigon/rpc" - "github.com/erigontech/erigon/rpc/ethapi" - "github.com/erigontech/erigon/rpc/requests" -) - -var ErrTokenIndexOutOfRange = errors.New("index is grater than the number of tokens in transaction") - -type ProofGenerator struct { - heimdall *Heimdall -} - -func NewProofGenerator() *ProofGenerator { - return &ProofGenerator{} -} - -func (pg *ProofGenerator) NodeCreated(ctx context.Context, node devnet.Node) { - - if pg.heimdall == nil { - if strings.HasPrefix(node.GetName(), "bor") { - if network := devnet.CurrentNetwork(ctx); network != nil { - for _, service := range network.Services { - if heimdall, ok := service.(*Heimdall); ok { - pg.heimdall = heimdall - } - } - } - } - } -} - -func (pg *ProofGenerator) NodeStarted(ctx context.Context, node devnet.Node) { -} - -func (pg *ProofGenerator) Start(ctx context.Context) error { - return nil -} - -func (pg *ProofGenerator) Stop() { -} - -func (pg *ProofGenerator) GenerateExitPayload(ctx context.Context, burnTxHash common.Hash, eventSignature common.Hash, tokenIndex int) ([]byte, error) { - logger := devnet.Logger(ctx) - - if pg.heimdall == nil || pg.heimdall.rootChainBinding == nil { - return nil, errors.New("ProofGenerator not initialized") - } - - logger.Info("Checking for checkpoint status", "hash", burnTxHash) - - isCheckpointed, err := pg.isCheckPointed(ctx, burnTxHash) - - if err != nil { - return nil, fmt.Errorf("error getting burn transaction: %w", err) - } - - if !isCheckpointed { - return nil, errors.New("eurn transaction has not been checkpointed yet") - } - - // build payload for exit - result, err := pg.buildPayloadForExit(ctx, burnTxHash, eventSignature, tokenIndex) - - if err != nil { - if errors.Is(err, ErrTokenIndexOutOfRange) { - return nil, fmt.Errorf("block not included: %w", err) - } - - return nil, errors.New("null receipt received") - } - - if len(result) == 0 { - return nil, errors.New("null result received") - } - - return result, nil -} - -func (pg *ProofGenerator) getChainBlockInfo(ctx context.Context, burnTxHash common.Hash) (uint64, uint64, error) { - childNode := devnet.SelectBlockProducer(devnet.WithCurrentNetwork(ctx, networkname.BorDevnet)) - - var wg sync.WaitGroup - - var lastChild *big.Int - var burnTransaction *ethapi.RPCTransaction - var err [2]error - - // err group - wg.Add(1) - go func() { - defer wg.Done() - lastChild, err[0] = pg.heimdall.rootChainBinding.GetLastChildBlock(&bind.CallOpts{}) - }() - - wg.Add(1) - go func() { - defer wg.Done() - burnTransaction, err[1] = childNode.GetTransactionByHash(burnTxHash) - }() - - wg.Wait() - - for _, err := range err { - if err != nil { - return 0, 0, err - } - } - - return lastChild.Uint64(), burnTransaction.BlockNumber.Uint64(), nil -} - -// lastchild block is greater equal to transacton block number; -func (pg *ProofGenerator) isCheckPointed(ctx context.Context, burnTxHash common.Hash) (bool, error) { - lastChildBlockNum, burnTxBlockNum, err := pg.getChainBlockInfo(ctx, burnTxHash) - - if err != nil { - return false, err - } - - return lastChildBlockNum >= burnTxBlockNum, nil -} - -func (pg *ProofGenerator) buildPayloadForExit(ctx context.Context, burnTxHash common.Hash, logEventSig common.Hash, index int) ([]byte, error) { - - node := devnet.SelectBlockProducer(ctx) - - if node == nil { - return nil, errors.New("no node available") - } - - if index < 0 { - return nil, errors.New("index must not negative") - } - - var receipt *types.Receipt - var block *requests.Block - - // step 1 - Get Block number from transaction hash - lastChildBlockNum, txBlockNum, err := pg.getChainBlockInfo(ctx, burnTxHash) - - if err != nil { - return nil, err - } - - if lastChildBlockNum < txBlockNum { - return nil, errors.New("burn transaction has not been checkpointed as yet") - } - - // step 2- get transaction receipt from txhash and - // block information from block number - - g, gctx := errgroup.WithContext(ctx) - g.SetLimit(2) - - g.Go(func() error { - var err error - receipt, err = node.GetTransactionReceipt(gctx, burnTxHash) - return err - }) - - g.Go(func() error { - var err error - block, err = node.GetBlockByNumber(gctx, rpc.AsBlockNumber(txBlockNum), true) - return err - }) - - if err := g.Wait(); err != nil { - return nil, err - } - - // step 3 - get information about block saved in parent chain - // step 4 - build block proof - var rootBlockNumber uint64 - var start, end uint64 - - rootBlockNumber, start, end, err = pg.getRootBlockInfo(txBlockNum) - - if err != nil { - return nil, err - } - - blockProofs, err := getBlockProofs(ctx, node, txBlockNum, start, end) - - if err != nil { - return nil, err - } - - // step 5- create receipt proof - receiptProof, err := getReceiptProof(ctx, node, receipt, block, nil) - - if err != nil { - return nil, err - } - - // step 6 - encode payload, convert into hex - var logIndex int - - if index > 0 { - logIndices := getAllLogIndices(logEventSig, receipt) - - if index >= len(logIndices) { - return nil, ErrTokenIndexOutOfRange - } - - logIndex = logIndices[index] - } else { - logIndex = getLogIndex(logEventSig, receipt) - } - - if logIndex < 0 { - return nil, errors.New("log not found in receipt") - } - - parentNodesBytes, err := rlp.EncodeToBytes(receiptProof.parentNodes) - - if err != nil { - return nil, err - } - - return rlp.EncodeToBytes( - []interface{}{ - rootBlockNumber, - hexutil.Encode(bytes.Join(blockProofs, []byte{})), - block.Number.Uint64(), - block.Time, - hexutil.Encode(block.TxHash[:]), - hexutil.Encode(block.ReceiptHash[:]), - hexutil.Encode(getReceiptBytes(receipt)), //rpl encoded - hexutil.Encode(parentNodesBytes), - hexutil.Encode(append([]byte{0}, receiptProof.path...)), - logIndex, - }) -} - -type receiptProof struct { - blockHash common.Hash - parentNodes [][]byte - root []byte - path []byte - value interface{} -} - -func getReceiptProof(ctx context.Context, node requests.RequestGenerator, receipt *types.Receipt, block *requests.Block, receipts []*types.Receipt) (*receiptProof, error) { - stateSyncTxHash := bortypes.ComputeBorTxHash(block.Number.Uint64(), block.Hash) - receiptsTrie := trie.New(trie.EmptyRoot) - - if len(receipts) == 0 { - g, gctx := errgroup.WithContext(ctx) - g.SetLimit(len(block.Transactions)) - - var lock sync.Mutex - - for _, transaction := range block.Transactions { - if transaction.Hash == stateSyncTxHash { - // ignore if txn hash is bor state-sync tx - continue - } - - hash := transaction.Hash - g.Go(func() error { - receipt, err := node.GetTransactionReceipt(gctx, hash) - - if err != nil { - return err - } - - path, _ := rlp.EncodeToBytes(receipt.TransactionIndex) - rawReceipt := getReceiptBytes(receipt) - lock.Lock() - defer lock.Unlock() - receiptsTrie.Update(path, rawReceipt) - - return nil - }) - } - - if err := g.Wait(); err != nil { - return nil, err - } - } else { - for _, receipt := range receipts { - path, _ := rlp.EncodeToBytes(receipt.TransactionIndex) - rawReceipt := getReceiptBytes(receipt) - receiptsTrie.Update(path, rawReceipt) - } - } - - path, _ := rlp.EncodeToBytes(receipt.TransactionIndex) - result, parents, ok := receiptsTrie.FindPath(path) - - if !ok { - return nil, errors.New("node does not contain the key") - } - - var nodeValue any - - if isTypedReceipt(receipt) { - nodeValue = result - } else { - rlp.DecodeBytes(result, nodeValue) - } - - return &receiptProof{ - blockHash: receipt.BlockHash, - parentNodes: parents, - root: block.ReceiptHash[:], - path: path, - value: nodeValue, - }, nil -} - -func getBlockProofs(ctx context.Context, node requests.RequestGenerator, blockNumber, startBlock, endBlock uint64) ([][]byte, error) { - merkleTreeDepth := int(math.Ceil(math.Log2(float64(endBlock - startBlock + 1)))) - - // We generate the proof root down, whereas we need from leaf up - var reversedProof [][]byte - - offset := startBlock - targetIndex := blockNumber - offset - leftBound := uint64(0) - rightBound := endBlock - offset - - // console.log("Searching for", targetIndex); - for depth := 0; depth < merkleTreeDepth; depth++ { - nLeaves := uint64(2) << (merkleTreeDepth - depth) - - // The pivot leaf is the last leaf which is included in the left subtree - pivotLeaf := leftBound + nLeaves/2 - 1 - - if targetIndex > pivotLeaf { - // Get the root hash to the merkle subtree to the left - newLeftBound := pivotLeaf + 1 - subTreeMerkleRoot, err := node.GetRootHash(ctx, offset+leftBound, offset+pivotLeaf) - - if err != nil { - return nil, err - } - - reversedProof = append(reversedProof, subTreeMerkleRoot[:]) - leftBound = newLeftBound - } else { - // Things are more complex when querying to the right. - // Root hash may come some layers down so we need to build a full tree by padding with zeros - // Some trees may be completely empty - - var newRightBound uint64 - - if rightBound <= pivotLeaf { - newRightBound = rightBound - } else { - newRightBound = pivotLeaf - } - - // Expect the merkle tree to have a height one less than the current layer - expectedHeight := merkleTreeDepth - (depth + 1) - if rightBound <= pivotLeaf { - // Tree is empty so we repeatedly hash zero to correct height - subTreeMerkleRoot := recursiveZeroHash(expectedHeight) - reversedProof = append(reversedProof, subTreeMerkleRoot[:]) - } else { - // Height of tree given by RPC node - subTreeHeight := int(math.Ceil(math.Log2(float64(rightBound - pivotLeaf)))) - - // Find the difference in height between this and the subtree we want - heightDifference := expectedHeight - subTreeHeight - - // For every extra layer we need to fill 2*n leaves filled with the merkle root of a zero-filled Merkle tree - // We need to build a tree which has heightDifference layers - - // The first leaf will hold the root hash as returned by the RPC - remainingNodesHash, err := node.GetRootHash(ctx, offset+pivotLeaf+1, offset+rightBound) - - if err != nil { - return nil, err - } - - // The remaining leaves will hold the merkle root of a zero-filled tree of height subTreeHeight - leafRoots := recursiveZeroHash(subTreeHeight) - - // Build a merkle tree of correct size for the subtree using these merkle roots - var leafCount int - - if heightDifference > 0 { - leafCount = 2 << heightDifference - } else { - leafCount = 1 - } - - leaves := make([]interface{}, leafCount) - - leaves[0] = remainingNodesHash[:] - - for i := 1; i < len(leaves); i++ { - leaves[i] = leafRoots[:] - } - - subTreeMerkleRoot, err := merkle_tree.HashTreeRoot(leaves...) - - if err != nil { - return nil, err - } - - reversedProof = append(reversedProof, subTreeMerkleRoot[:]) - } - - rightBound = newRightBound - } - } - - for i, j := 0, len(reversedProof)-1; i < j; i, j = i+1, j-1 { - reversedProof[i], reversedProof[j] = reversedProof[j], reversedProof[i] - } - - return reversedProof, nil -} - -func recursiveZeroHash(n int) common.Hash { - if n == 0 { - return common.Hash{} - } - - subHash := recursiveZeroHash(n - 1) - bytes, _ := rlp.EncodeToBytes([]common.Hash{subHash, subHash}) - return crypto.Keccak256Hash(bytes) -} - -func getAllLogIndices(logEventSig common.Hash, receipt *types.Receipt) []int { - var logIndices []int - - switch logEventSig.Hex() { - case "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef": - case "0xf94915c6d1fd521cee85359239227480c7e8776d7caf1fc3bacad5c269b66a14": - for index, log := range receipt.Logs { - if log.Topics[0] == logEventSig && - log.Topics[2] == zeroHash { - logIndices = append(logIndices, index) - } - } - case "0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62": - case "0x4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb": - for index, log := range receipt.Logs { - if log.Topics[0] == logEventSig && - log.Topics[3] == zeroHash { - logIndices = append(logIndices, index) - } - } - - case "0xf871896b17e9cb7a64941c62c188a4f5c621b86800e3d15452ece01ce56073df": - for index, log := range receipt.Logs { - if strings.EqualFold(hexutil.Encode(log.Topics[0][:]), "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef") && - log.Topics[2] == zeroHash { - logIndices = append(logIndices, index) - } - } - - default: - for index, log := range receipt.Logs { - if log.Topics[0] == logEventSig { - logIndices = append(logIndices, index) - } - } - } - - return logIndices -} - -func getLogIndex(logEventSig common.Hash, receipt *types.Receipt) int { - switch logEventSig.Hex() { - case "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef": - case "0xf94915c6d1fd521cee85359239227480c7e8776d7caf1fc3bacad5c269b66a14": - for index, log := range receipt.Logs { - if log.Topics[0] == logEventSig && - log.Topics[2] == zeroHash { - return index - } - } - - case "0xc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62": - case "0x4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb": - for index, log := range receipt.Logs { - if log.Topics[0] == logEventSig && - log.Topics[3] == zeroHash { - return index - } - } - - default: - for index, log := range receipt.Logs { - if log.Topics[0] == logEventSig { - return index - } - } - } - - return -1 -} - -func (pg *ProofGenerator) getRootBlockInfo(txBlockNumber uint64) (rootBlockNumber uint64, start uint64, end uint64, err error) { - // find in which block child was included in parent - rootBlockNumber, err = pg.findRootBlockFromChild(txBlockNumber) - - if err != nil { - return 0, 0, 0, err - } - - headerBlock, err := pg.heimdall.rootChainBinding.HeaderBlocks(&bind.CallOpts{}, new(big.Int).SetUint64(rootBlockNumber)) - - if err != nil { - return 0, 0, 0, err - } - - return rootBlockNumber, headerBlock.Start.Uint64(), headerBlock.End.Uint64(), nil -} - -const checkPointInterval = uint64(10000) - -func (pg *ProofGenerator) findRootBlockFromChild(childBlockNumber uint64) (uint64, error) { - // first checkpoint id = start * 10000 - start := uint64(1) - - currentHeaderBlock, err := pg.heimdall.rootChainBinding.CurrentHeaderBlock(&bind.CallOpts{}) - - if err != nil { - return 0, err - } - - end := currentHeaderBlock.Uint64() / checkPointInterval - - // binary search on all the checkpoints to find the checkpoint that contains the childBlockNumber - var ans uint64 - - for start <= end { - if start == end { - ans = start - break - } - - mid := (start + end) / 2 - headerBlock, err := pg.heimdall.rootChainBinding.HeaderBlocks(&bind.CallOpts{}, new(big.Int).SetUint64(mid*checkPointInterval)) - - if err != nil { - return 0, err - } - headerStart := headerBlock.Start.Uint64() - headerEnd := headerBlock.End.Uint64() - - if headerStart <= childBlockNumber && childBlockNumber <= headerEnd { - // if childBlockNumber is between the upper and lower bounds of the headerBlock, we found our answer - ans = mid - break - } else if headerStart > childBlockNumber { - // childBlockNumber was checkpointed before this header - end = mid - 1 - } else if headerEnd < childBlockNumber { - // childBlockNumber was checkpointed after this header - start = mid + 1 - } - } - - return ans * checkPointInterval, nil -} - -func isTypedReceipt(receipt *types.Receipt) bool { - return receipt.Status != 0 && receipt.Type != 0 -} - -func getReceiptBytes(receipt *types.Receipt) []byte { - buffer := &bytes.Buffer{} - receipt.EncodeRLP(buffer) - return buffer.Bytes() -} diff --git a/cmd/devnet/services/polygon/proofgenerator_test.go b/cmd/devnet/services/polygon/proofgenerator_test.go deleted file mode 100644 index c03b4debbf0..00000000000 --- a/cmd/devnet/services/polygon/proofgenerator_test.go +++ /dev/null @@ -1,440 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package polygon - -import ( - "bytes" - "context" - "crypto/ecdsa" - "errors" - "fmt" - "math" - "math/big" - "sync" - "testing" - - "github.com/holiman/uint256" - "github.com/pion/randutil" - - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon-lib/common/hexutil" - "github.com/erigontech/erigon-lib/crypto" - "github.com/erigontech/erigon-lib/log/v3" - "github.com/erigontech/erigon/cmd/devnet/blocks" - "github.com/erigontech/erigon/core" - "github.com/erigontech/erigon/core/state" - "github.com/erigontech/erigon/core/vm" - "github.com/erigontech/erigon/db/kv" - "github.com/erigontech/erigon/db/kv/memdb" - "github.com/erigontech/erigon/db/kv/rawdbv3" - "github.com/erigontech/erigon/db/rawdb" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/execution/chain" - "github.com/erigontech/erigon/execution/rlp" - "github.com/erigontech/erigon/execution/stages/mock" - "github.com/erigontech/erigon/execution/types" - "github.com/erigontech/erigon/polygon/bor" - polychain "github.com/erigontech/erigon/polygon/chain" - "github.com/erigontech/erigon/rpc" - "github.com/erigontech/erigon/rpc/ethapi" - "github.com/erigontech/erigon/rpc/requests" - "github.com/erigontech/erigon/turbo/services" - "github.com/erigontech/erigon/turbo/transactions" -) - -type requestGenerator struct { - sync.Mutex - requests.NopRequestGenerator - sentry *mock.MockSentry - bor *bor.Bor - chain *core.ChainPack - db kv.RwDB - txBlockMap map[common.Hash]*types.Block -} - -func newRequestGenerator(sentry *mock.MockSentry, chain *core.ChainPack) (*requestGenerator, error) { - db := memdb.New("", kv.ChainDB) - if err := db.Update(context.Background(), func(tx kv.RwTx) error { - if err := rawdb.WriteHeader(tx, chain.TopBlock.Header()); err != nil { - return err - } - if err := rawdb.WriteHeadHeaderHash(tx, chain.TopBlock.Header().Hash()); err != nil { - return err - } - return nil - }); err != nil { - return nil, err - } - - reader := blockReader{ - chain: chain, - } - - return &requestGenerator{ - db: db, - chain: chain, - sentry: sentry, - bor: bor.NewRo(polychain.BorDevnetChainConfig, reader, log.Root()), - txBlockMap: map[common.Hash]*types.Block{}, - }, nil -} - -func (rg *requestGenerator) GetRootHash(ctx context.Context, startBlock uint64, endBlock uint64) (common.Hash, error) { - tx, err := rg.db.BeginRo(ctx) - if err != nil { - return common.Hash{}, err - } - defer tx.Rollback() - result, err := rg.bor.GetRootHash(ctx, tx, startBlock, endBlock) - - if err != nil { - return common.Hash{}, err - } - - return common.HexToHash(result), nil -} - -func (rg *requestGenerator) GetBlockByNumber(ctx context.Context, blockNum rpc.BlockNumber, withTxs bool) (*requests.Block, error) { - if bn := int(blockNum.Uint64()); bn < len(rg.chain.Blocks) { - block := rg.chain.Blocks[bn] - - transactions := make([]*ethapi.RPCTransaction, len(block.Transactions())) - - for i, txn := range block.Transactions() { - rg.txBlockMap[txn.Hash()] = block - transactions[i] = ethapi.NewRPCTransaction(txn, block.Hash(), blockNum.Uint64(), uint64(i), block.BaseFee()) - } - - return &requests.Block{ - BlockWithTxHashes: requests.BlockWithTxHashes{ - Header: block.Header(), - Hash: block.Hash(), - }, - Transactions: transactions, - }, nil - } - - return nil, fmt.Errorf("block %d not found", blockNum.Uint64()) -} - -func (rg *requestGenerator) GetTransactionReceipt(ctx context.Context, hash common.Hash) (*types.Receipt, error) { - rg.Lock() - defer rg.Unlock() - - block, ok := rg.txBlockMap[hash] - - if !ok { - return nil, fmt.Errorf("can't find block to tx: %s", hash) - } - - engine := rg.bor - chainConfig := polychain.BorDevnetChainConfig - - reader := blockReader{ - chain: rg.chain, - } - - tx, err := rg.sentry.DB.BeginTemporalRo(context.Background()) - if err != nil { - return nil, err - } - defer tx.Rollback() - - ibs, _, _, _, _, err := transactions.ComputeBlockContext(ctx, engine, block.HeaderNoCopy(), chainConfig, reader, rawdbv3.TxNums, tx, 0) - if err != nil { - return nil, err - } - - var gasUsed uint64 - var usedBlobGas uint64 - - gp := new(core.GasPool).AddGas(block.GasLimit()).AddBlobGas(chainConfig.GetMaxBlobGasPerBlock(block.Header().Time)) - - noopWriter := state.NewNoopWriter() - - getHeader := func(hash common.Hash, number uint64) (*types.Header, error) { - return reader.Header(ctx, tx, hash, number) - } - - header := block.Header() - blockNum := block.NumberU64() - - for i, txn := range block.Transactions() { - ibs.SetTxContext(blockNum, i) - - receipt, _, err := core.ApplyTransaction(chainConfig, core.GetHashFn(header, getHeader), engine, nil, gp, ibs, noopWriter, header, txn, &gasUsed, &usedBlobGas, vm.Config{}) - - if err != nil { - return nil, err - } - - if txn.Hash() == hash { - receipt.BlockHash = block.Hash() - return receipt, nil - } - } - - return nil, errors.New("tx not found in block") -} - -type blockReader struct { - services.FullBlockReader - chain *core.ChainPack -} - -func (reader blockReader) BlockByNumber(ctx context.Context, db kv.Tx, number uint64) (*types.Block, error) { - if int(number) < len(reader.chain.Blocks) { - return reader.chain.Blocks[number], nil - } - - return nil, errors.New("block not found") -} - -func (reader blockReader) HeaderByNumber(ctx context.Context, txn kv.Getter, blockNum uint64) (*types.Header, error) { - if int(blockNum) < len(reader.chain.Headers) { - return reader.chain.Headers[blockNum], nil - } - - return nil, errors.New("header not found") -} - -func TestMerkle(t *testing.T) { - startBlock := 1600 - endBlock := 3200 - - if depth := int(math.Ceil(math.Log2(float64(endBlock - startBlock + 1)))); depth != 11 { - t.Fatal("Unexpected depth:", depth) - } - - startBlock = 0 - endBlock = 100000 - - if depth := int(math.Ceil(math.Log2(float64(endBlock - startBlock + 1)))); depth != 17 { - t.Fatal("Unexpected depth:", depth) - } - - startBlock = 0 - endBlock = 500000 - - if depth := int(math.Ceil(math.Log2(float64(endBlock - startBlock + 1)))); depth != 19 { - t.Fatal("Unexpected depth:", depth) - } -} - -func TestBlockGeneration(t *testing.T) { - if testing.Short() { - t.Skip() - } - - _, chain, err := generateBlocks(t, 1600) - - if err != nil { - t.Fatal(err) - } - - reader := blockReader{ - chain: chain, - } - - for number := uint64(0); number < 1600; number++ { - _, err = reader.BlockByNumber(context.Background(), nil, number) - - if err != nil { - t.Fatal(err) - } - - header, err := reader.HeaderByNumber(context.Background(), nil, number) - - if err != nil { - t.Fatal(err) - } - - if header == nil { - t.Fatalf("block header not found: %d", number) - } - } -} - -func TestBlockProof(t *testing.T) { - if testing.Short() { - t.Skip() - } - - sentry, chain, err := generateBlocks(t, 1600) - - if err != nil { - t.Fatal(err) - } - - rg, err := newRequestGenerator(sentry, chain) - - if err != nil { - t.Fatal(err) - } - - _, err = rg.GetRootHash(context.Background(), 0, 1599) - - if err != nil { - t.Fatal(err) - } - - blockProofs, err := getBlockProofs(context.Background(), rg, 10, 0, 1599) - - if err != nil { - t.Fatal(err) - } - - if len := len(blockProofs); len != 11 { - t.Fatal("Unexpected block depth:", len) - } - - if len := len(bytes.Join(blockProofs, []byte{})); len != 352 { - t.Fatal("Unexpected proof len:", len) - } -} - -func TestReceiptProof(t *testing.T) { - sentry, chain, err := generateBlocks(t, 10) - - if err != nil { - t.Fatal(err) - } - - rg, err := newRequestGenerator(sentry, chain) - - if err != nil { - t.Fatal(err) - } - - var block *requests.Block - var blockNo uint64 - - for block == nil { - block, err = rg.GetBlockByNumber(context.Background(), rpc.AsBlockNumber(blockNo), true) - - if err != nil { - t.Fatal(err) - } - - if len(block.Transactions) == 0 { - block = nil - blockNo++ - } - } - - receipt, err := rg.GetTransactionReceipt(context.Background(), block.Transactions[len(block.Transactions)-1].Hash) - - if err != nil { - t.Fatal(err) - } - - receiptProof, err := getReceiptProof(context.Background(), rg, receipt, block, nil) - - if err != nil { - t.Fatal(err) - } - - parentNodesBytes, err := rlp.EncodeToBytes(receiptProof.parentNodes) - - if err != nil { - t.Fatal(err) - } - - fmt.Println(hexutil.Encode(parentNodesBytes), hexutil.Encode(append([]byte{0}, receiptProof.path...))) -} - -func generateBlocks(t *testing.T, number int) (*mock.MockSentry, *core.ChainPack, error) { - - data := getGenesis(3) - - rand := randutil.NewMathRandomGenerator() - - return blocks.GenerateBlocks(t, data.genesisSpec, number, map[int]blocks.TxGen{ - 0: { - Fn: getBlockTx(data.addresses[0], data.addresses[1], uint256.NewInt(uint64(rand.Intn(5000))+1)), - Key: data.keys[0], - }, - 1: { - Fn: getBlockTx(data.addresses[1], data.addresses[2], uint256.NewInt(uint64(rand.Intn(5000))+1)), - Key: data.keys[1], - }, - 2: { - Fn: getBlockTx(data.addresses[2], data.addresses[0], uint256.NewInt(uint64(rand.Intn(5000))+1)), - Key: data.keys[2], - }, - }, func(_ int) int { - return rand.Intn(10) - }) -} - -func getBlockTx(from common.Address, to common.Address, amount *uint256.Int) blocks.TxFn { - return func(block *core.BlockGen, _ bind.ContractBackend) (types.Transaction, bool) { - return types.NewTransaction(block.TxNonce(from), to, amount, 21000, new(uint256.Int), nil), false - } -} - -type initialData struct { - keys []*ecdsa.PrivateKey - addresses []common.Address - transactOpts []*bind.TransactOpts - genesisSpec *types.Genesis -} - -func getGenesis(accounts int, funds ...*big.Int) initialData { - accountFunds := big.NewInt(1000000000) - if len(funds) > 0 { - accountFunds = funds[0] - } - - keys := make([]*ecdsa.PrivateKey, accounts) - - for i := 0; i < accounts; i++ { - keys[i], _ = crypto.GenerateKey() - } - - addresses := make([]common.Address, 0, len(keys)) - transactOpts := make([]*bind.TransactOpts, 0, len(keys)) - allocs := types.GenesisAlloc{} - for _, key := range keys { - addr := crypto.PubkeyToAddress(key.PublicKey) - addresses = append(addresses, addr) - to, err := bind.NewKeyedTransactorWithChainID(key, big.NewInt(1)) - if err != nil { - panic(err) - } - transactOpts = append(transactOpts, to) - - allocs[addr] = types.GenesisAccount{Balance: accountFunds} - } - - return initialData{ - keys: keys, - addresses: addresses, - transactOpts: transactOpts, - genesisSpec: &types.Genesis{ - Config: &chain.Config{ - ChainID: big.NewInt(1), - HomesteadBlock: new(big.Int), - TangerineWhistleBlock: new(big.Int), - SpuriousDragonBlock: big.NewInt(1), - ByzantiumBlock: big.NewInt(1), - ConstantinopleBlock: big.NewInt(1), - }, - Alloc: allocs, - }, - } -} diff --git a/cmd/devnet/services/polygon/statesync.go b/cmd/devnet/services/polygon/statesync.go deleted file mode 100644 index acdd712e9ef..00000000000 --- a/cmd/devnet/services/polygon/statesync.go +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package polygon - -import ( - "context" - "encoding/hex" - "fmt" - "sort" - "time" - - "github.com/erigontech/erigon/cmd/devnet/contracts" - "github.com/erigontech/erigon/execution/abi/bind" - "github.com/erigontech/erigon/polygon/bridge" -) - -// Maximum allowed event record data size -const LegacyMaxStateSyncSize = 100000 - -// New max state sync size after hardfork -const MaxStateSyncSize = 30000 - -type EventRecordWithBlock struct { - bridge.EventRecordWithTime - BlockNumber uint64 -} - -func (h *Heimdall) startStateSyncSubscription() { - var err error - syncChan := make(chan *contracts.TestStateSenderStateSynced, 100) - - h.syncSubscription, err = h.syncSenderBinding.WatchStateSynced(&bind.WatchOpts{}, syncChan, nil, nil) - - if err != nil { - h.unsubscribe() - h.logger.Error("Failed to subscribe to sync events", "err", err) - return - } - - for stateSyncedEvent := range syncChan { - if err := h.handleStateSynced(stateSyncedEvent); err != nil { - h.logger.Error("L1 sync event processing failed", "event", stateSyncedEvent.Raw.Index, "err", err) - } - } -} - -func (h *Heimdall) StateSyncEvents(ctx context.Context, fromID uint64, to int64) ([]*bridge.EventRecordWithTime, error) { - h.Lock() - defer h.Unlock() - - events := make([]*EventRecordWithBlock, 0, len(h.pendingSyncRecords)) - - //var removalKeys []syncRecordKey - - var minEventTime *time.Time - - for _ /*key*/, event := range h.pendingSyncRecords { - if event.ID >= fromID { - if event.Time.Unix() < to { - events = append(events, event) - } - - eventTime := event.Time.Round(1 * time.Second) - - if minEventTime == nil || eventTime.Before(*minEventTime) { - minEventTime = &eventTime - } - } - //else { - //removalKeys = append(removalKeys, key) - //} - } - - if len(events) == 0 { - h.logger.Info("Processed sync request", "from", fromID, "to", time.Unix(to, 0), "min-time", minEventTime, - "pending", len(h.pendingSyncRecords), "filtered", len(events)) - return nil, nil - } - - sort.Slice(events, func(i, j int) bool { - return events[i].ID < events[j].ID - }) - - eventsWithTime := make([]*bridge.EventRecordWithTime, len(events)) - for i, event := range events { - eventsWithTime[i] = &event.EventRecordWithTime - } - - //for _, removalKey := range removalKeys { - // delete(h.pendingSyncRecords, removalKey) - //} - - h.logger.Info("Processed sync request", - "from", fromID, "to", time.Unix(to, 0), "min-time", minEventTime, - "pending", len(h.pendingSyncRecords), "filtered", len(events), - "sent", fmt.Sprintf("%d-%d", events[0].ID, events[len(events)-1].ID)) - - return eventsWithTime, nil -} - -// handleStateSyncEvent - handle state sync event from rootchain -func (h *Heimdall) handleStateSynced(event *contracts.TestStateSenderStateSynced) error { - h.Lock() - defer h.Unlock() - - isOld, _ := h.isOldTx(event.Raw.TxHash, uint64(event.Raw.Index), BridgeEvents.ClerkEvent, event) - - if isOld { - h.logger.Info("Ignoring send event as already processed", - "event", "StateSynced", - "id", event.Id, - "contract", event.ContractAddress, - "data", hex.EncodeToString(event.Data), - "borChainId", h.chainConfig.ChainID, - "txHash", event.Raw.TxHash, - "logIndex", uint64(event.Raw.Index), - "blockNumber", event.Raw.BlockNumber, - ) - - return nil - } - - h.logger.Info( - "⬜ New send event", - "event", "StateSynced", - "id", event.Id, - "contract", event.ContractAddress, - "data", hex.EncodeToString(event.Data), - "borChainId", h.chainConfig.ChainID, - "txHash", event.Raw.TxHash, - "logIndex", uint64(event.Raw.Index), - "blockNumber", event.Raw.BlockNumber, - ) - - if event.Raw.BlockNumber > h.getSpanOverrideHeight() && len(event.Data) > MaxStateSyncSize { - h.logger.Info(`Data is too large to process, Resetting to ""`, "data", hex.EncodeToString(event.Data)) - event.Data = []byte{} - } else if len(event.Data) > LegacyMaxStateSyncSize { - h.logger.Info(`Data is too large to process, Resetting to ""`, "data", hex.EncodeToString(event.Data)) - event.Data = []byte{} - } - - h.pendingSyncRecords[syncRecordKey{event.Raw.TxHash, uint64(event.Raw.Index)}] = &EventRecordWithBlock{ - EventRecordWithTime: bridge.EventRecordWithTime{ - EventRecord: bridge.EventRecord{ - ID: event.Id.Uint64(), - Contract: event.ContractAddress, - Data: event.Data, - TxHash: event.Raw.TxHash, - LogIndex: uint64(event.Raw.Index), - ChainID: h.chainConfig.ChainID.String(), - }, - Time: time.Now(), - }, - BlockNumber: event.Raw.BlockNumber, - } - - return nil -} diff --git a/cmd/devnet/services/polygon/util.go b/cmd/devnet/services/polygon/util.go deleted file mode 100644 index 979a847cfe5..00000000000 --- a/cmd/devnet/services/polygon/util.go +++ /dev/null @@ -1,170 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package polygon - -import ( - "errors" - "fmt" - "math/big" - "reflect" - "strings" - - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon-lib/common/length" - "github.com/erigontech/erigon/execution/abi" - "github.com/erigontech/erigon/execution/types" -) - -// UnpackLog unpacks log -func UnpackLog(abiObject *abi.ABI, out interface{}, event string, log *types.Log) error { - if len(log.Data) > 0 { - if err := abiObject.UnpackIntoInterface(out, event, log.Data); err != nil { - return err - } - } - - var indexed abi.Arguments - - for _, arg := range abiObject.Events[event].Inputs { - if arg.Indexed { - indexed = append(indexed, arg) - } - } - - return parseTopics(out, indexed, log.Topics[1:]) -} - -var ( - reflectHash = reflect.TypeOf(common.Hash{}) - reflectAddress = reflect.TypeOf(common.Address{}) - reflectBigInt = reflect.TypeOf(new(big.Int)) -) - -// parseTopics converts the indexed topic fields into actual log field values. -// -// Note, dynamic types cannot be reconstructed since they get mapped to Keccak256 -// hashes as the topic value! -func parseTopics(out interface{}, fields abi.Arguments, topics []common.Hash) error { - // Sanity check that the fields and topics match up - if len(fields) != len(topics) { - return errors.New("topic/field count mismatch") - } - - // Iterate over all the fields and reconstruct them from topics - for _, arg := range fields { - if !arg.Indexed { - return errors.New("non-indexed field in topic reconstruction") - } - - field := reflect.ValueOf(out).Elem().FieldByName(capitalise(arg.Name)) - - // Try to parse the topic back into the fields based on primitive types - switch field.Kind() { - case reflect.Bool: - if topics[0][length.Hash-1] == 1 { - field.Set(reflect.ValueOf(true)) - } - case reflect.Int8: - num := new(big.Int).SetBytes(topics[0][:]) - field.Set(reflect.ValueOf(int8(num.Int64()))) - case reflect.Int16: - num := new(big.Int).SetBytes(topics[0][:]) - field.Set(reflect.ValueOf(int16(num.Int64()))) - case reflect.Int32: - num := new(big.Int).SetBytes(topics[0][:]) - field.Set(reflect.ValueOf(int32(num.Int64()))) - case reflect.Int64: - num := new(big.Int).SetBytes(topics[0][:]) - field.Set(reflect.ValueOf(num.Int64())) - case reflect.Uint8: - num := new(big.Int).SetBytes(topics[0][:]) - field.Set(reflect.ValueOf(uint8(num.Uint64()))) - case reflect.Uint16: - num := new(big.Int).SetBytes(topics[0][:]) - field.Set(reflect.ValueOf(uint16(num.Uint64()))) - case reflect.Uint32: - num := new(big.Int).SetBytes(topics[0][:]) - field.Set(reflect.ValueOf(uint32(num.Uint64()))) - case reflect.Uint64: - num := new(big.Int).SetBytes(topics[0][:]) - field.Set(reflect.ValueOf(num.Uint64())) - default: - // Ran out of plain primitive types, try custom types - switch field.Type() { - case reflectHash: // Also covers all dynamic types - field.Set(reflect.ValueOf(topics[0])) - case reflectAddress: - var addr common.Address - - copy(addr[:], topics[0][length.Hash-length.Addr:]) - - field.Set(reflect.ValueOf(addr)) - case reflectBigInt: - num := new(big.Int).SetBytes(topics[0][:]) - field.Set(reflect.ValueOf(num)) - default: - // Ran out of custom types, try the crazies - switch { - case arg.Type.T == abi.FixedBytesTy: - reflect.Copy(field, reflect.ValueOf(topics[0][length.Hash-arg.Type.Size:])) - - default: - return fmt.Errorf("unsupported indexed type: %v", arg.Type) - } - } - } - - topics = topics[1:] - } - - return nil -} - -// capitalise makes a camel-case string which starts with an upper case character. -func capitalise(input string) string { - for len(input) > 0 && input[0] == '_' { - input = input[1:] - } - - if len(input) == 0 { - return "" - } - - return toCamelCase(strings.ToUpper(input[:1]) + input[1:]) -} - -// toCamelCase converts an under-score string to a camel-case string -func toCamelCase(input string) string { - toupper := false - result := "" - - for k, v := range input { - switch { - case k == 0: - result = strings.ToUpper(string(input[0])) - case toupper: - result += strings.ToUpper(string(v)) - toupper = false - case v == '_': - toupper = true - default: - result += string(v) - } - } - - return result -} diff --git a/cmd/devnet/services/subscriptions.go b/cmd/devnet/services/subscriptions.go deleted file mode 100644 index e08c1e83baa..00000000000 --- a/cmd/devnet/services/subscriptions.go +++ /dev/null @@ -1,150 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package services - -import ( - "context" - "fmt" - - "github.com/erigontech/erigon-lib/log/v3" - "github.com/erigontech/erigon/cmd/devnet/devnet" - "github.com/erigontech/erigon/cmd/devnet/devnetutils" - "github.com/erigontech/erigon/cmd/devnet/scenarios" - "github.com/erigontech/erigon/rpc" - "github.com/erigontech/erigon/rpc/requests" -) - -func init() { - scenarios.RegisterStepHandlers( - scenarios.StepHandler(InitSubscriptions), - ) -} - -var subscriptions map[string]map[requests.SubMethod]*Subscription - -func GetSubscription(chainName string, method requests.SubMethod) *Subscription { - if methods, ok := subscriptions[chainName]; ok { - if subscription, ok := methods[method]; ok { - return subscription - } - } - - return nil -} - -// Subscription houses the client subscription, name and channel for its delivery -type Subscription struct { - Client *rpc.Client - ClientSub *rpc.ClientSubscription - Name requests.SubMethod - SubChan chan interface{} -} - -// NewSubscription returns a new Subscription instance -func NewSubscription(name requests.SubMethod) *Subscription { - return &Subscription{ - Name: name, - SubChan: make(chan interface{}), - } -} - -func InitSubscriptions(ctx context.Context, methods []requests.SubMethod) { - logger := devnet.Logger(ctx) - - logger.Trace("CONNECTING TO WEBSOCKETS AND SUBSCRIBING TO METHODS...") - if err := subscribeAll(ctx, methods); err != nil { - logger.Error("failed to subscribe to all methods", "error", err) - return - } -} - -// subscribe connects to a websocket client and returns the subscription handler and a channel buffer -func subscribe(client *rpc.Client, method requests.SubMethod, args ...interface{}) (*Subscription, error) { - methodSub := NewSubscription(method) - - namespace, subMethod, err := devnetutils.NamespaceAndSubMethodFromMethod(string(method)) - if err != nil { - return nil, fmt.Errorf("cannot get namespace and submethod from method: %v", err) - } - - arr := append([]interface{}{subMethod}, args...) - - sub, err := client.Subscribe(context.Background(), namespace, methodSub.SubChan, arr...) - if err != nil { - return nil, fmt.Errorf("client failed to subscribe: %v", err) - } - - methodSub.ClientSub = sub - methodSub.Client = client - - return methodSub, nil -} - -func subscribeToMethod(target string, method requests.SubMethod, logger log.Logger) (*Subscription, error) { - client, err := rpc.DialWebsocket(context.Background(), "ws://"+target, "", logger) - - if err != nil { - return nil, fmt.Errorf("failed to dial websocket: %v", err) - } - - sub, err := subscribe(client, method) - if err != nil { - return nil, fmt.Errorf("error subscribing to method: %v", err) - } - - return sub, nil -} - -// UnsubscribeAll closes all the client subscriptions and empties their global subscription channel -func UnsubscribeAll() { - if subscriptions == nil { - return - } - - for _, methods := range subscriptions { - - for _, methodSub := range methods { - if methodSub != nil { - methodSub.ClientSub.Unsubscribe() - for len(methodSub.SubChan) > 0 { - <-methodSub.SubChan - } - methodSub.SubChan = nil // avoid memory leak - } - } - } -} - -// subscribeAll subscribes to the range of methods provided -func subscribeAll(ctx context.Context, methods []requests.SubMethod) error { - subscriptions = map[string]map[requests.SubMethod]*Subscription{} - logger := devnet.Logger(ctx) - - for _, network := range devnet.Networks(ctx) { - subscriptions[network.Chain] = map[requests.SubMethod]*Subscription{} - - for _, method := range methods { - sub, err := subscribeToMethod(devnet.HTTPHost(network.Nodes[0]), method, logger) - if err != nil { - return err - } - subscriptions[network.Chain][method] = sub - } - } - - return nil -} diff --git a/cmd/devnet/tests/bor_devnet_test.go b/cmd/devnet/tests/bor_devnet_test.go deleted file mode 100644 index 0cfb288b9d8..00000000000 --- a/cmd/devnet/tests/bor_devnet_test.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package tests - -import ( - "context" - "testing" - - "github.com/stretchr/testify/require" - - accounts_steps "github.com/erigontech/erigon/cmd/devnet/accounts/steps" - contracts_steps "github.com/erigontech/erigon/cmd/devnet/contracts/steps" - "github.com/erigontech/erigon/cmd/devnet/services" - "github.com/erigontech/erigon/execution/chain/networkname" - "github.com/erigontech/erigon/rpc/requests" -) - -func TestStateSync(t *testing.T) { - t.Skip() - - runCtx, err := ContextStart(t, networkname.BorDevnet) - require.NoError(t, err) - var ctx context.Context = runCtx - - t.Run("InitSubscriptions", func(t *testing.T) { - services.InitSubscriptions(ctx, []requests.SubMethod{requests.Methods.ETHNewHeads}) - }) - t.Run("CreateAccountWithFunds", func(t *testing.T) { - _, err := accounts_steps.CreateAccountWithFunds(ctx, networkname.Dev, "root-funder", 200.0) - require.NoError(t, err) - }) - t.Run("CreateAccountWithFunds", func(t *testing.T) { - _, err := accounts_steps.CreateAccountWithFunds(ctx, networkname.BorDevnet, "child-funder", 200.0) - require.NoError(t, err) - }) - t.Run("DeployChildChainReceiver", func(t *testing.T) { - var err error - ctx, err = contracts_steps.DeployChildChainReceiver(ctx, "child-funder") //nolint - require.NoError(t, err) - }) - t.Run("DeployRootChainSender", func(t *testing.T) { - var err error - ctx, err = contracts_steps.DeployRootChainSender(ctx, "root-funder") //nolint - require.NoError(t, err) - }) - t.Run("GenerateSyncEvents", func(t *testing.T) { - require.NoError(t, contracts_steps.GenerateSyncEvents(ctx, "root-funder", 10, 2, 2)) - }) - t.Run("ProcessRootTransfers", func(t *testing.T) { - require.NoError(t, contracts_steps.ProcessRootTransfers(ctx, "root-funder", 10, 2, 2)) - }) - t.Run("BatchProcessRootTransfers", func(t *testing.T) { - require.NoError(t, contracts_steps.BatchProcessRootTransfers(ctx, "root-funder", 1, 10, 2, 2)) - }) -} - -func TestChildChainExit(t *testing.T) { - t.Skip("FIXME: step CreateAccountWithFunds fails: Failed to get transfer tx: failed to search reserves for hashes: no block heads subscription") - - runCtx, err := ContextStart(t, networkname.BorDevnet) - require.NoError(t, err) - var ctx context.Context = runCtx - - t.Run("CreateAccountWithFunds", func(t *testing.T) { - _, err := accounts_steps.CreateAccountWithFunds(ctx, networkname.Dev, "root-funder", 200.0) - require.NoError(t, err) - }) - t.Run("CreateAccountWithFunds", func(t *testing.T) { - _, err := accounts_steps.CreateAccountWithFunds(ctx, networkname.BorDevnet, "child-funder", 200.0) - require.NoError(t, err) - }) - t.Run("DeployRootChainReceiver", func(t *testing.T) { - var err error - ctx, err = contracts_steps.DeployRootChainReceiver(ctx, "root-funder") //nolint - require.NoError(t, err) - }) - t.Run("DeployChildChainSender", func(t *testing.T) { - var err error - ctx, err = contracts_steps.DeployChildChainSender(ctx, "child-funder") //nolint - require.NoError(t, err) - }) - t.Run("ProcessChildTransfers", func(t *testing.T) { - require.NoError(t, contracts_steps.ProcessChildTransfers(ctx, "child-funder", 1, 2, 2)) - }) - //t.Run("BatchProcessTransfers", func(t *testing.T) { - // require.Nil(t, contracts_steps.BatchProcessTransfers(ctx, "child-funder", 1, 10, 2, 2)) - //}) -} diff --git a/cmd/devnet/tests/context.go b/cmd/devnet/tests/context.go deleted file mode 100644 index b5be0bb3f41..00000000000 --- a/cmd/devnet/tests/context.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package tests - -import ( - "fmt" - "os" - "runtime" - "strconv" - "testing" - - "github.com/erigontech/erigon-lib/log/v3" - "github.com/erigontech/erigon/cmd/devnet/devnet" - "github.com/erigontech/erigon/cmd/devnet/networks" - "github.com/erigontech/erigon/cmd/devnet/services" - "github.com/erigontech/erigon/cmd/devnet/services/polygon" - "github.com/erigontech/erigon/execution/chain/networkname" - "github.com/erigontech/erigon/turbo/debug" -) - -func initDevnet(chainName string, dataDir string, producerCount int, gasLimit uint64, logger log.Logger, consoleLogLevel log.Lvl, dirLogLevel log.Lvl) (devnet.Devnet, error) { - const baseRpcHost = "localhost" - const baseRpcPort = 9545 - - switch chainName { - case networkname.BorDevnet: - heimdallURL := polygon.HeimdallURLDefault - const sprintSize uint64 = 0 - return networks.NewBorDevnetWithLocalHeimdall(dataDir, baseRpcHost, baseRpcPort, heimdallURL, sprintSize, producerCount, gasLimit, logger, consoleLogLevel, dirLogLevel), nil - - case networkname.Dev: - return networks.NewDevDevnet(dataDir, baseRpcHost, baseRpcPort, producerCount, gasLimit, logger, consoleLogLevel, dirLogLevel), nil - - case "": - envChainName, _ := os.LookupEnv("DEVNET_CHAIN") - if envChainName == "" { - envChainName = networkname.Dev - } - return initDevnet(envChainName, dataDir, producerCount, gasLimit, logger, consoleLogLevel, dirLogLevel) - - default: - return nil, fmt.Errorf("unknown network: '%s'", chainName) - } -} - -func ContextStart(t *testing.T, chainName string) (devnet.Context, error) { - //goland:noinspection GoBoolExpressions - if runtime.GOOS == "windows" { - t.Skip("FIXME: TempDir RemoveAll cleanup error: remove dev-0\\clique\\db\\clique\\mdbx.dat: The process cannot access the file because it is being used by another process") - } - - debug.RaiseFdLimit() - logger := log.New() - dataDir := t.TempDir() - - envProducerCount, _ := os.LookupEnv("PRODUCER_COUNT") - if envProducerCount == "" { - envProducerCount = "1" - } - - producerCount, _ := strconv.ParseUint(envProducerCount, 10, 64) - - // TODO get log levels from env - var dirLogLevel log.Lvl = log.LvlTrace - var consoleLogLevel log.Lvl = log.LvlCrit - - var network devnet.Devnet - network, err := initDevnet(chainName, dataDir, int(producerCount), 0, logger, consoleLogLevel, dirLogLevel) - if err != nil { - return nil, fmt.Errorf("ContextStart initDevnet failed: %w", err) - } - - runCtx, err := network.Start(logger) - if err != nil { - return nil, fmt.Errorf("ContextStart devnet start failed: %w", err) - } - - t.Cleanup(services.UnsubscribeAll) - t.Cleanup(network.Stop) - - return runCtx, nil -} diff --git a/cmd/devnet/tests/generic_devnet_test.go b/cmd/devnet/tests/generic_devnet_test.go deleted file mode 100644 index 11b3198873e..00000000000 --- a/cmd/devnet/tests/generic_devnet_test.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package tests - -import ( - "context" - "testing" - "time" - - "github.com/stretchr/testify/require" - - "github.com/erigontech/erigon/cmd/devnet/accounts" - "github.com/erigontech/erigon/cmd/devnet/admin" - contracts_steps "github.com/erigontech/erigon/cmd/devnet/contracts/steps" - "github.com/erigontech/erigon/cmd/devnet/services" - "github.com/erigontech/erigon/cmd/devnet/transactions" - "github.com/erigontech/erigon/rpc/requests" -) - -func testDynamicTx(t *testing.T, ctx context.Context) { - t.Run("InitSubscriptions", func(t *testing.T) { - services.InitSubscriptions(ctx, []requests.SubMethod{requests.Methods.ETHNewHeads}) - }) - t.Run("PingErigonRpc", func(t *testing.T) { - require.NoError(t, admin.PingErigonRpc(ctx)) - }) - t.Run("CheckTxPoolContent", func(t *testing.T) { - transactions.CheckTxPoolContent(ctx, 0, 0, 0) - }) - t.Run("SendTxWithDynamicFee", func(t *testing.T) { - const recipientAddress = "0x71562b71999873DB5b286dF957af199Ec94617F7" - const sendValue uint64 = 10000 - _, err := transactions.SendTxWithDynamicFee(ctx, recipientAddress, accounts.DevAddress, sendValue) - require.NoError(t, err) - }) - t.Run("AwaitBlocks", func(t *testing.T) { - require.NoError(t, transactions.AwaitBlocks(ctx, 2*time.Second)) - }) -} - -func TestDynamicTxNode0(t *testing.T) { - t.Skip() - - runCtx, err := ContextStart(t, "") - require.NoError(t, err) - testDynamicTx(t, runCtx.WithCurrentNetwork(0).WithCurrentNode(0)) -} - -func TestDynamicTxAnyNode(t *testing.T) { - t.Skip() - - runCtx, err := ContextStart(t, "") - require.NoError(t, err) - testDynamicTx(t, runCtx.WithCurrentNetwork(0)) -} - -func TestCallContract(t *testing.T) { - t.Skip() - - runCtx, err := ContextStart(t, "") - require.NoError(t, err) - ctx := runCtx.WithCurrentNetwork(0) - - t.Run("InitSubscriptions", func(t *testing.T) { - services.InitSubscriptions(ctx, []requests.SubMethod{requests.Methods.ETHNewHeads}) - }) - t.Run("DeployAndCallLogSubscriber", func(t *testing.T) { - _, err := contracts_steps.DeployAndCallLogSubscriber(ctx, accounts.DevAddress) - require.NoError(t, err) - }) -} diff --git a/cmd/devnet/transactions/block.go b/cmd/devnet/transactions/block.go deleted file mode 100644 index a3010d1c90b..00000000000 --- a/cmd/devnet/transactions/block.go +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package transactions - -import ( - "context" - "errors" - "fmt" - "time" - - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon-lib/common/hexutil" - - "github.com/erigontech/erigon-lib/log/v3" - - "github.com/erigontech/erigon/cmd/devnet/devnet" - "github.com/erigontech/erigon/cmd/devnet/devnetutils" - "github.com/erigontech/erigon/cmd/devnet/services" - "github.com/erigontech/erigon/rpc" - "github.com/erigontech/erigon/rpc/requests" -) - -// max number of blocks to look for a transaction in -const defaultMaxNumberOfEmptyBlockChecks = 25 - -func AwaitTransactions(ctx context.Context, hashes ...common.Hash) (map[common.Hash]uint64, error) { - devnet.Logger(ctx).Info("Awaiting transactions in confirmed blocks...") - - hashmap := map[common.Hash]bool{} - - for _, hash := range hashes { - hashmap[hash] = true - } - - maxNumberOfEmptyBlockChecks := defaultMaxNumberOfEmptyBlockChecks - network := devnet.CurrentNetwork(ctx) - if (network != nil) && (network.MaxNumberOfEmptyBlockChecks > 0) { - maxNumberOfEmptyBlockChecks = network.MaxNumberOfEmptyBlockChecks - } - - m, err := searchBlockForHashes(ctx, hashmap, maxNumberOfEmptyBlockChecks) - if err != nil { - return nil, fmt.Errorf("failed to search reserves for hashes: %v", err) - } - - return m, nil -} - -func searchBlockForHashes( - ctx context.Context, - hashmap map[common.Hash]bool, - maxNumberOfEmptyBlockChecks int, -) (map[common.Hash]uint64, error) { - logger := devnet.Logger(ctx) - - if len(hashmap) == 0 { - return nil, errors.New("no hashes to search for") - } - - txToBlock := make(map[common.Hash]uint64, len(hashmap)) - - headsSub := services.GetSubscription(devnet.CurrentChainName(ctx), requests.Methods.ETHNewHeads) - - // get a block from the new heads channel - if headsSub == nil { - return nil, errors.New("no block heads subscription") - } - - var blockCount int - for { - block := <-headsSub.SubChan - blockNum := block.(map[string]interface{})["number"].(string) - - _, numFound, foundErr := txHashInBlock(headsSub.Client, hashmap, blockNum, txToBlock, logger) - - if foundErr != nil { - return nil, fmt.Errorf("failed to find hash in block with number %q: %v", foundErr, blockNum) - } - - if len(hashmap) == 0 { // this means we have found all the txs we're looking for - logger.Info("All the transactions created have been included in blocks") - return txToBlock, nil - } - - if numFound == 0 { - blockCount++ // increment the number of blocks seen to check against the max number of blocks to iterate over - } - - if blockCount == maxNumberOfEmptyBlockChecks { - for h := range hashmap { - logger.Error("Missing Tx", "txHash", h) - } - - return nil, errors.New("timeout when searching for tx") - } - } -} - -// Block represents a simple block for queries -type Block struct { - Number *hexutil.Big - Transactions []common.Hash - BlockHash common.Hash -} - -// txHashInBlock checks if the block with block number has the transaction hash in its list of transactions -func txHashInBlock(client *rpc.Client, hashmap map[common.Hash]bool, blockNumber string, txToBlockMap map[common.Hash]uint64, logger log.Logger) (uint64, int, error) { - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() // releases the resources held by the context - - var ( - currBlock Block - numFound int - ) - err := client.CallContext(ctx, &currBlock, string(requests.Methods.ETHGetBlockByNumber), blockNumber, false) - if err != nil { - return uint64(0), 0, fmt.Errorf("failed to get block by number: %v", err) - } - - for _, txnHash := range currBlock.Transactions { - // check if txn is in the hash set and remove it from the set if it is present - if _, ok := hashmap[txnHash]; ok { - numFound++ - logger.Info("SUCCESS => Txn included into block", "txHash", txnHash, "blockNum", blockNumber) - // add the block number as an entry to the map - txToBlockMap[txnHash] = devnetutils.HexToInt(blockNumber) - delete(hashmap, txnHash) - if len(hashmap) == 0 { - return devnetutils.HexToInt(blockNumber), numFound, nil - } - } - } - - return uint64(0), 0, nil -} diff --git a/cmd/devnet/transactions/tx.go b/cmd/devnet/transactions/tx.go deleted file mode 100644 index 20b710f58a6..00000000000 --- a/cmd/devnet/transactions/tx.go +++ /dev/null @@ -1,457 +0,0 @@ -// Copyright 2024 The Erigon Authors -// This file is part of Erigon. -// -// Erigon is free software: you can redistribute it and/or modify -// it under the terms of the GNU Lesser General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. -// -// Erigon is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Lesser General Public License for more details. -// -// You should have received a copy of the GNU Lesser General Public License -// along with Erigon. If not, see . - -package transactions - -import ( - "context" - "fmt" - "strings" - "time" - - "github.com/holiman/uint256" - - "github.com/erigontech/erigon-lib/common" - "github.com/erigontech/erigon-lib/log/v3" - "github.com/erigontech/erigon/cmd/devnet/accounts" - "github.com/erigontech/erigon/cmd/devnet/blocks" - "github.com/erigontech/erigon/cmd/devnet/devnet" - "github.com/erigontech/erigon/cmd/devnet/devnetutils" - "github.com/erigontech/erigon/cmd/devnet/scenarios" - "github.com/erigontech/erigon/execution/chain/params" - "github.com/erigontech/erigon/execution/types" - "github.com/erigontech/erigon/rpc" -) - -func init() { - scenarios.MustRegisterStepHandlers( - scenarios.StepHandler(CheckTxPoolContent), - scenarios.StepHandler(SendTxWithDynamicFee), - scenarios.StepHandler(AwaitBlocks), - scenarios.StepHandler(SendTxLoad), - ) -} - -func CheckTxPoolContent(ctx context.Context, expectedPendingSize, expectedQueuedSize, expectedBaseFeeSize int) { - pendingSize, queuedSize, baseFeeSize, err := devnet.SelectNode(ctx).TxpoolContent() - - logger := devnet.Logger(ctx) - - if err != nil { - logger.Error("FAILURE getting txpool content", "error", err) - return - } - - if expectedPendingSize >= 0 && pendingSize != expectedPendingSize { - logger.Debug("FAILURE mismatched pending subpool size", "expected", expectedPendingSize, "got", pendingSize) - return - } - - if expectedQueuedSize >= 0 && queuedSize != expectedQueuedSize { - logger.Error("FAILURE mismatched queued subpool size", "expected", expectedQueuedSize, "got", queuedSize) - return - } - - if expectedBaseFeeSize >= 0 && baseFeeSize != expectedBaseFeeSize { - logger.Debug("FAILURE mismatched basefee subpool size", "expected", expectedBaseFeeSize, "got", baseFeeSize) - } - - logger.Info("Subpool sizes", "pending", pendingSize, "queued", queuedSize, "basefee", baseFeeSize) -} - -func Transfer(ctx context.Context, toAddr, fromAddr string, value uint64, wait bool) (common.Hash, error) { - logger := devnet.Logger(ctx) - - node := devnet.SelectNode(ctx) - - // create a non-contract transaction and sign it - signedTx, _, err := CreateTransaction(node, toAddr, fromAddr, value) - - if err != nil { - logger.Error("failed to create a transaction", "error", err) - return common.Hash{}, err - } - - logger.Info("Sending tx", "value", value, "to", toAddr, "from", fromAddr, "tx", signedTx.Hash()) - - // send the signed transaction - hash, err := node.SendTransaction(signedTx) - - if err != nil { - logger.Error("failed to send transaction", "error", err) - return common.Hash{}, err - } - - if wait { - if _, err = AwaitTransactions(ctx, hash); err != nil { - return common.Hash{}, fmt.Errorf("failed to call contract tx: %v", err) - } - } - - return hash, nil -} - -func SendTxWithDynamicFee(ctx context.Context, to, from string, amount uint64) ([]common.Hash, error) { - // get the latest nonce for the next transaction - logger := devnet.Logger(ctx) - - lowerThanBaseFeeTxs, higherThanBaseFeeTxs, err := CreateManyEIP1559TransactionsRefWithBaseFee2(ctx, to, from, 200) - if err != nil { - logger.Error("failed CreateManyEIP1559TransactionsRefWithBaseFee", "error", err) - return nil, err - } - - higherThanBaseFeeHashlist, err := SendManyTransactions(ctx, higherThanBaseFeeTxs) - if err != nil { - logger.Error("failed SendManyTransactions(higherThanBaseFeeTxs)", "error", err) - return nil, err - } - - lowerThanBaseFeeHashlist, err := SendManyTransactions(ctx, lowerThanBaseFeeTxs) - - if err != nil { - logger.Error("failed SendManyTransactions(lowerThanBaseFeeTxs)", "error", err) - return nil, err - } - - CheckTxPoolContent(ctx, len(higherThanBaseFeeHashlist), 0, len(lowerThanBaseFeeHashlist)) - - CheckTxPoolContent(ctx, -1, -1, -1) - - if _, err = AwaitTransactions(ctx, higherThanBaseFeeHashlist...); err != nil { - return nil, fmt.Errorf("failed to call contract tx: %v", err) - } - - logger.Info("SUCCESS: All transactions in pending pool included in blocks") - - return append(lowerThanBaseFeeHashlist, higherThanBaseFeeHashlist...), nil -} - -func SendTxLoad(ctx context.Context, to, from string, amount uint64, txPerSec uint) error { - logger := devnet.Logger(ctx) - - batchCount := txPerSec / 4 - - if batchCount < 1 { - batchCount = 1 - } - - ms250 := 250 * time.Millisecond - - for { - start := time.Now() - - tx, err := CreateManyEIP1559TransactionsHigherThanBaseFee(ctx, to, from, int(batchCount)) - - if err != nil { - logger.Error("failed Create Txns", "error", err) - return err - } - - _, err = SendManyTransactions(ctx, tx) - - if err != nil { - logger.Error("failed SendManyTransactions(higherThanBaseFeeTxs)", "error", err) - return err - } - - select { - case <-ctx.Done(): - return nil - default: - } - - duration := time.Since(start) - - if duration < ms250 { - time.Sleep(ms250 - duration) - } - } -} - -func AwaitBlocks(ctx context.Context, sleepTime time.Duration) error { - logger := devnet.Logger(ctx) - - for i := 1; i <= 20; i++ { - node := devnet.SelectNode(ctx) - - blockNumber, err := node.BlockNumber() - - if err != nil { - logger.Error("FAILURE => error getting block number", "error", err) - } else { - logger.Info("Got block number", "blockNum", blockNumber) - } - - pendingSize, queuedSize, baseFeeSize, err := node.TxpoolContent() - - if err != nil { - logger.Error("FAILURE getting txpool content", "error", err) - } else { - logger.Info("Txpool subpool sizes", "pending", pendingSize, "queued", queuedSize, "basefee", baseFeeSize) - } - - time.Sleep(sleepTime) - } - - return nil -} - -const gasPrice = 912_345_678 - -func CreateManyEIP1559TransactionsRefWithBaseFee(ctx context.Context, to, from string, logger log.Logger) ([]types.Transaction, []types.Transaction, error) { - toAddress := common.HexToAddress(to) - fromAddress := common.HexToAddress(from) - - baseFeePerGas, err := blocks.BaseFeeFromBlock(ctx) - - if err != nil { - return nil, nil, fmt.Errorf("failed BaseFeeFromBlock: %v", err) - } - - devnet.Logger(ctx).Info("BaseFeePerGas", "val", baseFeePerGas) - - lowerBaseFeeTransactions, higherBaseFeeTransactions, err := signEIP1559TxsLowerAndHigherThanBaseFee2(ctx, 1, 1, baseFeePerGas, toAddress, fromAddress) - - if err != nil { - return nil, nil, fmt.Errorf("failed signEIP1559TxsLowerAndHigherThanBaseFee2: %v", err) - } - - return lowerBaseFeeTransactions, higherBaseFeeTransactions, nil -} - -func CreateManyEIP1559TransactionsRefWithBaseFee2(ctx context.Context, to, from string, count int) ([]types.Transaction, []types.Transaction, error) { - toAddress := common.HexToAddress(to) - fromAddress := common.HexToAddress(from) - - baseFeePerGas, err := blocks.BaseFeeFromBlock(ctx) - if err != nil { - return nil, nil, fmt.Errorf("failed BaseFeeFromBlock: %v", err) - } - - devnet.Logger(ctx).Info("BaseFeePerGas2", "val", baseFeePerGas) - - lower := count - devnetutils.RandomInt(count) - higher := count - lower - - lowerBaseFeeTransactions, higherBaseFeeTransactions, err := signEIP1559TxsLowerAndHigherThanBaseFee2(ctx, lower, higher, baseFeePerGas, toAddress, fromAddress) - - if err != nil { - return nil, nil, fmt.Errorf("failed signEIP1559TxsLowerAndHigherThanBaseFee2: %v", err) - } - - return lowerBaseFeeTransactions, higherBaseFeeTransactions, nil -} - -func CreateManyEIP1559TransactionsHigherThanBaseFee(ctx context.Context, to, from string, count int) ([]types.Transaction, error) { - toAddress := common.HexToAddress(to) - fromAddress := common.HexToAddress(from) - - baseFeePerGas, err := blocks.BaseFeeFromBlock(ctx) - - if err != nil { - return nil, fmt.Errorf("failed BaseFeeFromBlock: %v", err) - } - - baseFeePerGas = baseFeePerGas * 2 - - devnet.Logger(ctx).Info("BaseFeePerGas2", "val", baseFeePerGas) - - node := devnet.SelectNode(ctx) - - res, err := node.GetTransactionCount(fromAddress, rpc.PendingBlock) - - if err != nil { - return nil, fmt.Errorf("failed to get transaction count for address 0x%x: %v", fromAddress, err) - } - - nonce := res.Uint64() - - return signEIP1559TxsHigherThanBaseFee(ctx, count, baseFeePerGas, &nonce, toAddress, fromAddress) -} - -// createNonContractTx returns a signed transaction and the recipient address -func CreateTransaction(node devnet.Node, to, from string, value uint64) (types.Transaction, common.Address, error) { - toAccount := accounts.GetAccount(to) - - var toAddress common.Address - - if toAccount == nil { - if strings.HasPrefix(to, "0x") { - toAddress = common.HexToAddress(from) - } else { - return nil, common.Address{}, fmt.Errorf("unknown to account: %s", to) - } - } else { - toAddress = toAccount.Address - } - - fromAccount := accounts.GetAccount(from) - - if fromAccount == nil { - return nil, common.Address{}, fmt.Errorf("unknown from account: %s", from) - } - - res, err := node.GetTransactionCount(fromAccount.Address, rpc.PendingBlock) - - if err != nil { - return nil, common.Address{}, fmt.Errorf("failed to get transaction count for address 0x%x: %v", fromAccount.Address, err) - } - - // create a new transaction using the parameters to send - transaction := types.NewTransaction(res.Uint64(), toAddress, uint256.NewInt(value), params.TxGas, uint256.NewInt(gasPrice), nil) - - // sign the transaction using the developer 0signed private key - signedTx, err := types.SignTx(transaction, *types.LatestSignerForChainID(node.ChainID()), fromAccount.SigKey()) - - if err != nil { - return nil, common.Address{}, fmt.Errorf("failed to sign non-contract transaction: %v", err) - } - - return signedTx, toAddress, nil -} - -func signEIP1559TxsLowerAndHigherThanBaseFee2(ctx context.Context, amountLower, amountHigher int, baseFeePerGas uint64, toAddress common.Address, fromAddress common.Address) ([]types.Transaction, []types.Transaction, error) { - node := devnet.SelectNode(ctx) - - res, err := node.GetTransactionCount(fromAddress, rpc.PendingBlock) - - if err != nil { - return nil, nil, fmt.Errorf("failed to get transaction count for address 0x%x: %v", fromAddress, err) - } - - nonce := res.Uint64() - - higherBaseFeeTransactions, err := signEIP1559TxsHigherThanBaseFee(ctx, amountHigher, baseFeePerGas, &nonce, toAddress, fromAddress) - - if err != nil { - return nil, nil, fmt.Errorf("failed signEIP1559TxsHigherThanBaseFee: %v", err) - } - - lowerBaseFeeTransactions, err := signEIP1559TxsLowerThanBaseFee(ctx, amountLower, baseFeePerGas, &nonce, toAddress, fromAddress) - - if err != nil { - return nil, nil, fmt.Errorf("failed signEIP1559TxsLowerThanBaseFee: %v", err) - } - - return lowerBaseFeeTransactions, higherBaseFeeTransactions, nil -} - -// signEIP1559TxsLowerThanBaseFee creates n number of transactions with gasFeeCap lower than baseFeePerGas -func signEIP1559TxsLowerThanBaseFee(ctx context.Context, n int, baseFeePerGas uint64, nonce *uint64, toAddress, fromAddress common.Address) ([]types.Transaction, error) { - var signedTransactions []types.Transaction - - var ( - minFeeCap = baseFeePerGas - 300_000_000 - maxFeeCap = (baseFeePerGas - 100_000_000) + 1 // we want the value to be inclusive in the random number generation, hence the addition of 1 - ) - - node := devnet.SelectNode(ctx) - signer := *types.LatestSignerForChainID(node.ChainID()) - chainId := *uint256.NewInt(node.ChainID().Uint64()) - - for i := 0; i < n; i++ { - gasFeeCap, err := devnetutils.RandomNumberInRange(minFeeCap, maxFeeCap) - - if err != nil { - return nil, err - } - - value, err := devnetutils.RandomNumberInRange(0, 100_000) - - if err != nil { - return nil, err - } - - transaction := types.NewEIP1559Transaction(chainId, *nonce, toAddress, uint256.NewInt(value), uint64(210_000), uint256.NewInt(gasPrice), new(uint256.Int), uint256.NewInt(gasFeeCap), nil) - - devnet.Logger(ctx).Trace("LOWER", "transaction", i, "nonce", transaction.Nonce, "value", transaction.Value, "feecap", transaction.FeeCap) - - signedTransaction, err := types.SignTx(transaction, signer, accounts.SigKey(fromAddress)) - - if err != nil { - return nil, err - } - - signedTransactions = append(signedTransactions, signedTransaction) - *nonce++ - } - - return signedTransactions, nil -} - -// signEIP1559TxsHigherThanBaseFee creates amount number of transactions with gasFeeCap higher than baseFeePerGas -func signEIP1559TxsHigherThanBaseFee(ctx context.Context, n int, baseFeePerGas uint64, nonce *uint64, toAddress, fromAddress common.Address) ([]types.Transaction, error) { - var signedTransactions []types.Transaction - - var ( - minFeeCap = baseFeePerGas - maxFeeCap = (baseFeePerGas + 100_000_000) + 1 // we want the value to be inclusive in the random number generation, hence the addition of 1 - ) - - node := devnet.SelectNode(ctx) - signer := *types.LatestSignerForChainID(node.ChainID()) - chainId := *uint256.NewInt(node.ChainID().Uint64()) - - for i := 0; i < n; i++ { - gasFeeCap, err := devnetutils.RandomNumberInRange(minFeeCap, maxFeeCap) - if err != nil { - return nil, err - } - - value, err := devnetutils.RandomNumberInRange(0, 100_000) - if err != nil { - return nil, err - } - - transaction := types.NewEIP1559Transaction(chainId, *nonce, toAddress, uint256.NewInt(value), uint64(210_000), uint256.NewInt(gasPrice), new(uint256.Int), uint256.NewInt(gasFeeCap), nil) - - devnet.Logger(ctx).Trace("HIGHER", "transaction", i, "nonce", transaction.Nonce, "value", transaction.Value, "feecap", transaction.FeeCap) - - signerKey := accounts.SigKey(fromAddress) - if signerKey == nil { - return nil, fmt.Errorf("devnet.signEIP1559TxsHigherThanBaseFee failed to SignTx: private key not found for address %s", fromAddress) - } - - signedTransaction, err := types.SignTx(transaction, signer, signerKey) - if err != nil { - return nil, err - } - - signedTransactions = append(signedTransactions, signedTransaction) - *nonce++ - } - - return signedTransactions, nil -} - -func SendManyTransactions(ctx context.Context, signedTransactions []types.Transaction) ([]common.Hash, error) { - logger := devnet.Logger(ctx) - - logger.Info(fmt.Sprintf("Sending %d transactions to the txpool...", len(signedTransactions))) - hashes := make([]common.Hash, len(signedTransactions)) - - for idx, txn := range signedTransactions { - hash, err := devnet.SelectNode(ctx).SendTransaction(txn) - if err != nil { - logger.Error("failed SendTransaction", "error", err) - return nil, err - } - hashes[idx] = hash - } - - return hashes, nil -} diff --git a/debug.Dockerfile b/debug.Dockerfile index 8e25a0803cc..ba5002bd63b 100644 --- a/debug.Dockerfile +++ b/debug.Dockerfile @@ -47,7 +47,6 @@ RUN mkdir -p ~/.local/share/erigon # copy compiled artifacts from builder ## then give each binary its own layer -COPY --from=builder /app/build/bin/devnet /usr/local/bin/devnet COPY --from=builder /app/build/bin/downloader /usr/local/bin/downloader COPY --from=builder /app/build/bin/erigon /usr/local/bin/erigon COPY --from=builder /app/build/bin/erigon-cl /usr/local/bin/erigon-cl diff --git a/rpc/requests/request_generator.go b/rpc/requests/request_generator.go index f5c793520b0..e289d831fbb 100644 --- a/rpc/requests/request_generator.go +++ b/rpc/requests/request_generator.go @@ -35,7 +35,6 @@ import ( "github.com/erigontech/erigon-lib/common" "github.com/erigontech/erigon-lib/common/hexutil" "github.com/erigontech/erigon-lib/log/v3" - "github.com/erigontech/erigon/cmd/devnet/devnetutils" "github.com/erigontech/erigon/execution/types" "github.com/erigontech/erigon/p2p" "github.com/erigontech/erigon/rpc" @@ -391,7 +390,7 @@ func (req *requestGenerator) Subscribe(ctx context.Context, method SubMethod, su } } - namespace, subMethod, err := devnetutils.NamespaceAndSubMethodFromMethod(string(method)) + namespace, subMethod, err := NamespaceAndSubMethodFromMethod(string(method)) if err != nil { return nil, fmt.Errorf("cannot get namespace and submethod from method: %v", err) @@ -411,3 +410,12 @@ func (req *requestGenerator) UnsubscribeAll() { req.subscriptionClient = nil subscriptionClient.Close() } + +// NamespaceAndSubMethodFromMethod splits a parent method into namespace and the actual method +func NamespaceAndSubMethodFromMethod(method string) (string, string, error) { + parts := strings.SplitN(method, "_", 2) + if len(parts) != 2 { + return "", "", errors.New("invalid string to split") + } + return parts[0], parts[1], nil +} diff --git a/wmake.ps1 b/wmake.ps1 index 03d5431b334..ffa8a07e4cf 100644 --- a/wmake.ps1 +++ b/wmake.ps1 @@ -23,7 +23,6 @@ Param( [ValidateSet( "clean", "db-tools", - "devnet", "downloader", "erigon", "evm", @@ -71,7 +70,6 @@ if ($BuildTargets.Count -gt 1) { if ($BuildTargets[0] -eq "all") { $BuildTargets = @( - "devnet", "downloader", "erigon", "evm",