From d4c7873c9f2a9135d4fc186d7f1b1fa8e044bbc3 Mon Sep 17 00:00:00 2001 From: cairo <101215230+cairoeth@users.noreply.github.com> Date: Sun, 24 Mar 2024 00:15:08 -0500 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=A8=20fix=20lints=20from=20staticcheck?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Makefile | 2 +- preconf-operator/cmd/operator/main.go | 4 +- preconf-operator/core/chainio/avs_reader.go | 9 +- preconf-operator/core/chainio/avs_writer.go | 3 +- preconf-operator/core/config/config.go | 33 +++---- preconf-operator/core/utils.go | 1 - preconf-operator/operator.go | 96 ++++++++++----------- preconf-operator/receiverapi/receiverapi.go | 21 ++--- preconf-operator/registration.go | 4 +- preconf-operator/rpc_client.go | 20 ++--- preconf-operator/sse/client_rpc.go | 17 ++-- preconf-operator/types/avs_config.go | 11 +-- preconf-share/preconshare/api.go | 15 +--- preconf-share/preconshare/backend.go | 3 +- preconf-share/preconshare/database.go | 11 +-- preconf-share/preconshare/hints.go | 12 --- preconf-share/preconshare/sim_queue.go | 5 -- preconf-share/preconshare/utils.go | 30 ------- rpc/adapters/webfile/fetcher.go | 3 +- rpc/application/builder_info.go | 8 +- rpc/cmd/server/main.go | 27 +----- rpc/database/mem_store.go | 2 +- rpc/database/types.go | 3 +- rpc/server/configuration.go | 2 +- rpc/server/ofacblacklist.go | 2 +- rpc/server/redisstate.go | 12 +-- rpc/server/request_handler.go | 4 +- rpc/server/request_intercepts.go | 4 +- rpc/server/request_processor.go | 84 +----------------- rpc/server/request_record.go | 2 +- rpc/server/request_record_test.go | 16 ++-- rpc/server/server.go | 4 +- rpc/server/url_params.go | 4 +- rpc/server/url_params_test.go | 2 +- rpc/server/util.go | 4 +- rpc/server/whitelist.go | 2 +- rpc/tests/e2e_test.go | 14 +-- rpc/testutils/mock_rpcbackend.go | 5 +- rpc/testutils/rpctesthelpers.go | 3 - rpc/testutils/transactions.go | 6 +- rpc/types/types.go | 3 +- tests/utils.go | 3 +- 42 files changed, 168 insertions(+), 348 deletions(-) delete mode 100644 preconf-operator/core/utils.go diff --git a/Makefile b/Makefile index 9b438a8..9f4f976 100644 --- a/Makefile +++ b/Makefile @@ -55,7 +55,7 @@ lint: gofmt -d -s . gofumpt -d -extra . go vet ./... - staticcheck ./... + go list ./... | grep -F -e contracts/ -v | xargs staticcheck golangci-lint run fmt: diff --git a/preconf-operator/cmd/operator/main.go b/preconf-operator/cmd/operator/main.go index 17ac959..7f566a6 100644 --- a/preconf-operator/cmd/operator/main.go +++ b/preconf-operator/cmd/operator/main.go @@ -29,8 +29,8 @@ func main() { } } -func operatorMain(ctx_cli *cli.Context) error { - configPath := ctx_cli.GlobalString(config.ConfigFileFlag.Name) +func operatorMain(ctxCli *cli.Context) error { + configPath := ctxCli.GlobalString(config.ConfigFileFlag.Name) nodeConfig := types.NodeConfig{} err := sdkutils.ReadYamlConfig(configPath, &nodeConfig) if err != nil { diff --git a/preconf-operator/core/chainio/avs_reader.go b/preconf-operator/core/chainio/avs_reader.go index 9bfb4a7..94889ab 100644 --- a/preconf-operator/core/chainio/avs_reader.go +++ b/preconf-operator/core/chainio/avs_reader.go @@ -1,3 +1,4 @@ +// Package chainio contains the logic to interact with the AVS contracts onchain. package chainio import ( @@ -28,15 +29,15 @@ type AvsReader struct { var _ AvsReaderer = (*AvsReader)(nil) func BuildAvsReaderFromConfig(c *config.Config) (*AvsReader, error) { - return BuildAvsReader(c.IncredibleSquaringRegistryCoordinatorAddr, c.OperatorStateRetrieverAddr, c.EthHttpClient, c.Logger) + return BuildAvsReader(c.IncredibleSquaringRegistryCoordinatorAddr, c.OperatorStateRetrieverAddr, c.EthHTTPClient, c.Logger) } -func BuildAvsReader(registryCoordinatorAddr, operatorStateRetrieverAddr gethcommon.Address, ethHttpClient eth.EthClient, logger logging.Logger) (*AvsReader, error) { - avsManagersBindings, err := NewAvsManagersBindings(registryCoordinatorAddr, operatorStateRetrieverAddr, ethHttpClient, logger) +func BuildAvsReader(registryCoordinatorAddr, operatorStateRetrieverAddr gethcommon.Address, ethHTTPClient eth.EthClient, logger logging.Logger) (*AvsReader, error) { + avsManagersBindings, err := NewAvsManagersBindings(registryCoordinatorAddr, operatorStateRetrieverAddr, ethHTTPClient, logger) if err != nil { return nil, err } - avsRegistryReader, err := sdkavsregistry.BuildAvsRegistryChainReader(registryCoordinatorAddr, operatorStateRetrieverAddr, ethHttpClient, logger) + avsRegistryReader, err := sdkavsregistry.BuildAvsRegistryChainReader(registryCoordinatorAddr, operatorStateRetrieverAddr, ethHTTPClient, logger) if err != nil { return nil, err } diff --git a/preconf-operator/core/chainio/avs_writer.go b/preconf-operator/core/chainio/avs_writer.go index 7760ce2..e89d040 100644 --- a/preconf-operator/core/chainio/avs_writer.go +++ b/preconf-operator/core/chainio/avs_writer.go @@ -20,13 +20,12 @@ type AvsWriter struct { AvsContractBindings *AvsManagersBindings logger logging.Logger TxMgr txmgr.TxManager - client eth.EthClient } var _ AvsWriterer = (*AvsWriter)(nil) func BuildAvsWriterFromConfig(c *config.Config) (*AvsWriter, error) { - return BuildAvsWriter(c.TxMgr, c.IncredibleSquaringRegistryCoordinatorAddr, c.OperatorStateRetrieverAddr, c.EthHttpClient, c.Logger) + return BuildAvsWriter(c.TxMgr, c.IncredibleSquaringRegistryCoordinatorAddr, c.OperatorStateRetrieverAddr, c.EthHTTPClient, c.Logger) } func BuildAvsWriter(txMgr txmgr.TxManager, registryCoordinatorAddr, operatorStateRetrieverAddr gethcommon.Address, ethHTTPClient eth.EthClient, logger logging.Logger) (*AvsWriter, error) { diff --git a/preconf-operator/core/config/config.go b/preconf-operator/core/config/config.go index 3aa0ff5..3cdfdff 100644 --- a/preconf-operator/core/config/config.go +++ b/preconf-operator/core/config/config.go @@ -1,3 +1,4 @@ +// Package config contains the config types. package config import ( @@ -25,14 +26,14 @@ type Config struct { EcdsaPrivateKey *ecdsa.PrivateKey BlsPrivateKey *bls.PrivateKey Logger sdklogging.Logger - EigenMetricsIpPortAddress string + EigenMetricsIPPortAddress string // we need the url for the eigensdk currently... eventually standardize api so as to // only take an ethclient or an rpcUrl (and build the ethclient at each constructor site) - EthHttpRpcUrl string - EthHttpClient eth.EthClient + EthHTTPRPCURL string + EthHTTPClient eth.EthClient OperatorStateRetrieverAddr common.Address IncredibleSquaringRegistryCoordinatorAddr common.Address - AggregatorServerIpPortAddr string + AggregatorServerIPPortAddr string RegisterOperatorOnStartup bool // json:"-" skips this field when marshaling (only used for logging to stdout), since SignerFn doesnt implement marshalJson SignerFn signerv2.SignerFn `json:"-"` @@ -40,15 +41,15 @@ type Config struct { AggregatorAddress common.Address } -// These are read from ConfigFileFlag +// ConfigRaw These are read from ConfigFileFlag type ConfigRaw struct { Environment sdklogging.LogLevel `yaml:"environment"` - EthRpcUrl string `yaml:"eth_rpc_url"` - AggregatorServerIpPortAddr string `yaml:"aggregator_server_ip_port_address"` + EthRPCURL string `yaml:"eth_rpc_url"` + AggregatorServerIPPortAddr string `yaml:"aggregator_server_ip_port_address"` RegisterOperatorOnStartup bool `yaml:"register_operator_on_startup"` } -// These are read from CredibleSquaringDeploymentFileFlag +// IncredibleSquaringDeploymentRaw These are read from CredibleSquaringDeploymentFileFlag type IncredibleSquaringDeploymentRaw struct { Addresses IncredibleSquaringContractsRaw `json:"addresses"` } @@ -79,7 +80,7 @@ func NewConfig(ctx *cli.Context) (*Config, error) { return nil, err } - ethRpcClient, err := eth.NewClient(configRaw.EthRpcUrl) + ethRPCClient, err := eth.NewClient(configRaw.EthRPCURL) if err != nil { logger.Errorf("Cannot create http ethclient", "err", err) return nil, err @@ -101,26 +102,26 @@ func NewConfig(ctx *cli.Context) (*Config, error) { return nil, err } - chainId, err := ethRpcClient.ChainID(context.Background()) + chainID, err := ethRPCClient.ChainID(context.Background()) if err != nil { - logger.Error("Cannot get chainId", "err", err) + logger.Error("Cannot get chainID", "err", err) return nil, err } - signerV2, _, err := signerv2.SignerFromConfig(signerv2.Config{PrivateKey: ecdsaPrivateKey}, chainId) + signerV2, _, err := signerv2.SignerFromConfig(signerv2.Config{PrivateKey: ecdsaPrivateKey}, chainID) if err != nil { panic(err) } - txMgr := txmgr.NewSimpleTxManager(ethRpcClient, logger, signerV2, aggregatorAddr) + txMgr := txmgr.NewSimpleTxManager(ethRPCClient, logger, signerV2, aggregatorAddr) config := &Config{ EcdsaPrivateKey: ecdsaPrivateKey, Logger: logger, - EthHttpRpcUrl: configRaw.EthRpcUrl, - EthHttpClient: ethRpcClient, + EthHTTPRPCURL: configRaw.EthRPCURL, + EthHTTPClient: ethRPCClient, OperatorStateRetrieverAddr: common.HexToAddress(credibleSquaringDeploymentRaw.Addresses.OperatorStateRetrieverAddr), IncredibleSquaringRegistryCoordinatorAddr: common.HexToAddress(credibleSquaringDeploymentRaw.Addresses.RegistryCoordinatorAddr), - AggregatorServerIpPortAddr: configRaw.AggregatorServerIpPortAddr, + AggregatorServerIPPortAddr: configRaw.AggregatorServerIPPortAddr, RegisterOperatorOnStartup: configRaw.RegisterOperatorOnStartup, SignerFn: signerV2, TxMgr: txMgr, diff --git a/preconf-operator/core/utils.go b/preconf-operator/core/utils.go deleted file mode 100644 index 9a8bc95..0000000 --- a/preconf-operator/core/utils.go +++ /dev/null @@ -1 +0,0 @@ -package core diff --git a/preconf-operator/operator.go b/preconf-operator/operator.go index 40e5a66..f47e8dc 100644 --- a/preconf-operator/operator.go +++ b/preconf-operator/operator.go @@ -1,3 +1,4 @@ +// Package operator AVS operator logic. package operator import ( @@ -22,7 +23,6 @@ import ( "github.com/Layr-Labs/eigensdk-go/crypto/bls" sdkecdsa "github.com/Layr-Labs/eigensdk-go/crypto/ecdsa" "github.com/Layr-Labs/eigensdk-go/logging" - sdklogging "github.com/Layr-Labs/eigensdk-go/logging" sdkmetrics "github.com/Layr-Labs/eigensdk-go/metrics" "github.com/Layr-Labs/eigensdk-go/metrics/collectors/economic" rpccalls "github.com/Layr-Labs/eigensdk-go/metrics/collectors/rpc_calls" @@ -36,8 +36,8 @@ import ( ) const ( - AVS_NAME = "preconfirmations" - SEM_VER = "0.0.1" + AvsName = "preconfirmations" + SemVer = "0.0.1" ) type Operator struct { @@ -51,54 +51,52 @@ type Operator struct { // writing to the chain should be done via the cli only metricsReg *prometheus.Registry metrics metrics.Metrics - nodeApi *nodeapi.NodeApi - receiveApi *receiverapi.ReceiveApi + nodeAPI *nodeapi.NodeApi + receiveAPI *receiverapi.ReceiveAPI avsWriter *chainio.AvsWriter avsReader chainio.AvsReaderer eigenlayerReader sdkelcontracts.ELReader eigenlayerWriter sdkelcontracts.ELWriter blsKeypair *bls.KeyPair - operatorId bls.OperatorId + operatorID bls.OperatorId operatorAddr common.Address // ip address of aggregator - aggregatorServerIpPortAddr string + aggregatorServerIPPortAddr string // rpc client to send signed task responses to aggregator - aggregatorRpcClient AggregatorRpcClienter + aggregatorRPCClient AggregatorRPCClienter // needed when opting in to avs (allow this service manager contract to slash operator) credibleSquaringServiceManagerAddr common.Address } -// TODO(samlaf): config is a mess right now, since the chainio client constructors -// -// take the config in core (which is shared with aggregator and challenger) +// NewOperatorFromConfig the config in core (which is shared with aggregator and challenger) func NewOperatorFromConfig(c types.NodeConfig) (*Operator, error) { var logLevel logging.LogLevel if c.Production { - logLevel = sdklogging.Production + logLevel = logging.Production } else { - logLevel = sdklogging.Development + logLevel = logging.Development } - logger, err := sdklogging.NewZapLogger(logLevel) + logger, err := logging.NewZapLogger(logLevel) if err != nil { return nil, err } reg := prometheus.NewRegistry() - eigenMetrics := sdkmetrics.NewEigenMetrics(AVS_NAME, c.EigenMetricsIpPortAddress, reg, logger) - avsAndEigenMetrics := metrics.NewAvsAndEigenMetrics(AVS_NAME, eigenMetrics, reg) + eigenMetrics := sdkmetrics.NewEigenMetrics(AvsName, c.EigenMetricsIPPortAddress, reg, logger) + avsAndEigenMetrics := metrics.NewAvsAndEigenMetrics(AvsName, eigenMetrics, reg) // Setup Node Api - nodeApi := nodeapi.NewNodeApi(AVS_NAME, SEM_VER, c.NodeApiIpPortAddress, logger) + nodeAPI := nodeapi.NewNodeApi(AvsName, SemVer, c.NodeAPIIPPortAddress, logger) - var ethRpcClient eth.EthClient + var ethRPCClient eth.EthClient if c.EnableMetrics { - rpcCallsCollector := rpccalls.NewCollector(AVS_NAME, reg) - ethRpcClient, err = eth.NewInstrumentedClient(c.EthRpcUrl, rpcCallsCollector) + rpcCallsCollector := rpccalls.NewCollector(AvsName, reg) + ethRPCClient, err = eth.NewInstrumentedClient(c.EthRPCURL, rpcCallsCollector) if err != nil { logger.Errorf("Cannot create http ethclient", "err", err) return nil, err } } else { - ethRpcClient, err = eth.NewClient(c.EthRpcUrl) + ethRPCClient, err = eth.NewClient(c.EthRPCURL) if err != nil { logger.Errorf("Cannot create http ethclient", "err", err) return nil, err @@ -106,7 +104,7 @@ func NewOperatorFromConfig(c types.NodeConfig) (*Operator, error) { } // Setup Receive Api - receiveApi := receiverapi.NewReceiveApi("localhost:8000", logger, ethRpcClient) + receiveAPI := receiverapi.NewReceiveAPI("localhost:8000", logger, ethRPCClient) blsKeyPassword, ok := os.LookupEnv("OPERATOR_BLS_KEY_PASSWORD") if !ok { @@ -117,12 +115,12 @@ func NewOperatorFromConfig(c types.NodeConfig) (*Operator, error) { logger.Errorf("Cannot parse bls private key", "err", err) return nil, err } - // TODO(samlaf): should we add the chainId to the config instead? + // TODO(samlaf): should we add the chainID to the config instead? // this way we can prevent creating a signer that signs on mainnet by mistake - // if the config says chainId=5, then we can only create a goerli signer - chainId, err := ethRpcClient.ChainID(context.Background()) + // if the config says chainID=5, then we can only create a goerli signer + chainID, err := ethRPCClient.ChainID(context.Background()) if err != nil { - logger.Error("Cannot get chainId", "err", err) + logger.Error("Cannot get chainID", "err", err) return nil, err } @@ -134,17 +132,17 @@ func NewOperatorFromConfig(c types.NodeConfig) (*Operator, error) { signerV2, _, err := signerv2.SignerFromConfig(signerv2.Config{ KeystorePath: c.EcdsaPrivateKeyStorePath, Password: ecdsaKeyPassword, - }, chainId) + }, chainID) if err != nil { panic(err) } chainioConfig := clients.BuildAllConfig{ - EthHttpUrl: c.EthRpcUrl, - EthWsUrl: c.EthRpcUrl, + EthHttpUrl: c.EthRPCURL, + EthWsUrl: c.EthRPCURL, RegistryCoordinatorAddr: c.AVSRegistryCoordinatorAddress, OperatorStateRetrieverAddr: c.OperatorStateRetrieverAddress, - AvsName: AVS_NAME, - PromMetricsIpPortAddress: c.EigenMetricsIpPortAddress, + AvsName: AvsName, + PromMetricsIpPortAddress: c.EigenMetricsIPPortAddress, } sdkClients, err := clients.BuildAll(chainioConfig, common.HexToAddress(c.OperatorAddress), signerV2, logger) @@ -152,11 +150,11 @@ func NewOperatorFromConfig(c types.NodeConfig) (*Operator, error) { panic(err) } - txMgr := txmgr.NewSimpleTxManager(ethRpcClient, logger, signerV2, common.HexToAddress(c.OperatorAddress)) + txMgr := txmgr.NewSimpleTxManager(ethRPCClient, logger, signerV2, common.HexToAddress(c.OperatorAddress)) avsWriter, err := chainio.BuildAvsWriter( txMgr, common.HexToAddress(c.AVSRegistryCoordinatorAddress), - common.HexToAddress(c.OperatorStateRetrieverAddress), ethRpcClient, logger, + common.HexToAddress(c.OperatorStateRetrieverAddress), ethRPCClient, logger, ) if err != nil { logger.Error("Cannot create AvsWriter", "err", err) @@ -166,7 +164,7 @@ func NewOperatorFromConfig(c types.NodeConfig) (*Operator, error) { avsReader, err := chainio.BuildAvsReader( common.HexToAddress(c.AVSRegistryCoordinatorAddress), common.HexToAddress(c.OperatorStateRetrieverAddress), - ethRpcClient, logger) + ethRPCClient, logger) if err != nil { logger.Error("Cannot create AvsReader", "err", err) return nil, err @@ -179,12 +177,12 @@ func NewOperatorFromConfig(c types.NodeConfig) (*Operator, error) { } economicMetricsCollector := economic.NewCollector( sdkClients.ElChainReader, sdkClients.AvsRegistryChainReader, - AVS_NAME, logger, common.HexToAddress(c.OperatorAddress), quorumNames) + AvsName, logger, common.HexToAddress(c.OperatorAddress), quorumNames) reg.MustRegister(economicMetricsCollector) - aggregatorRpcClient, err := NewAggregatorRpcClient(c.AggregatorServerIpPortAddress, logger, avsAndEigenMetrics) + aggregatorRPCClient, err := NewAggregatorRPCClient(c.AggregatorServerIPPortAddress, logger, avsAndEigenMetrics) if err != nil { - logger.Error("Cannot create AggregatorRpcClient. Is aggregator running?", "err", err) + logger.Error("Cannot create AggregatorRPCClient. Is aggregator running?", "err", err) return nil, err } @@ -193,19 +191,19 @@ func NewOperatorFromConfig(c types.NodeConfig) (*Operator, error) { logger: logger, metricsReg: reg, metrics: avsAndEigenMetrics, - nodeApi: nodeApi, - receiveApi: receiveApi, - ethClient: ethRpcClient, + nodeAPI: nodeAPI, + receiveAPI: receiveAPI, + ethClient: ethRPCClient, avsWriter: avsWriter, avsReader: avsReader, eigenlayerReader: sdkClients.ElChainReader, eigenlayerWriter: sdkClients.ElChainWriter, blsKeypair: blsKeyPair, operatorAddr: common.HexToAddress(c.OperatorAddress), - aggregatorServerIpPortAddr: c.AggregatorServerIpPortAddress, - aggregatorRpcClient: aggregatorRpcClient, + aggregatorServerIPPortAddr: c.AggregatorServerIPPortAddress, + aggregatorRPCClient: aggregatorRPCClient, credibleSquaringServiceManagerAddr: common.HexToAddress(c.AVSRegistryCoordinatorAddress), - operatorId: [32]byte{0}, // this is set below + operatorID: [32]byte{0}, // this is set below } @@ -221,14 +219,14 @@ func NewOperatorFromConfig(c types.NodeConfig) (*Operator, error) { } // OperatorId is set in contract during registration so we get it after registering operator. - operatorId, err := sdkClients.AvsRegistryChainReader.GetOperatorId(&bind.CallOpts{}, operator.operatorAddr) + operatorID, err := sdkClients.AvsRegistryChainReader.GetOperatorId(&bind.CallOpts{}, operator.operatorAddr) if err != nil { logger.Error("Cannot get operator id", "err", err) return nil, err } - operator.operatorId = operatorId + operator.operatorID = operatorID logger.Info("Operator info", - "operatorId", operatorId, + "operatorID", operatorID, "operatorAddr", c.OperatorAddress, "operatorG1Pubkey", operator.blsKeypair.GetPubKeyG1(), "operatorG2Pubkey", operator.blsKeypair.GetPubKeyG2(), @@ -251,11 +249,11 @@ func (o *Operator) Start(ctx context.Context) error { o.logger.Infof("Starting operator.") - if o.config.EnableNodeApi { - o.nodeApi.Start() + if o.config.EnableNodeAPI { + o.nodeAPI.Start() } - o.receiveApi.Start() + o.receiveAPI.Start() var metricsErrChan <-chan error if o.config.EnableMetrics { diff --git a/preconf-operator/receiverapi/receiverapi.go b/preconf-operator/receiverapi/receiverapi.go index c01dfd6..7399dec 100644 --- a/preconf-operator/receiverapi/receiverapi.go +++ b/preconf-operator/receiverapi/receiverapi.go @@ -1,3 +1,4 @@ +// Package receiverapi contains the logic to receive preconfirmation callbacks. package receiverapi import ( @@ -14,7 +15,7 @@ import ( "github.com/ethereum/go-ethereum/core/types" ) -type ReceiveApi struct { +type ReceiveAPI struct { ipPortAddr string logger logging.Logger client eth.EthClient @@ -29,24 +30,24 @@ type ReceiveTx struct { Tx *hexutil.Bytes `json:"tx,omitempty"` } -type JsonRpcRequest struct { - Id interface{} `json:"id"` +type JSONRPCRequest struct { + ID interface{} `json:"id"` Method string `json:"method"` Params []ReceiveTx `json:"params"` Version string `json:"jsonrpc,omitempty"` } -func NewReceiveApi(IpPortAddr string, logger logging.Logger, client eth.EthClient) *ReceiveApi { - receiveApi := &ReceiveApi{ - ipPortAddr: IpPortAddr, +func NewReceiveAPI(IPPortAddr string, logger logging.Logger, client eth.EthClient) *ReceiveAPI { + receiveAPI := &ReceiveAPI{ + ipPortAddr: IPPortAddr, logger: logger, client: client, } - return receiveApi + return receiveAPI } // Start starts the receiver api server in a goroutine -func (api *ReceiveApi) Start() <-chan error { +func (api *ReceiveAPI) Start() <-chan error { api.logger.Infof("Starting receiver api server at address %v", api.ipPortAddr) mux := http.NewServeMux() @@ -60,9 +61,9 @@ func (api *ReceiveApi) Start() <-chan error { return errChan } -func (api *ReceiveApi) receive(w http.ResponseWriter, r *http.Request) { +func (api *ReceiveAPI) receive(w http.ResponseWriter, r *http.Request) { decoder := json.NewDecoder(r.Body) - var txs JsonRpcRequest + var txs JSONRPCRequest err := decoder.Decode(&txs) if err != nil { api.logger.Error("could not read request body", "err", err) diff --git a/preconf-operator/registration.go b/preconf-operator/registration.go index 4c8711d..1f45993 100644 --- a/preconf-operator/registration.go +++ b/preconf-operator/registration.go @@ -72,7 +72,7 @@ func (o *Operator) DepositIntoStrategy(strategyAddr common.Address, amount *big. return err } - txOpts, err := o.avsWriter.TxMgr.GetNoSendTxOpts() + txOpts, _ := o.avsWriter.TxMgr.GetNoSendTxOpts() tx, err := contractErc20Mock.Mint(txOpts, o.operatorAddr, amount) if err != nil { o.logger.Error("Error assembling Mint tx", "err", err) @@ -92,7 +92,7 @@ func (o *Operator) DepositIntoStrategy(strategyAddr common.Address, amount *big. return nil } -// Registration specific functions +// RegisterOperatorWithAvs Registration specific functions func (o *Operator) RegisterOperatorWithAvs( operatorEcdsaKeyPair *ecdsa.PrivateKey, ) error { diff --git a/preconf-operator/rpc_client.go b/preconf-operator/rpc_client.go index c8ea373..f0e85f5 100644 --- a/preconf-operator/rpc_client.go +++ b/preconf-operator/rpc_client.go @@ -11,28 +11,28 @@ import ( "github.com/Layr-Labs/eigensdk-go/logging" ) -type AggregatorRpcClienter interface { +type AggregatorRPCClienter interface { SendSignedTaskResponseToAggregator(signedTaskResponse *aggregator.SignedTaskResponse) } -type AggregatorRpcClient struct { +type AggregatorRPCClient struct { rpcClient *rpc.Client metrics metrics.Metrics logger logging.Logger - aggregatorIpPortAddr string + aggregatorIPPortAddr string } -func NewAggregatorRpcClient(aggregatorIpPortAddr string, logger logging.Logger, metrics metrics.Metrics) (*AggregatorRpcClient, error) { - return &AggregatorRpcClient{ +func NewAggregatorRPCClient(aggregatorIPPortAddr string, logger logging.Logger, metrics metrics.Metrics) (*AggregatorRPCClient, error) { + return &AggregatorRPCClient{ // set to nil so that we can create an rpc client even if the aggregator is not running rpcClient: nil, metrics: metrics, logger: logger, - aggregatorIpPortAddr: aggregatorIpPortAddr, + aggregatorIPPortAddr: aggregatorIPPortAddr, }, nil } -func (c *AggregatorRpcClient) dialAggregatorRpcClient() error { - client, err := rpc.DialHTTP("tcp", c.aggregatorIpPortAddr) +func (c *AggregatorRPCClient) dialAggregatorRPCClient() error { + client, err := rpc.DialHTTP("tcp", c.aggregatorIPPortAddr) if err != nil { return err } @@ -45,10 +45,10 @@ func (c *AggregatorRpcClient) dialAggregatorRpcClient() error { // this is because sending the signed task response to the aggregator is time sensitive, // so there is no point in retrying if it fails for a few times. // Currently hardcoded to retry sending the signed task response 5 times, waiting 2 seconds in between each attempt. -func (c *AggregatorRpcClient) SendSignedTaskResponseToAggregator(signedTaskResponse *aggregator.SignedTaskResponse) { +func (c *AggregatorRPCClient) SendSignedTaskResponseToAggregator(signedTaskResponse *aggregator.SignedTaskResponse) { if c.rpcClient == nil { c.logger.Info("rpc client is nil. Dialing aggregator rpc client") - err := c.dialAggregatorRpcClient() + err := c.dialAggregatorRPCClient() if err != nil { c.logger.Error("Could not dial aggregator rpc client. Not sending signed task response header to aggregator. Is aggregator running?", "err", err) return diff --git a/preconf-operator/sse/client_rpc.go b/preconf-operator/sse/client_rpc.go index e2edf94..ac9e7d0 100644 --- a/preconf-operator/sse/client_rpc.go +++ b/preconf-operator/sse/client_rpc.go @@ -56,16 +56,13 @@ func (s *Subscription) readEvents() { var event MatchMakerEvent err = json.Unmarshal([]byte(msg.Payload), &event) - select { - default: - if err != nil { - s.eventChan <- Event{ - Error: err, - } - } else { - s.eventChan <- Event{ - Data: &event, - } + if err != nil { + s.eventChan <- Event{ + Error: err, + } + } else { + s.eventChan <- Event{ + Data: &event, } } } diff --git a/preconf-operator/types/avs_config.go b/preconf-operator/types/avs_config.go index 37200c5..fb1ed97 100644 --- a/preconf-operator/types/avs_config.go +++ b/preconf-operator/types/avs_config.go @@ -1,3 +1,4 @@ +// Package types contains the types used in the AVS JSON-RPC communication. package types import ( @@ -51,13 +52,13 @@ type NodeConfig struct { OperatorStateRetrieverAddress string `yaml:"operator_state_retriever_address"` AVSRegistryCoordinatorAddress string `yaml:"avs_registry_coordinator_address"` TokenStrategyAddr string `yaml:"token_strategy_addr"` - EthRpcUrl string `yaml:"eth_rpc_url"` + EthRPCURL string `yaml:"eth_rpc_url"` BlsPrivateKeyStorePath string `yaml:"bls_private_key_store_path"` EcdsaPrivateKeyStorePath string `yaml:"ecdsa_private_key_store_path"` - AggregatorServerIpPortAddress string `yaml:"aggregator_server_ip_port_address"` + AggregatorServerIPPortAddress string `yaml:"aggregator_server_ip_port_address"` RegisterOperatorOnStartup bool `yaml:"register_operator_on_startup"` - EigenMetricsIpPortAddress string `yaml:"eigen_metrics_ip_port_address"` + EigenMetricsIPPortAddress string `yaml:"eigen_metrics_ip_port_address"` EnableMetrics bool `yaml:"enable_metrics"` - NodeApiIpPortAddress string `yaml:"node_api_ip_port_address"` - EnableNodeApi bool `yaml:"enable_node_api"` + NodeAPIIPPortAddress string `yaml:"node_api_ip_port_address"` + EnableNodeAPI bool `yaml:"enable_node_api"` } diff --git a/preconf-share/preconshare/api.go b/preconf-share/preconshare/api.go index a4f1c74..77f706a 100644 --- a/preconf-share/preconshare/api.go +++ b/preconf-share/preconshare/api.go @@ -25,9 +25,7 @@ var ( ErrInternalServiceError = errors.New("mev-share service error") - simBundleTimeout = 500 * time.Millisecond - cancelBundleTimeout = 3 * time.Second - bundleCacheSize = 1000 + bundleCacheSize = 1000 ) type SimScheduler interface { @@ -83,17 +81,6 @@ func NewAPI( } } -func findAndReplace(strs []common.Hash, old, replacer common.Hash) bool { - var found bool - for i, str := range strs { - if str == old { - strs[i] = replacer - found = true - } - } - return found -} - func (m *API) SendRequest(ctx context.Context, request SendRequestArgs) (_ SendRequestResponse, err error) { logger := m.log startAt := time.Now() diff --git a/preconf-share/preconshare/backend.go b/preconf-share/preconshare/backend.go index 24f5135..d695a1c 100644 --- a/preconf-share/preconshare/backend.go +++ b/preconf-share/preconshare/backend.go @@ -51,8 +51,7 @@ func (b *RedisHintBackend) NotifyHint(ctx context.Context, hint *Hint) error { } type JSONRPCBuilder struct { - url string - client jsonrpc.RPCClient + url string } func (b *JSONRPCBuilder) String() string { diff --git a/preconf-share/preconshare/database.go b/preconf-share/preconshare/database.go index 628cd9c..fc26138 100644 --- a/preconf-share/preconshare/database.go +++ b/preconf-share/preconshare/database.go @@ -6,7 +6,6 @@ import ( "encoding/json" "errors" "fmt" - "math/big" "time" "github.com/ethereum/go-ethereum/common" @@ -15,11 +14,7 @@ import ( _ "github.com/lib/pq" ) -var ( - ethToWei = big.NewInt(1e18) - - ErrBundleNotCancelled = errors.New("bundle not cancelled") -) +var ErrBundleNotCancelled = errors.New("bundle not cancelled") type DBSbundle struct { Hash []byte `db:"hash"` @@ -365,10 +360,6 @@ func (b *DBBackend) InsertBundleForStats(ctx context.Context, bundle *SendReques return known, dbTx.Commit() } -func dbIntToEth(i *hexutil.Big) string { - return new(big.Rat).SetFrac(i.ToInt(), ethToWei).FloatString(18) -} - func (b *DBBackend) InsertPreconf(ctx context.Context, preconf *ConfirmRequestArgs) error { var dbPreconf DBSpreconf diff --git a/preconf-share/preconshare/hints.go b/preconf-share/preconshare/hints.go index 80140e9..8df4f3b 100644 --- a/preconf-share/preconshare/hints.go +++ b/preconf-share/preconshare/hints.go @@ -125,18 +125,6 @@ func ExtractHints(bundle *SendRequestArgs) (Hint, error) { return hint, nil } -func cleanLogs(logs []*types.Log) []CleanLog { - res := make([]CleanLog, len(logs)) - for i, log := range logs { - res[i] = CleanLog{ - Address: log.Address, - Topics: log.Topics, - Data: log.Data, - } - } - return res -} - // Swap (index_topic_1 address sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, index_topic_2 address to) var uni2log = common.HexToHash("0xd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d822") diff --git a/preconf-share/preconshare/sim_queue.go b/preconf-share/preconshare/sim_queue.go index 7d36488..90caf2a 100644 --- a/preconf-share/preconshare/sim_queue.go +++ b/preconf-share/preconshare/sim_queue.go @@ -3,7 +3,6 @@ package preconshare import ( "context" "encoding/json" - "strings" "sync" "time" @@ -180,7 +179,3 @@ func (w *SimulationWorker) isBundleCancelled(ctx context.Context, bundle *SendRe } return res, nil } - -func isErrorRecoverable(message string) bool { - return !strings.Contains(message, "nonce too low") -} diff --git a/preconf-share/preconshare/utils.go b/preconf-share/preconshare/utils.go index a60a44f..0340ba8 100644 --- a/preconf-share/preconshare/utils.go +++ b/preconf-share/preconshare/utils.go @@ -8,29 +8,13 @@ import ( "time" "github.com/ethereum/go-ethereum/ethclient" - "github.com/ethereum/go-ethereum/params" ) var ( - ethDivisor = new(big.Float).SetUint64(params.Ether) - gweiDivisor = new(big.Float).SetUint64(params.GWei) - big1 = big.NewInt(1) big10 = big.NewInt(10) ) -func formatUnits(value *big.Int, unit string) string { - float := new(big.Float).SetInt(value) - switch unit { - case "eth": - return float.Quo(float, ethDivisor).String() - case "gwei": - return float.Quo(float, gweiDivisor).String() - default: - return "" - } -} - type EthCachingClient struct { ethClient *ethclient.Client mu sync.RWMutex @@ -118,17 +102,3 @@ func RoundUpWithPrecision(number *big.Int, precisionDigits int) *big.Int { return result } - -func newerInclusion(old, newBundle *SendRequestArgs) bool { - if old == nil { - return true - } - if newBundle == nil { - return false - } - if old.Inclusion.MaxBlock < newBundle.Inclusion.MaxBlock { - return true - } - - return false -} diff --git a/rpc/adapters/webfile/fetcher.go b/rpc/adapters/webfile/fetcher.go index 7112bd1..6762759 100644 --- a/rpc/adapters/webfile/fetcher.go +++ b/rpc/adapters/webfile/fetcher.go @@ -1,3 +1,4 @@ +// Package webfile contains the fetcher logic package webfile import ( @@ -9,7 +10,7 @@ import ( var ErrRequest = fmt.Errorf("request failed") -// https://raw.githubusercontent.com/flashbots/dowg/main/builder-registrations.json +// Fetcher https://raw.githubusercontent.com/flashbots/dowg/main/builder-registrations.json type Fetcher struct { url string cl http.Client diff --git a/rpc/application/builder_info.go b/rpc/application/builder_info.go index 58a7d96..9efc708 100644 --- a/rpc/application/builder_info.go +++ b/rpc/application/builder_info.go @@ -1,3 +1,4 @@ +// Package application contains the logic to start the builder info service. package application import ( @@ -5,7 +6,6 @@ import ( "encoding/json" "strings" "time" - // "go.uber.org/zap" ) type BuilderInfo struct { @@ -52,11 +52,7 @@ func (bis *BuilderInfoService) syncLoop(fetchInterval time.Duration) { ticker := time.NewTicker(fetchInterval) for range ticker.C { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - err := bis.fetchBuilderInfo(ctx) - if err != nil { - // TODO: probably panic on multiple consequent errors, though it's not critical in nature - // log.Error("failed to fetch builder info", zap.Error(err)) - } + _ = bis.fetchBuilderInfo(ctx) cancel() } } diff --git a/rpc/cmd/server/main.go b/rpc/cmd/server/main.go index 4ad86ed..1922bda 100644 --- a/rpc/cmd/server/main.go +++ b/rpc/cmd/server/main.go @@ -48,28 +48,7 @@ func main() { var err error flag.Parse() - // logFormat := log.TerminalFormat(true) - // if *logJSONPtr { - // logFormat = log.JSONFormat() - // } - - // logLevel := log.LvlInfo - // if *debugPtr { - // logLevel = log.LvlDebug - // } - - // log.Root().SetHandler(log.LvlFilterHandler(logLevel, log.StreamHandler(os.Stderr, logFormat))) - // logger := log.New() - // if *serviceName != "" { - // logger = logger.New(log.Ctx{"service": *serviceName}) - // } - // // Perhaps print only the version - // if *versionPtr { - // logger.Info("rpc-endpoint", "version", version) - // return - // } - - logger, _ := zap.NewDevelopment() + atom := zap.NewAtomicLevel() if *debugPtr { atom.SetLevel(zap.DebugLevel) @@ -77,7 +56,7 @@ func main() { encoderCfg := zap.NewProductionEncoderConfig() encoderCfg.EncodeTime = zapcore.ISO8601TimeEncoder - logger = zap.New(zapcore.NewCore( + logger := zap.New(zapcore.NewCore( zapcore.NewJSONEncoder(encoderCfg), zapcore.Lock(os.Stdout), atom, @@ -119,7 +98,7 @@ func main() { ProxyURL: *proxyURL, RedisURL: *redisURL, RelaySigningKey: key, - RelayUrl: *relayURL, + RelayURL: *relayURL, Version: version, BuilderInfoSource: *builderInfoSource, FetchInfoInterval: *fetchIntervalSeconds, diff --git a/rpc/database/mem_store.go b/rpc/database/mem_store.go index c2b2725..712f32d 100644 --- a/rpc/database/mem_store.go +++ b/rpc/database/mem_store.go @@ -31,7 +31,7 @@ func (m *memStore) SaveRawTxEntries(entries []*EthSendRawTxEntry) error { if len(entries) != 0 { m.mutex.Lock() defer m.mutex.Unlock() - m.EthSendRawTxs[entries[0].RequestId] = entries + m.EthSendRawTxs[entries[0].RequestID] = entries } return nil } diff --git a/rpc/database/types.go b/rpc/database/types.go index a39bf23..5301a67 100644 --- a/rpc/database/types.go +++ b/rpc/database/types.go @@ -1,3 +1,4 @@ +// Package database contains the types used in the database. package database import ( @@ -26,7 +27,7 @@ type RequestEntry struct { // EthSendRawTxEntry to store each eth_sendRawTransaction calls type EthSendRawTxEntry struct { ID uuid.UUID `db:"id"` - RequestId uuid.UUID `db:"request_id"` // id from RequestEntry table + RequestID uuid.UUID `db:"request_id"` // id from RequestEntry table InsertedAt time.Time `db:"inserted_at"` IsOnOafcList bool `db:"is_on_oafc_list"` IsWhiteHatBundleCollection bool `db:"is_white_hat_bundle_collection"` diff --git a/rpc/server/configuration.go b/rpc/server/configuration.go index c6d3f2c..7c3f26d 100644 --- a/rpc/server/configuration.go +++ b/rpc/server/configuration.go @@ -17,7 +17,7 @@ type Configuration struct { ProxyURL string RedisURL string RelaySigningKey *ecdsa.PrivateKey - RelayUrl string + RelayURL string Version string BuilderInfoSource string FetchInfoInterval int diff --git a/rpc/server/ofacblacklist.go b/rpc/server/ofacblacklist.go index 7e03ecd..e318067 100644 --- a/rpc/server/ofacblacklist.go +++ b/rpc/server/ofacblacklist.go @@ -1,4 +1,4 @@ -// OFAC banned addresses +/* Package server OFAC banned addresses */ package server import "strings" diff --git a/rpc/server/redisstate.go b/rpc/server/redisstate.go index 1f107bc..fa50891 100644 --- a/rpc/server/redisstate.go +++ b/rpc/server/redisstate.go @@ -110,7 +110,7 @@ func NewRedisState(redisURL string) (*RedisState, error) { }, nil } -// Enable lookup of timeSentToRelay by txHash +// SetTxSentToRelay Enable lookup of timeSentToRelay by txHash func (s *RedisState) SetTxSentToRelay(txHash string) error { key := RedisKeyTxSentToRelay(txHash) err := s.RedisClient.Set(context.Background(), key, Now().UTC().Unix(), RedisExpiryTxSentToRelay).Err() @@ -135,7 +135,7 @@ func (s *RedisState) GetTxSentToRelay(txHash string) (timeSent time.Time, found return t, true, nil } -// Enable lookup of txHash by txFrom+nonce +// SetTxHashForSenderAndNonce Enable lookup of txHash by txFrom+nonce func (s *RedisState) SetTxHashForSenderAndNonce(txFrom string, nonce uint64, txHash string) error { key := RedisKeyTxHashForSenderAndNonce(txFrom, nonce) err := s.RedisClient.Set(context.Background(), key, strings.ToLower(txHash), RedisExpiryTxHashForSenderAndNonce).Err() @@ -154,7 +154,7 @@ func (s *RedisState) GetTxHashForSenderAndNonce(txFrom string, nonce uint64) (tx return txHash, true, nil } -// nonce-fix per account +// SetNonceFixForAccount nonce-fix per account func (s *RedisState) SetNonceFixForAccount(txFrom string, numTimesSent uint64) error { key := RedisKeyNonceFixForAccount(txFrom) err := s.RedisClient.Set(context.Background(), key, numTimesSent, RedisExpiryNonceFixForAccount).Err() @@ -183,7 +183,7 @@ func (s *RedisState) GetNonceFixForAccount(txFrom string) (numTimesSent uint64, return numTimesSent, true, nil } -// Enable lookup of txFrom by txHash +// SetSenderOfTxHash Enable lookup of txFrom by txHash func (s *RedisState) SetSenderOfTxHash(txHash, txFrom string) error { key := RedisKeySenderOfTxHash(txHash) err := s.RedisClient.Set(context.Background(), key, strings.ToLower(txFrom), RedisExpirySenderOfTxHash).Err() @@ -202,7 +202,7 @@ func (s *RedisState) GetSenderOfTxHash(txHash string) (txSender string, found bo return strings.ToLower(txSender), true, nil } -// Enable lookup of tx bundles by bundle ID +// AddTxToWhitehatBundle Enable lookup of tx bundles by bundle ID func (s *RedisState) AddTxToWhitehatBundle(bundleID, signedTx string) error { key := RedisKeyWhitehatBundleTransactions(bundleID) @@ -296,7 +296,7 @@ func (s *RedisState) GetSenderMaxNonce(txFrom string) (senderMaxNonce uint64, fo return senderMaxNonce, true, nil } -// Block transactions, with a specific return value (eg. "nonce too low") +// SetBlockedTxHash Block transactions, with a specific return value (eg. "nonce too low") func (s *RedisState) SetBlockedTxHash(txHash, returnValue string) error { key := RedisKeyBlockedTxHash(txHash) err := s.RedisClient.Set(context.Background(), key, returnValue, RedisExpiryBlockedTxHash).Err() diff --git a/rpc/server/request_handler.go b/rpc/server/request_handler.go index e3947f7..079df58 100644 --- a/rpc/server/request_handler.go +++ b/rpc/server/request_handler.go @@ -13,7 +13,7 @@ import ( "go.uber.org/zap" ) -// RPC request handler for a single/ batch JSON-RPC request +// RPCRequestHandler RPC request handler for a single/ batch JSON-RPC request type RPCRequestHandler struct { respw *http.ResponseWriter req *http.Request @@ -100,7 +100,7 @@ func (r *RPCRequestHandler) process() { } // mev-share parameters - urlParams, err := ExtractParametersFromUrl(r.req.URL, r.builderNames) + urlParams, err := ExtractParametersFromURL(r.req.URL, r.builderNames) if err != nil { r.logger.Warn("[process] Invalid auction preference", zap.Error(err)) res := AuctionPreferenceErrorToJSONRPCResponse(jsonReq, err) diff --git a/rpc/server/request_intercepts.go b/rpc/server/request_intercepts.go index 261812c..fce786d 100644 --- a/rpc/server/request_intercepts.go +++ b/rpc/server/request_intercepts.go @@ -11,7 +11,7 @@ import ( var ProtectTxAPIHost = GetEnv("TX_API_HOST", "https://protect.flashbots.net") // If public getTransactionReceipt of a submitted tx is null, then check internal API to see if tx has failed -func (r *RPCRequest) check_post_getTransactionReceipt(jsonResp *types.JSONRPCResponse) (requestFinished bool) { +func (r *RPCRequest) checkPostGetTransactionReceipt(jsonResp *types.JSONRPCResponse) (requestFinished bool) { if jsonResp == nil { return false } @@ -80,7 +80,7 @@ func (r *RPCRequest) check_post_getTransactionReceipt(jsonResp *types.JSONRPCRes // // NOTE: This branch can never happen, because if tx is included then Receipt will not return null // // TODO? If latest tx of this user was a successful, then we should remove the nonce fix // // This could lead to a ping-pong between checking 2 tx, with one check adding and another removing the nonce fix - // // See also the branch tmp-check_post_getTransactionReceipt-removeNonceFix + // // See also the branch tmp-checkPostGetTransactionReceipt-removeNonceFix // _ = 1 } diff --git a/rpc/server/request_processor.go b/rpc/server/request_processor.go index 22732d8..ade3f96 100644 --- a/rpc/server/request_processor.go +++ b/rpc/server/request_processor.go @@ -1,13 +1,10 @@ -/* -Request represents an incoming client request -*/ +/* Package server Request represents an incoming client request */ package server import ( "context" "crypto/ecdsa" "encoding/json" - "errors" "io" "math/big" "reflect" @@ -22,7 +19,6 @@ import ( "github.com/ethereum/go-ethereum/common/hexutil" ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" - "github.com/metachris/flashbotsrpc" "github.com/ybbus/jsonrpc/v3" "go.uber.org/zap" ) @@ -111,7 +107,7 @@ func (r *RPCRequest) ProcessRequest() *types.JSONRPCResponse { // After proxy, perhaps check backend [MM fix #3 step 2] if r.jsonReq.Method == "eth_getTransactionReceipt" { - requestCompleted := r.check_post_getTransactionReceipt(r.jsonRes) + requestCompleted := r.checkPostGetTransactionReceipt(r.jsonRes) if requestCompleted { return r.jsonRes } @@ -320,82 +316,6 @@ func (r *RPCRequest) sendTxToRelay() { r.logger.Info("[sendTxToRelay] Sent and received preconfirmation", zap.String("tx", txHash), zap.Uint64("block", uint64(result.Block))) } -// Sends cancel-tx to relay as cancelPrivateTransaction, if initial tx was sent there too. -func (r *RPCRequest) handleCancelTx() (requestCompleted bool) { - cancelTxHash := strings.ToLower(r.tx.Hash().Hex()) - txFromLower := strings.ToLower(r.txFrom) - r.logger.Info("[cancel-tx] cancelling transaction", zap.String("cancelTxHash", cancelTxHash), zap.String("txFromLower", txFromLower), zap.Uint64("txNonce", r.tx.Nonce())) - - // Get initial txHash by sender+nonce - initialTxHash, txHashFound, err := RState.GetTxHashForSenderAndNonce(txFromLower, r.tx.Nonce()) - if err != nil { - r.logger.Error("[cancelTx] Redis:GetTxHashForSenderAndNonce failed", zap.Error(err)) - r.writeRPCError("internal server error", types.JSONRPCInternalError) - return true - } - - if !txHashFound { // not found, send to mempool - return false - } - - // Check if initial tx was sent to relay - _, txWasSentToRelay, err := RState.GetTxSentToRelay(initialTxHash) - if err != nil { - r.logger.Error("[cancelTx] Redis:GetTxSentToRelay failed", zap.Error(err)) - r.writeRPCError("internal server error", types.JSONRPCInternalError) - return true - } - - if !txWasSentToRelay { // was not sent to relay, send to mempool - return false - } - - // Should send cancel-tx to relay. Check if cancel-tx was already sent before - _, cancelTxAlreadySentToRelay, err := RState.GetTxSentToRelay(cancelTxHash) - if err != nil { - r.logger.Error("[cancelTx] Redis:GetTxSentToRelay error", zap.Error(err)) - r.writeRPCError("internal server error", types.JSONRPCInternalError) - return true - } - - if cancelTxAlreadySentToRelay { // already sent - r.writeRPCResult(cancelTxHash) - return true - } - - err = RState.SetTxSentToRelay(cancelTxHash) - if err != nil { - r.logger.Error("[cancelTx] Redis:SetTxSentToRelay failed", zap.Error(err)) - } - - r.logger.Info("[cancel-tx] sending to relay", zap.String("initialTxHash", initialTxHash), zap.String("txFromLower", txFromLower), zap.Uint64("txNonce", r.tx.Nonce())) - - if DebugDontSendTx { - r.logger.Info("[cancelTx] Faked sending cancel-tx to relay, did nothing", zap.String("tx", initialTxHash)) - r.writeRPCResult(initialTxHash) - return true - } - - cancelPrivTxArgs := flashbotsrpc.FlashbotsCancelPrivateTransactionRequest{TxHash: initialTxHash} - - fbRpc := flashbotsrpc.New(r.relayURL) - _, err = fbRpc.FlashbotsCancelPrivateTransaction(r.relaySigningKey, cancelPrivTxArgs) - if err != nil { - if errors.Is(err, flashbotsrpc.ErrRelayErrorResponse) { - // errors could be: 'tx not found', 'tx was already cancelled', 'tx has already expired' - r.logger.Info("[cancelTx] Relay error response", zap.Error(err), zap.String("rawTx", r.rawTxHex)) - r.writeRPCError(err.Error(), types.JSONRPCInternalError) - } else { - r.logger.Error("[cancelTx] Relay call failed", zap.Error(err), zap.String("rawTx", r.rawTxHex)) - r.writeRPCError("internal server error", types.JSONRPCInternalError) - } - return true - } - - r.writeRPCResult(cancelTxHash) - return true -} - func (r *RPCRequest) GetAddressNonceRange(address string) (minNonce, maxNonce uint64, err error) { // Get minimum nonce by asking the eth node for the current transaction count _req := types.NewJSONRPCRequest(1, "eth_getTransactionCount", []interface{}{r.txFrom, "latest"}) diff --git a/rpc/server/request_record.go b/rpc/server/request_record.go index 2cfe43b..1e0d07e 100644 --- a/rpc/server/request_record.go +++ b/rpc/server/request_record.go @@ -25,7 +25,7 @@ func NewRequestRecord(db database.Store) *requestRecord { func (r *requestRecord) AddEthSendRawTxEntry(id uuid.UUID) *database.EthSendRawTxEntry { entry := &database.EthSendRawTxEntry{ ID: id, - RequestId: r.requestEntry.ID, + RequestID: r.requestEntry.ID, } r.mutex.Lock() defer r.mutex.Unlock() diff --git a/rpc/server/request_record_test.go b/rpc/server/request_record_test.go index 2863d6d..a2f8fa0 100644 --- a/rpc/server/request_record_test.go +++ b/rpc/server/request_record_test.go @@ -74,30 +74,30 @@ func Test_requestRecord_SaveRecord(t *testing.T) { id: id1, requestEntry: database.RequestEntry{ID: id1}, ethSendRawTxEntries: []*database.EthSendRawTxEntry{ - {RequestId: id1, WasSentToMempool: true}, - {RequestId: id1, WasSentToMempool: true}, - {RequestId: id1, IsCancelTx: true}, - {RequestId: id1, WasSentToRelay: true, ErrorCode: -32600}, - {RequestId: id1, WasSentToMempool: true}, + {RequestID: id1, WasSentToMempool: true}, + {RequestID: id1, WasSentToMempool: true}, + {RequestID: id1, IsCancelTx: true}, + {RequestID: id1, WasSentToRelay: true, ErrorCode: -32600}, + {RequestID: id1, WasSentToMempool: true}, }, rawTxEntryLen: 4, }, "Should successfully store single request": { id: id2, requestEntry: database.RequestEntry{ID: id2}, - ethSendRawTxEntries: []*database.EthSendRawTxEntry{{RequestId: id2, WasSentToMempool: true}}, + ethSendRawTxEntries: []*database.EthSendRawTxEntry{{RequestID: id2, WasSentToMempool: true}}, rawTxEntryLen: 1, }, "Should successfully store single request with rawTxEntry has error": { id: id3, requestEntry: database.RequestEntry{ID: id3}, - ethSendRawTxEntries: []*database.EthSendRawTxEntry{{RequestId: id3, ErrorCode: -32600}}, + ethSendRawTxEntries: []*database.EthSendRawTxEntry{{RequestID: id3, ErrorCode: -32600}}, rawTxEntryLen: 1, }, "Should not store if the request doesnt meet entry condition": { id: id4, requestEntry: database.RequestEntry{ID: id4}, - ethSendRawTxEntries: []*database.EthSendRawTxEntry{{RequestId: id4, IsCancelTx: true}}, + ethSendRawTxEntries: []*database.EthSendRawTxEntry{{RequestID: id4, IsCancelTx: true}}, rawTxEntryLen: 0, }, } diff --git a/rpc/server/server.go b/rpc/server/server.go index b15b8dd..c146a68 100644 --- a/rpc/server/server.go +++ b/rpc/server/server.go @@ -29,7 +29,7 @@ var Now = time.Now // used to mock time in tests var DebugDontSendTx = os.Getenv("DEBUG_DONT_SEND_RAWTX") != "" -// Metamask fix helper +// RState Metamask fix helper var RState *RedisState type BuilderNameProvider interface { @@ -100,7 +100,7 @@ func NewRPCEndPointServer(cfg Configuration) (*RPCEndPointServer, error) { proxyTimeoutSeconds: cfg.ProxyTimeoutSeconds, proxyURL: cfg.ProxyURL, relaySigningKey: cfg.RelaySigningKey, - relayURL: cfg.RelayUrl, + relayURL: cfg.RelayURL, startTime: Now(), version: cfg.Version, chainID: bts, diff --git a/rpc/server/url_params.go b/rpc/server/url_params.go index a84405a..0176751 100644 --- a/rpc/server/url_params.go +++ b/rpc/server/url_params.go @@ -31,14 +31,14 @@ type URLParameters struct { fast bool } -// ExtractParametersFromUrl extracts the auction preference from the url query +// ExtractParametersFromURL extracts the auction preference from the url query // Allowed query params: // - hint: mev share hints, can be set multiple times, default: hash, special_logs // - originID: origin id, default: "" // - builder: target builder, can be set multiple times, default: empty (only send to flashbots builders) // - refund: refund in the form of 0xaddress:percentage, default: empty (will be set by default when backrun is produced) // example: 0x123:80 - will refund 80% of the backrun profit to 0x123 -func ExtractParametersFromUrl(url *url.URL, allBuilders []string) (params URLParameters, err error) { +func ExtractParametersFromURL(url *url.URL, allBuilders []string) (params URLParameters, err error) { if strings.HasPrefix(url.Path, "/fast") { params.fast = true } diff --git a/rpc/server/url_params_test.go b/rpc/server/url_params_test.go index 06f5b94..9071415 100644 --- a/rpc/server/url_params_test.go +++ b/rpc/server/url_params_test.go @@ -208,7 +208,7 @@ func TestExtractAuctionPreferenceFromUrl(t *testing.T) { t.Fatal("failed to parse url: ", err) } - got, err := ExtractParametersFromUrl(url, []string{"builder1", "builder2"}) + got, err := ExtractParametersFromURL(url, []string{"builder1", "builder2"}) if tt.err != nil { require.ErrorIs(t, err, tt.err) } else { diff --git a/rpc/server/util.go b/rpc/server/util.go index 4e064df..8727fcb 100644 --- a/rpc/server/util.go +++ b/rpc/server/util.go @@ -115,12 +115,12 @@ func GetIPHash(r *http.Request) string { return hex.EncodeToString(hash[:]) } -// CHROME_ID: nkbihfbeogaeaoehlefnkodbefgpgknn +// IsMetamask CHROME_ID: nkbihfbeogaeaoehlefnkodbefgpgknn func IsMetamask(r *http.Request) bool { return r.Header.Get("Origin") == "chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn" } -// FIREFOX_ID: webextension@metamask.io +// IsMetamaskMoz FIREFOX_ID: webextension@metamask.io func IsMetamaskMoz(r *http.Request) bool { return r.Header.Get("Origin") == "moz-extension://57f9aaf6-270a-154f-9a8a-632d0db4128c" } diff --git a/rpc/server/whitelist.go b/rpc/server/whitelist.go index 05775d6..779145d 100644 --- a/rpc/server/whitelist.go +++ b/rpc/server/whitelist.go @@ -1,4 +1,4 @@ -// Whitelist for smart contract functions that never need protection. +// Package server Whitelist for smart contract functions that never need protection. package server import "strings" diff --git a/rpc/tests/e2e_test.go b/rpc/tests/e2e_test.go index e9c2983..e814444 100644 --- a/rpc/tests/e2e_test.go +++ b/rpc/tests/e2e_test.go @@ -78,7 +78,7 @@ func testServerSetup(db database.Store) { ProxyURL: RPCBackendServerURL, RedisURL: redisServer.Addr(), RelaySigningKey: relaySigningKey, - RelayUrl: RPCBackendServerURL, + RelayURL: RPCBackendServerURL, Version: "test", }) if err != nil { @@ -227,7 +227,7 @@ func TestMetamaskFix(t *testing.T) { testServerSetupWithMockStore() testutils.MockTxAPIStatusForHash[testutils.TestTxMM2Hash] = types.TxStatusFailed - reqGetTransactionCount := types.NewJSONRPCRequest(1, "eth_getTransactionCount", []interface{}{testutils.TestTx_MM2_From, "latest"}) + reqGetTransactionCount := types.NewJSONRPCRequest(1, "eth_getTransactionCount", []interface{}{testutils.TestTxMM2From, "latest"}) txCountBefore := testutils.SendRPCAndParseResponseOrFailNowString(t, reqGetTransactionCount) // first sendRawTransaction call: rawTx that triggers the error (creates MM cache entry) @@ -433,7 +433,7 @@ func TestBatch_eth_transaction(t *testing.T) { testServerSetupWithMockStore() var batch []*types.JSONRPCRequest - reqGetTransactionCount := types.NewJSONRPCRequest(1, "eth_getTransactionCount", []interface{}{testutils.TestTx_MM2_From, "latest"}) + reqGetTransactionCount := types.NewJSONRPCRequest(1, "eth_getTransactionCount", []interface{}{testutils.TestTxMM2From, "latest"}) batch = append(batch, reqGetTransactionCount) // first sendRawTransaction call: rawTx that triggers the error (creates MM cache entry) reqSendRawTransaction := types.NewJSONRPCRequest(2, "eth_sendRawTransaction", []interface{}{testutils.TestTxMM2RawTx}) @@ -474,7 +474,7 @@ func TestBatch_eth_call(t *testing.T) { "to": "0xf1a54b0759b58661cea17cff19dd37940a9b5f1b", }}) batch = append(batch, req2) - reqGetTransactionCount := types.NewJSONRPCRequest(3, "eth_getTransactionCount", []interface{}{testutils.TestTx_MM2_From, "latest"}) + reqGetTransactionCount := types.NewJSONRPCRequest(3, "eth_getTransactionCount", []interface{}{testutils.TestTxMM2From, "latest"}) batch = append(batch, reqGetTransactionCount) // first sendRawTransaction call: rawTx that triggers the error (creates MM cache entry) reqSendRawTransaction := types.NewJSONRPCRequest(4, "eth_sendRawTransaction", []interface{}{testutils.TestTxMM2RawTx}) @@ -516,7 +516,7 @@ func TestBatch_CombinationOfSuccessAndFailure(t *testing.T) { "to": "0xf1a54b0759b58661cea17cff19dd37940a9b5f1b", }}) batch = append(batch, req2) - reqGetTransactionCount := types.NewJSONRPCRequest(1, "eth_getTransactionCount", []interface{}{testutils.TestTx_MM2_From, "latest"}) + reqGetTransactionCount := types.NewJSONRPCRequest(1, "eth_getTransactionCount", []interface{}{testutils.TestTxMM2From, "latest"}) batch = append(batch, reqGetTransactionCount) // first sendRawTransaction call: rawTx that triggers the error (creates MM cache entry) reqSendRawTransaction := types.NewJSONRPCRequest(1, "eth_sendRawTransactionxxx", []interface{}{testutils.TestTxMM2RawTx}) @@ -608,7 +608,7 @@ func TestWhitehatBundleCollectionGetBalance(t *testing.T) { url := testutils.RPCEndpointURL + "?bundle=" + bundleID // sendRawTransaction adds tx to MM cache entry, to be used at later eth_getTransactionReceipt call - reqGetTransactionCount := types.NewJSONRPCRequest(1, "eth_getBalance", []interface{}{testutils.TestTx_MM2_From, "latest"}) + reqGetTransactionCount := types.NewJSONRPCRequest(1, "eth_getBalance", []interface{}{testutils.TestTxMM2From, "latest"}) resp, err := testutils.SendRPCAndParseResponseTo(url, reqGetTransactionCount) require.Nil(t, err, err) require.Nil(t, resp.Error, resp.Error) @@ -665,7 +665,7 @@ func Test_StoreBatchRequests(t *testing.T) { "to": "0xf1a54b0759b58661cea17cff19dd37940a9b5f1b", }}) batch = append(batch, req2) - reqGetTransactionCount := types.NewJSONRPCRequest(1, "eth_getTransactionCount", []interface{}{testutils.TestTx_MM2_From, "latest"}) + reqGetTransactionCount := types.NewJSONRPCRequest(1, "eth_getTransactionCount", []interface{}{testutils.TestTxMM2From, "latest"}) batch = append(batch, reqGetTransactionCount) // first sendRawTransaction call: rawTx that triggers the error (creates MM cache entry) reqSendRawTransaction := types.NewJSONRPCRequest(1, "eth_sendRawTransaction", []interface{}{testutils.TestTxMM2RawTx}) diff --git a/rpc/testutils/mock_rpcbackend.go b/rpc/testutils/mock_rpcbackend.go index 9082b32..b3e62df 100644 --- a/rpc/testutils/mock_rpcbackend.go +++ b/rpc/testutils/mock_rpcbackend.go @@ -1,7 +1,4 @@ -/* - * Dummy RPC backend for both Ethereum node and Flashbots Relay. - * Implements JSON-RPC calls that the tests need. - */ +/* Package testutils Dummy RPC backend for both Ethereum node and Flashbots Relay. Implements JSON-RPC calls that the tests need. */ package testutils import ( diff --git a/rpc/testutils/rpctesthelpers.go b/rpc/testutils/rpctesthelpers.go index c34944d..18f6853 100644 --- a/rpc/testutils/rpctesthelpers.go +++ b/rpc/testutils/rpctesthelpers.go @@ -1,6 +1,3 @@ -/* - * Test helpers. - */ package testutils import ( diff --git a/rpc/testutils/transactions.go b/rpc/testutils/transactions.go index fb6223c..7ce2e8c 100644 --- a/rpc/testutils/transactions.go +++ b/rpc/testutils/transactions.go @@ -10,9 +10,9 @@ var ( // Test tx for MM2 fix var ( - TestTxMM2RawTx = "0xf86980850e5b35485d8252089409f427f1bd2d7537a02812275d03be7747dbd68c859d64bd68008025a0a94ba415e4d7c517548551442828aa192f149a8a04554e452084ee0ea55ea013a015966c84d9d38779ce63454a3f38038b269544d70433bfa7db0f6a37034b8e93" - TestTx_MM2_From = "0x7AaBc7915DF92a85E199DbB4B1D21E637e1a90A2" - TestTxMM2Hash = "0xc543e2ad05cffdee95b984df20edd2e38e124c54461faa1276adc36e826588c9" + TestTxMM2RawTx = "0xf86980850e5b35485d8252089409f427f1bd2d7537a02812275d03be7747dbd68c859d64bd68008025a0a94ba415e4d7c517548551442828aa192f149a8a04554e452084ee0ea55ea013a015966c84d9d38779ce63454a3f38038b269544d70433bfa7db0f6a37034b8e93" + TestTxMM2From = "0x7AaBc7915DF92a85E199DbB4B1D21E637e1a90A2" + TestTxMM2Hash = "0xc543e2ad05cffdee95b984df20edd2e38e124c54461faa1276adc36e826588c9" ) // Test tx for MM2 fix diff --git a/rpc/types/types.go b/rpc/types/types.go index 0c1bd22..af4ebbc 100644 --- a/rpc/types/types.go +++ b/rpc/types/types.go @@ -1,3 +1,4 @@ +// Package types contains the types used in the JSON-RPC requests and responses. package types import ( @@ -47,7 +48,7 @@ type JSONRPCResponse struct { Version string `json:"jsonrpc"` } -// JSONRPCError: https://www.jsonrpc.org/specification#error_object +// JSONRPCError https://www.jsonrpc.org/specification#error_object type JSONRPCError struct { Code int `json:"code"` Message string `json:"message"` diff --git a/tests/utils.go b/tests/utils.go index ea2a281..2a0b421 100644 --- a/tests/utils.go +++ b/tests/utils.go @@ -1,3 +1,4 @@ +// Package tests contains the utilities for tests. package tests import ( @@ -8,7 +9,7 @@ import ( "time" ) -// Make sure to stop the anvil subprocess by calling anvilCmd.Process.Kill() +// StartAnvilChainAndDeployContracts Make sure to stop the anvil subprocess by calling anvilCmd.Process.Kill() func StartAnvilChainAndDeployContracts() *exec.Cmd { fmt.Println("Starting anvil...") anvilCmd := exec.Command("anvil", "--fork-url", "https://goerli.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161")