Skip to content

Commit

Permalink
chore(evm): wiped deprecated evm apis: miner, personal (#1958)
Browse files Browse the repository at this point in the history
* chore(evm): wiped miner api

* chore: changelog update

* chore(evm): removed personal api

* chore(evm): removed miner and personal api methods
  • Loading branch information
onikonychev authored Jul 8, 2024
1 parent 1b758bb commit 2a6c81a
Show file tree
Hide file tree
Showing 12 changed files with 8 additions and 915 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- [#1936](https://github.com/NibiruChain/nibiru/pull/1936) - feat(evm): EVM fungible token protobufs and encoding tests
- [#1947](https://github.com/NibiruChain/nibiru/pull/1947) - fix(evm): fix FunToken state marshalling
- [#1949](https://github.com/NibiruChain/nibiru/pull/1949) - feat(evm): add fungible token mapping queries
- [#1958](https://github.com/NibiruChain/nibiru/pull/1958) - chore(evm): wiped deprecated evm apis: miner, personal

#### Dapp modules: perp, spot, oracle, etc

Expand Down
4 changes: 2 additions & 2 deletions app/server/config/server_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ func GetDefaultAPINamespaces() []string {

// GetAPINamespaces returns the all the available JSON-RPC API namespaces.
func GetAPINamespaces() []string {
return []string{"web3", "eth", "personal", "net", "txpool", "debug", "miner"}
return []string{"web3", "eth", "net", "txpool", "debug"}
}

// DefaultJSONRPCConfig returns an EVM config with the JSON-RPC API enabled by default
Expand Down Expand Up @@ -397,7 +397,7 @@ address = "{{ .JSONRPC.Address }}"
ws-address = "{{ .JSONRPC.WsAddress }}"
# API defines a list of JSON-RPC namespaces that should be enabled
# Example: "eth,txpool,personal,net,debug,web3"
# Example: "eth,txpool,net,debug,web3"
api = "{{range $index, $elmt := .JSONRPC.API}}{{if $index}},{{$elmt}}{{else}}{{$elmt}}{{end}}{{end}}"
# GasCap sets a cap on gas that can be used in eth_call/estimateGas (0=infinite). Default: 25,000,000.
Expand Down
9 changes: 0 additions & 9 deletions eth/rpc/backend/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import (
"github.com/cometbft/cometbft/libs/log"
tmrpctypes "github.com/cometbft/cometbft/rpc/core/types"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/cosmos/cosmos-sdk/server"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/ethereum/go-ethereum/common"
Expand Down Expand Up @@ -48,12 +47,6 @@ type EVMBackend interface {
// Node specific queries
Accounts() ([]common.Address, error)
Syncing() (interface{}, error)
SetEtherbase(etherbase common.Address) bool
SetGasPrice(gasPrice hexutil.Big) bool
ImportRawKey(privkey, password string) (common.Address, error)
ListAccounts() ([]common.Address, error)
NewMnemonic(uid string, language keyring.Language, hdPath, bip39Passphrase string, algo keyring.SignatureAlgo) (*keyring.Record, error)
UnprotectedAllowed() bool
RPCGasCap() uint64 // global gas cap for eth_call over rpc: DoS protection
RPCEVMTimeout() time.Duration // global timeout for eth_call over rpc: DoS protection
RPCTxFeeCap() float64 // RPCTxFeeCap is the global transaction fee(price * gaslimit) cap for send-transaction variants. The unit is ether.
Expand Down Expand Up @@ -94,11 +87,9 @@ type EVMBackend interface {
ChainID() (*hexutil.Big, error)
ChainConfig() *params.ChainConfig
// TODO: feat: Dynamic fees
// GlobalMinGasPrice() (math.LegacyDec, error)
BaseFee(blockRes *tmrpctypes.ResultBlockResults) (*big.Int, error)
CurrentHeader() (*gethcore.Header, error)
PendingTransactions() ([]*sdk.Tx, error)
GetCoinbase() (sdk.AccAddress, error)
FeeHistory(blockCount gethrpc.DecimalOrHex, lastBlock gethrpc.BlockNumber, rewardPercentiles []float64) (*rpc.FeeHistoryResult, error)
SuggestGasTipCap(baseFee *big.Int) (*big.Int, error)

Expand Down
25 changes: 0 additions & 25 deletions eth/rpc/backend/chain_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,31 +97,6 @@ func (b *Backend) PendingTransactions() ([]*sdk.Tx, error) {
return result, nil
}

// GetCoinbase is the address that staking rewards will be send to (alias for Etherbase).
func (b *Backend) GetCoinbase() (sdk.AccAddress, error) {
node, err := b.clientCtx.GetNode()
if err != nil {
return nil, err
}

status, err := node.Status(b.ctx)
if err != nil {
return nil, err
}

req := &evm.QueryValidatorAccountRequest{
ConsAddress: sdk.ConsAddress(status.ValidatorInfo.Address).String(),
}

res, err := b.queryClient.ValidatorAccount(b.ctx, req)
if err != nil {
return nil, err
}

address, _ := sdk.AccAddressFromBech32(res.AccountAddress) // #nosec G703
return address, nil
}

// FeeHistory returns data relevant for fee estimation based on the specified range of blocks.
func (b *Backend) FeeHistory(
userBlockCount gethrpc.DecimalOrHex, // number blocks to fetch, maximum is 100
Expand Down
57 changes: 0 additions & 57 deletions eth/rpc/backend/chain_info_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,63 +136,6 @@ func (s *BackendSuite) TestChainId() {
}
}

func (s *BackendSuite) TestGetCoinbase() {
validatorAcc := sdk.AccAddress(evmtest.NewEthAccInfo().EthAddr.Bytes())
testCases := []struct {
name string
registerMock func()
accAddr sdk.AccAddress
expPass bool
}{
{
"fail - Can't retrieve status from node",
func() {
client := s.backend.clientCtx.Client.(*mocks.Client)
RegisterStatusError(client)
},
validatorAcc,
false,
},
{
"fail - Can't query validator account",
func() {
client := s.backend.clientCtx.Client.(*mocks.Client)
queryClient := s.backend.queryClient.QueryClient.(*mocks.EVMQueryClient)
RegisterStatus(client)
RegisterValidatorAccountError(queryClient)
},
validatorAcc,
false,
},
{
"pass - Gets coinbase account",
func() {
client := s.backend.clientCtx.Client.(*mocks.Client)
queryClient := s.backend.queryClient.QueryClient.(*mocks.EVMQueryClient)
RegisterStatus(client)
RegisterValidatorAccount(queryClient, validatorAcc)
},
validatorAcc,
true,
},
}

for _, tc := range testCases {
s.Run(fmt.Sprintf("case %s", tc.name), func() {
s.SetupTest() // reset test and queries
tc.registerMock()

accAddr, err := s.backend.GetCoinbase()

if tc.expPass {
s.Require().Equal(tc.accAddr, accAddr)
} else {
s.Require().Error(err)
}
})
}
}

func (s *BackendSuite) TestSuggestGasTipCap() {
testCases := []struct {
name string
Expand Down
223 changes: 0 additions & 223 deletions eth/rpc/backend/node_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,12 @@
package backend

import (
"fmt"
"math/big"
"time"

errorsmod "cosmossdk.io/errors"
sdkmath "cosmossdk.io/math"
tmtypes "github.com/cometbft/cometbft/types"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/client/tx"
sdkcrypto "github.com/cosmos/cosmos-sdk/crypto"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
sdkconfig "github.com/cosmos/cosmos-sdk/server/config"
sdk "github.com/cosmos/cosmos-sdk/types"
authtx "github.com/cosmos/cosmos-sdk/x/auth/tx"
distributiontypes "github.com/cosmos/cosmos-sdk/x/distribution/types"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"

"github.com/NibiruChain/nibiru/app/server/config"
"github.com/NibiruChain/nibiru/eth"
"github.com/NibiruChain/nibiru/eth/crypto/ethsecp256k1"
"github.com/NibiruChain/nibiru/eth/rpc"
"github.com/NibiruChain/nibiru/x/evm"
)

Expand Down Expand Up @@ -75,212 +58,6 @@ func (b *Backend) Syncing() (interface{}, error) {
}, nil
}

// SetEtherbase sets the etherbase of the miner
func (b *Backend) SetEtherbase(etherbase common.Address) bool {
delAddr, err := b.GetCoinbase()
if err != nil {
b.logger.Debug("failed to get coinbase address", "error", err.Error())
return false
}

withdrawAddr := sdk.AccAddress(etherbase.Bytes())
msg := distributiontypes.NewMsgSetWithdrawAddress(delAddr, withdrawAddr)

if err := msg.ValidateBasic(); err != nil {
b.logger.Debug("tx failed basic validation", "error", err.Error())
return false
}

// Assemble transaction from fields
builder, ok := b.clientCtx.TxConfig.NewTxBuilder().(authtx.ExtensionOptionsTxBuilder)
if !ok {
b.logger.Debug("clientCtx.TxConfig.NewTxBuilder returns unsupported builder", "error", err.Error())
return false
}

err = builder.SetMsgs(msg)
if err != nil {
b.logger.Error("builder.SetMsgs failed", "error", err.Error())
return false
}

// Fetch minimun gas price to calculate fees using the configuration.
minGasPrices := b.cfg.GetMinGasPrices()
if len(minGasPrices) == 0 || minGasPrices.Empty() {
b.logger.Debug("the minimun fee is not set")
return false
}
minGasPriceValue := minGasPrices[0].Amount
denom := minGasPrices[0].Denom

delCommonAddr := common.BytesToAddress(delAddr.Bytes())
nonce, err := b.GetTransactionCount(delCommonAddr, rpc.EthPendingBlockNumber)
if err != nil {
b.logger.Debug("failed to get nonce", "error", err.Error())
return false
}

txFactory := tx.Factory{}
txFactory = txFactory.
WithChainID(b.clientCtx.ChainID).
WithKeybase(b.clientCtx.Keyring).
WithTxConfig(b.clientCtx.TxConfig).
WithSequence(uint64(*nonce)).
WithGasAdjustment(1.25)

_, gas, err := tx.CalculateGas(b.clientCtx, txFactory, msg)
if err != nil {
b.logger.Debug("failed to calculate gas", "error", err.Error())
return false
}

txFactory = txFactory.WithGas(gas)

value := new(big.Int).SetUint64(gas * minGasPriceValue.Ceil().TruncateInt().Uint64())
fees := sdk.Coins{sdk.NewCoin(denom, sdkmath.NewIntFromBigInt(value))}
builder.SetFeeAmount(fees)
builder.SetGasLimit(gas)

keyInfo, err := b.clientCtx.Keyring.KeyByAddress(delAddr)
if err != nil {
b.logger.Debug("failed to get the wallet address using the keyring", "error", err.Error())
return false
}

if err := tx.Sign(txFactory, keyInfo.Name, builder, false); err != nil {
b.logger.Debug("failed to sign tx", "error", err.Error())
return false
}

// Encode transaction by default Tx encoder
txEncoder := b.clientCtx.TxConfig.TxEncoder()
txBytes, err := txEncoder(builder.GetTx())
if err != nil {
b.logger.Debug("failed to encode eth tx using default encoder", "error", err.Error())
return false
}

tmHash := common.BytesToHash(tmtypes.Tx(txBytes).Hash())

// Broadcast transaction in sync mode (default)
// NOTE: If error is encountered on the node, the broadcast will not return an error
syncCtx := b.clientCtx.WithBroadcastMode(flags.BroadcastSync)
rsp, err := syncCtx.BroadcastTx(txBytes)
if rsp != nil && rsp.Code != 0 {
err = errorsmod.ABCIError(rsp.Codespace, rsp.Code, rsp.RawLog)
}
if err != nil {
b.logger.Debug("failed to broadcast tx", "error", err.Error())
return false
}

b.logger.Debug("broadcasted tx to set miner withdraw address (etherbase)", "hash", tmHash.String())
return true
}

// ImportRawKey armors and encrypts a given raw hex encoded ECDSA key and stores it into the key directory.
// The name of the key will have the format "personal_<length-keys>", where <length-keys> is the total number of
// keys stored on the keyring.
//
// NOTE: The key will be both armored and encrypted using the same passphrase.
func (b *Backend) ImportRawKey(privkey, password string) (common.Address, error) {
priv, err := crypto.HexToECDSA(privkey)
if err != nil {
return common.Address{}, err
}

privKey := &ethsecp256k1.PrivKey{Key: crypto.FromECDSA(priv)}

addr := sdk.AccAddress(privKey.PubKey().Address().Bytes())
ethereumAddr := common.BytesToAddress(addr)

// return if the key has already been imported
if _, err := b.clientCtx.Keyring.KeyByAddress(addr); err == nil {
return ethereumAddr, nil
}

// ignore error as we only care about the length of the list
list, _ := b.clientCtx.Keyring.List() // #nosec G703
privKeyName := fmt.Sprintf("personal_%d", len(list))

armor := sdkcrypto.EncryptArmorPrivKey(privKey, password, ethsecp256k1.KeyType)

if err := b.clientCtx.Keyring.ImportPrivKey(privKeyName, armor, password); err != nil {
return common.Address{}, err
}

b.logger.Info("key successfully imported", "name", privKeyName, "address", ethereumAddr.String())

return ethereumAddr, nil
}

// ListAccounts will return a list of addresses for accounts this node manages.
func (b *Backend) ListAccounts() ([]common.Address, error) {
addrs := []common.Address{}

list, err := b.clientCtx.Keyring.List()
if err != nil {
return nil, err
}

for _, info := range list {
pubKey, err := info.GetPubKey()
if err != nil {
return nil, err
}
addrs = append(addrs, common.BytesToAddress(pubKey.Address()))
}

return addrs, nil
}

// NewAccount will create a new account and returns the address for the new account.
func (b *Backend) NewMnemonic(uid string,
_ keyring.Language,
hdPath,
bip39Passphrase string,
algo keyring.SignatureAlgo,
) (*keyring.Record, error) {
info, _, err := b.clientCtx.Keyring.NewMnemonic(uid, keyring.English, hdPath, bip39Passphrase, algo)
if err != nil {
return nil, err
}
return info, err
}

// SetGasPrice sets the minimum accepted gas price for the miner.
// NOTE: this function accepts only integers to have the same interface than go-eth
// to use float values, the gas prices must be configured using the configuration file
func (b *Backend) SetGasPrice(gasPrice hexutil.Big) bool {
appConf, err := config.GetConfig(b.clientCtx.Viper)
if err != nil {
b.logger.Debug("could not get the server config", "error", err.Error())
return false
}

var unit string
minGasPrices := appConf.GetMinGasPrices()

// fetch the base denom from the sdk Config in case it's not currently defined on the node config
if len(minGasPrices) == 0 || minGasPrices.Empty() {
var err error
unit, err = sdk.GetBaseDenom()
if err != nil {
b.logger.Debug("could not get the denom of smallest unit registered", "error", err.Error())
return false
}
} else {
unit = minGasPrices[0].Denom
}

c := sdk.NewDecCoin(unit, sdkmath.NewIntFromBigInt(gasPrice.ToInt()))

appConf.SetMinGasPrices(sdk.DecCoins{c})
sdkconfig.WriteConfigFile(b.clientCtx.Viper.ConfigFileUsed(), appConf)
b.logger.Info("Your configuration file was modified. Please RESTART your node.", "gas-price", c.String())
return true
}

// UnprotectedAllowed returns the node configuration value for allowing
// unprotected transactions (i.e not replay-protected)
func (b Backend) UnprotectedAllowed() bool {
Expand Down
Loading

0 comments on commit 2a6c81a

Please sign in to comment.