Skip to content
This repository has been archived by the owner on Jun 20, 2024. It is now read-only.

Commit

Permalink
feat: node instantiation
Browse files Browse the repository at this point in the history
  • Loading branch information
aloknerurkar authored Sep 29, 2023
2 parents 817b096 + e2d83ce commit 658475d
Show file tree
Hide file tree
Showing 22 changed files with 1,410 additions and 30 deletions.
222 changes: 222 additions & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
package main

import (
"fmt"
"io"
"log/slog"
"os"
"time"

"github.com/ethereum/go-ethereum/crypto"
"github.com/primevprotocol/mev-commit/pkg/node"
"github.com/urfave/cli/v2"
"gopkg.in/yaml.v2"
)

const (
defaultP2PPort = 13522
defaultHTTPPort = 13523
)

var (
optionConfig = &cli.StringFlag{
Name: "config",
Usage: "path to config file",
Required: true,
EnvVars: []string{"MEV_COMMIT_CONFIG"},
}
)

func main() {
app := &cli.App{
Name: "mev-commit",
Usage: "Entry point for mev-commit",
Commands: []*cli.Command{
{
Name: "start",
Usage: "Start mev-commit",
Flags: []cli.Flag{
optionConfig,
},
Action: func(c *cli.Context) error {
return start(c)
},
},
{
Name: "create-key",
Action: func(c *cli.Context) error {
return createKey(c)
},
},
}}

if err := app.Run(os.Args); err != nil {
fmt.Fprintf(app.Writer, "exited with error: %v\n", err)
}
}

func createKey(c *cli.Context) error {
privKey, err := crypto.GenerateKey()
if err != nil {
return err
}

if len(c.Args().Slice()) != 1 {
return fmt.Errorf("usage: mev-commit create-key <output_file>")
}

outputFile := c.Args().Slice()[0]

f, err := os.Create(outputFile)
if err != nil {
return err
}

defer f.Close()

if err := crypto.SaveECDSA(outputFile, privKey); err != nil {
return err
}

fmt.Fprintf(c.App.Writer, "Private key saved to file: %s\n", outputFile)
return nil
}

type config struct {
PrivKeyFile string `yaml:"priv_key_file" json:"priv_key_file"`
Secret string `yaml:"secret" json:"secret"`
PeerType string `yaml:"peer_type" json:"peer_type"`
P2PPort int `yaml:"p2p_port" json:"p2p_port"`
HTTPPort int `yaml:"http_port" json:"http_port"`
LogFmt string `yaml:"log_fmt" json:"log_fmt"`
LogLevel string `yaml:"log_level" json:"log_level"`
Bootnodes []string `yaml:"bootnodes" json:"bootnodes"`
}

func checkConfig(cfg *config) error {
if cfg.PrivKeyFile == "" {
return fmt.Errorf("priv_key_file is required")
}

if cfg.Secret == "" {
return fmt.Errorf("secret is required")
}

if cfg.PeerType == "" {
return fmt.Errorf("peer_type is required")
}

if cfg.P2PPort == 0 {
cfg.P2PPort = defaultP2PPort
}

if cfg.HTTPPort == 0 {
cfg.HTTPPort = defaultHTTPPort
}

if cfg.LogFmt == "" {
cfg.LogFmt = "text"
}

if cfg.LogLevel == "" {
cfg.LogLevel = "info"
}

return nil
}

func start(c *cli.Context) error {
configFile := c.String(optionConfig.Name)
fmt.Fprintf(c.App.Writer, "starting mev-commit with config file: %s\n", configFile)

var cfg config
buf, err := os.ReadFile(configFile)
if err != nil {
return fmt.Errorf("failed to read config file at '%s': %w", configFile, err)
}

if err := yaml.Unmarshal(buf, &cfg); err != nil {
return fmt.Errorf("failed to unmarshal config file at '%s': %w", configFile, err)
}

if err := checkConfig(&cfg); err != nil {
return fmt.Errorf("invalid config file at '%s': %w", configFile, err)
}

logger, err := newLogger(cfg.LogLevel, cfg.LogFmt, c.App.Writer)
if err != nil {
return fmt.Errorf("failed to create logger: %w", err)
}

privKey, err := crypto.LoadECDSA(cfg.PrivKeyFile)
if err != nil {
return fmt.Errorf("failed to load private key from file '%s': %w", cfg.PrivKeyFile, err)
}

nd, err := node.NewNode(&node.Options{
PrivKey: privKey,
Secret: cfg.Secret,
PeerType: cfg.PeerType,
P2PPort: cfg.P2PPort,
HTTPPort: cfg.HTTPPort,
Logger: logger,
Bootnodes: cfg.Bootnodes,
})
if err != nil {
return fmt.Errorf("failed starting node: %w", err)
}

<-c.Done()
fmt.Fprintf(c.App.Writer, "shutting down...\n")
closed := make(chan struct{})

go func() {
defer close(closed)

err := nd.Close()
if err != nil {
logger.Error("failed to close node", "error", err)
}
}()

select {
case <-closed:
case <-time.After(5 * time.Second):
logger.Error("failed to close node in time")
}

return nil
}

func newLogger(lvl, logFmt string, sink io.Writer) (*slog.Logger, error) {
var (
level = new(slog.LevelVar) // Info by default
handler slog.Handler
)

switch lvl {
case "debug":
level.Set(slog.LevelDebug)
case "info":
level.Set(slog.LevelInfo)
case "warn":
level.Set(slog.LevelWarn)
case "error":
level.Set(slog.LevelError)
default:
return nil, fmt.Errorf("invalid log level: %s", lvl)
}

switch logFmt {
case "text":
handler = slog.NewTextHandler(sink, &slog.HandlerOptions{Level: level})
case "none":
fallthrough
case "json":
handler = slog.NewJSONHandler(sink, &slog.HandlerOptions{Level: level})
default:
return nil, fmt.Errorf("invalid log format: %s", logFmt)
}

return slog.New(handler), nil
}
5 changes: 5 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ require (
github.com/libp2p/go-libp2p v0.31.0
github.com/libp2p/go-msgio v0.3.0
github.com/prometheus/client_golang v1.16.0
github.com/urfave/cli/v2 v2.25.7
github.com/vmihailenco/msgpack/v5 v5.3.5
golang.org/x/crypto v0.12.0
golang.org/x/sync v0.3.0
gopkg.in/yaml.v2 v2.4.0
)

require (
Expand All @@ -20,6 +22,7 @@ require (
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/containerd/cgroups v1.1.0 // indirect
github.com/coreos/go-systemd/v22 v22.5.0 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect
github.com/davidlazar/go-crypto v0.0.0-20200604182044-b73af7476f6c // indirect
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.2.0 // indirect
github.com/docker/go-units v0.5.0 // indirect
Expand Down Expand Up @@ -81,8 +84,10 @@ require (
github.com/quic-go/quic-go v0.38.1 // indirect
github.com/quic-go/webtransport-go v0.5.3 // indirect
github.com/raulk/go-watchdog v1.3.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/spaolacci/murmur3 v1.1.0 // indirect
github.com/vmihailenco/tagparser/v2 v2.0.0 // indirect
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect
go.uber.org/dig v1.17.0 // indirect
go.uber.org/fx v1.20.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
Expand Down
10 changes: 10 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ github.com/coreos/go-systemd/v22 v22.5.0 h1:RrqgGjYQKalulkV8NGVIfkXQf6YYmOyiJKk8
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v0.0.0-20171005155431-ecdeabc65495/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
Expand Down Expand Up @@ -282,6 +284,8 @@ github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBO
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
github.com/shurcooL/component v0.0.0-20170202220835-f88ec8f54cc4/go.mod h1:XhFIlyj5a1fBNx5aJTbKoIq0mNaPvOagO+HjB3EtxrY=
github.com/shurcooL/events v0.0.0-20181021180414-410e4ca65f48/go.mod h1:5u70Mqkb5O5cxEA8nxTsgrgLehJeAw6Oc4Ab1c/P1HM=
Expand Down Expand Up @@ -321,12 +325,16 @@ github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcU
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA=
github.com/urfave/cli v1.22.2/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
github.com/urfave/cli/v2 v2.25.7 h1:VAzn5oq403l5pHjc4OhD54+XGO9cdKVL/7lDjF+iKUs=
github.com/urfave/cli/v2 v2.25.7/go.mod h1:8qnjx1vcq5s2/wpsqoZFndg2CE5tNFyrTvS6SinrnYQ=
github.com/viant/assertly v0.4.8/go.mod h1:aGifi++jvCrUaklKEKT0BU95igDNaqkvz+49uaYMPRU=
github.com/viant/toolbox v0.24.0/go.mod h1:OxMCG57V0PXuIP2HNQrtJf2CjqdmbrOx5EkMILuUhzM=
github.com/vmihailenco/msgpack/v5 v5.3.5 h1:5gO0H1iULLWGhs2H5tbAHIZTV8/cYafcFOr9znI5mJU=
github.com/vmihailenco/msgpack/v5 v5.3.5/go.mod h1:7xyJ9e+0+9SaZT0Wt1RGleJXzli6Q/V5KbhBonMG9jc=
github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g=
github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds=
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU=
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
Expand Down Expand Up @@ -487,6 +495,8 @@ gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWD
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
Expand Down
Loading

0 comments on commit 658475d

Please sign in to comment.