Skip to content

Commit

Permalink
refactor: partial commit from #2037. Remove mocks
Browse files Browse the repository at this point in the history
  • Loading branch information
Unique-Divine committed Sep 16, 2024
1 parent 5085dad commit 3620875
Show file tree
Hide file tree
Showing 26 changed files with 349 additions and 6,496 deletions.
413 changes: 1 addition & 412 deletions eth/rpc/backend/account_info_test.go

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion eth/rpc/backend/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func NewBackend(
}

// CosmosBackend: Currently unused. Backend functionality for the shared
// "cosmos" RPC namespace. Implements [BackendI] in combination with [EVMBackend].
// "cosmos" RPC namespace. Implements [BackendI] in combination with [Backend].
// TODO: feat(eth): Implement the cosmos JSON-RPC defined by Wallet Connect V2:
// https://docs.walletconnect.com/2.0/json-rpc/cosmos.
type CosmosBackend interface {
Expand Down
243 changes: 75 additions & 168 deletions eth/rpc/backend/backend_suite_test.go
Original file line number Diff line number Diff line change
@@ -1,203 +1,110 @@
package backend
package backend_test

import (
"bufio"
"math/big"
"os"
"path/filepath"
"testing"

dbm "github.com/cometbft/cometbft-db"
"crypto/ecdsa"

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"
gethcommon "github.com/ethereum/go-ethereum/common"
gethcore "github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/params"
"github.com/stretchr/testify/suite"

"github.com/NibiruChain/nibiru/v2/app"
"github.com/NibiruChain/nibiru/v2/eth"
"github.com/NibiruChain/nibiru/v2/eth/crypto/hd"
"github.com/NibiruChain/nibiru/v2/eth/encoding"
"github.com/NibiruChain/nibiru/v2/eth/indexer"
"github.com/NibiruChain/nibiru/v2/x/evm/evmtest"

"github.com/NibiruChain/nibiru/v2/eth/rpc"
"github.com/NibiruChain/nibiru/v2/eth/rpc/backend/mocks"
"github.com/NibiruChain/nibiru/v2/x/evm"
evmtest "github.com/NibiruChain/nibiru/v2/x/evm/evmtest"

"github.com/NibiruChain/nibiru/v2/app"
"github.com/NibiruChain/nibiru/v2/app/appconst"
"github.com/NibiruChain/nibiru/v2/eth"
"github.com/NibiruChain/nibiru/v2/eth/rpc/backend"

"github.com/NibiruChain/nibiru/v2/x/common/testutil/genesis"
"github.com/NibiruChain/nibiru/v2/x/common/testutil/testapp"
"github.com/NibiruChain/nibiru/v2/x/common/testutil/testnetwork"
)

var recipient = evmtest.NewEthPrivAcc().EthAddr
var amountToSend = evm.NativeToWei(big.NewInt(1))
var transferTxBlockNumber rpc.BlockNumber
var transferTxHash gethcommon.Hash

type BackendSuite struct {
suite.Suite

backend *Backend
from common.Address
acc sdk.AccAddress
signer keyring.Signer
cfg testnetwork.Config
network *testnetwork.Network
node *testnetwork.Validator
fundedAccPrivateKey *ecdsa.PrivateKey
fundedAccEthAddr gethcommon.Address
fundedAccNibiAddr sdk.AccAddress
backend *backend.Backend
ethChainID *big.Int
}

func TestBackendSuite(t *testing.T) {
suite.Run(t, new(BackendSuite))
}

const ChainID = eth.EIP155ChainID_Testnet

// SetupTest is executed before every BackendTestSuite test
func (s *BackendSuite) SetupTest() {
ctx := server.NewDefaultContext()
ctx.Viper.Set("telemetry.global-labels", []interface{}{})

baseDir := s.T().TempDir()
nodeDirName := "node"
clientDir := filepath.Join(baseDir, nodeDirName, "nibirucli")
keyRing, err := s.generateTestKeyring(clientDir)
if err != nil {
panic(err)
}

// Create Account with set sequence
s.acc = sdk.AccAddress(evmtest.NewEthPrivAcc().EthAddr.Bytes())
accounts := map[string]client.TestAccount{}
accounts[s.acc.String()] = client.TestAccount{
Address: s.acc,
Num: uint64(1),
Seq: uint64(1),
}

ethAcc := evmtest.NewEthPrivAcc()
from, priv := ethAcc.EthAddr, ethAcc.PrivKey
s.from = from
s.signer = evmtest.NewSigner(priv)
s.Require().NoError(err)

encCfg := encoding.MakeConfig(app.ModuleBasics)
evm.RegisterInterfaces(encCfg.InterfaceRegistry)
eth.RegisterInterfaces(encCfg.InterfaceRegistry)
clientCtx := client.Context{}.WithChainID(ChainID).
WithHeight(1).
WithTxConfig(encCfg.TxConfig).
WithKeyringDir(clientDir).
WithKeyring(keyRing).
WithAccountRetriever(client.TestAccountRetriever{Accounts: accounts})

allowUnprotectedTxs := false
idxer := indexer.NewKVIndexer(dbm.NewMemDB(), ctx.Logger, clientCtx)

s.backend = NewBackend(ctx, ctx.Logger, clientCtx, allowUnprotectedTxs, idxer)
s.backend.cfg.JSONRPC.GasCap = 0
s.backend.cfg.JSONRPC.EVMTimeout = 0
s.backend.queryClient.QueryClient = mocks.NewEVMQueryClient(s.T())
s.backend.clientCtx.Client = mocks.NewClient(s.T())
s.backend.ctx = rpc.NewContextWithHeight(1)

s.backend.clientCtx.Codec = encCfg.Codec
}
func (s *BackendSuite) SetupSuite() {
testapp.EnsureNibiruPrefix()

// buildEthereumTx returns an example legacy Ethereum transaction
func (s *BackendSuite) buildEthereumTx() (*evm.MsgEthereumTx, []byte) {
ethTxParams := evm.EvmTxArgs{
ChainID: s.backend.chainID,
Nonce: uint64(0),
To: &common.Address{},
Amount: big.NewInt(0),
GasLimit: 100000,
GasPrice: big.NewInt(1),
}
msgEthereumTx := evm.NewTx(&ethTxParams)

// A valid msg should have empty `From`
msgEthereumTx.From = s.from.Hex()

txBuilder := s.backend.clientCtx.TxConfig.NewTxBuilder()
err := txBuilder.SetMsgs(msgEthereumTx)
genState := genesis.NewTestGenesisState(app.MakeEncodingConfig())
homeDir := s.T().TempDir()
s.cfg = testnetwork.BuildNetworkConfig(genState)
network, err := testnetwork.New(s.T(), homeDir, s.cfg)
s.Require().NoError(err)
s.network = network
s.node = network.Validators[0]
s.ethChainID = appconst.GetEthChainID(s.node.ClientCtx.ChainID)
s.backend = s.node.EthRpcBackend

bz, err := s.backend.clientCtx.TxConfig.TxEncoder()(txBuilder.GetTx())
s.Require().NoError(err)
return msgEthereumTx, bz
}
testAccPrivateKey, _ := crypto.GenerateKey()
s.fundedAccPrivateKey = testAccPrivateKey
s.fundedAccEthAddr = crypto.PubkeyToAddress(testAccPrivateKey.PublicKey)
s.fundedAccNibiAddr = eth.EthAddrToNibiruAddr(s.fundedAccEthAddr)

// buildFormattedBlock returns a formatted block for testing
func (s *BackendSuite) buildFormattedBlock(
blockRes *tmrpctypes.ResultBlockResults,
resBlock *tmrpctypes.ResultBlock,
fullTx bool,
tx *evm.MsgEthereumTx,
validator sdk.AccAddress,
baseFee *big.Int,
) map[string]interface{} {
header := resBlock.Block.Header
gasLimit := int64(^uint32(0)) // for `MaxGas = -1` (DefaultConsensusParams)
gasUsed := new(big.Int).SetUint64(uint64(blockRes.TxsResults[0].GasUsed))

root := common.Hash{}.Bytes()
receipt := gethcore.NewReceipt(root, false, gasUsed.Uint64())
bloom := gethcore.CreateBloom(gethcore.Receipts{receipt})

ethRPCTxs := []interface{}{}
if tx != nil {
if fullTx {
rpcTx, err := rpc.NewRPCTxFromEthTx(
tx.AsTransaction(),
common.BytesToHash(header.Hash()),
uint64(header.Height),
uint64(0),
baseFee,
s.backend.chainID,
)
s.Require().NoError(err)
ethRPCTxs = []interface{}{rpcTx}
} else {
ethRPCTxs = []interface{}{common.HexToHash(tx.Hash)}
}
}

return rpc.FormatBlock(
header,
resBlock.Block.Size(),
gasLimit,
gasUsed,
ethRPCTxs,
bloom,
common.BytesToAddress(validator.Bytes()),
baseFee,
)
}
funds := sdk.NewCoins(sdk.NewInt64Coin(eth.EthBaseDenom, 100_000_000))

func (s *BackendSuite) generateTestKeyring(clientDir string) (keyring.Keyring, error) {
buf := bufio.NewReader(os.Stdin)
encCfg := encoding.MakeConfig(app.ModuleBasics)
return keyring.New(
sdk.KeyringServiceName(), // appName
keyring.BackendTest, // backend
clientDir, // rootDir
buf, // userInput
encCfg.Codec, // codec
[]keyring.Option{hd.EthSecp256k1Option()}...,
txResp, err := testnetwork.FillWalletFromValidator(
s.fundedAccNibiAddr, funds, s.node, eth.EthBaseDenom,
)
}
s.Require().NoError(err, txResp.TxHash)
s.NoError(s.network.WaitForNextBlock())

func (s *BackendSuite) signAndEncodeEthTx(msgEthereumTx *evm.MsgEthereumTx) []byte {
ethAcc := evmtest.NewEthPrivAcc()
from, priv := ethAcc.EthAddr, ethAcc.PrivKey
signer := evmtest.NewSigner(priv)

queryClient := s.backend.queryClient.QueryClient.(*mocks.EVMQueryClient)
RegisterParamsWithoutHeader(queryClient, 1)
// Send 1 Transfer TX and use the results in the tests
transferTxBlockNumber, transferTxHash = s.sendNibiViaEthTransfer(recipient, amountToSend)
}

ethSigner := gethcore.LatestSigner(s.backend.ChainConfig())
msgEthereumTx.From = from.String()
err := msgEthereumTx.Sign(ethSigner, signer)
// SendNibiViaEthTransfer sends nibi using the eth rpc backend
func (s *BackendSuite) sendNibiViaEthTransfer(
to gethcommon.Address,
amount *big.Int,
) (rpc.BlockNumber, gethcommon.Hash) {
block, err := s.backend.BlockNumber()
s.Require().NoError(err)

tx, err := msgEthereumTx.BuildTx(s.backend.clientCtx.TxConfig.NewTxBuilder(), eth.EthBaseDenom)
s.NoError(err)

signer := gethcore.LatestSignerForChainID(s.ethChainID)
gasPrice := evm.NativeToWei(big.NewInt(1))
tx, err := gethcore.SignNewTx(
s.fundedAccPrivateKey,
signer,
&gethcore.LegacyTx{
To: &to,
Value: amount,
Gas: params.TxGas,
GasPrice: gasPrice,
})
s.Require().NoError(err)

txEncoder := s.backend.clientCtx.TxConfig.TxEncoder()
txBz, err := txEncoder(tx)
txBz, err := tx.MarshalBinary()
s.Require().NoError(err)
txHash, err := s.backend.SendRawTransaction(txBz)
s.Require().NoError(err)
s.Require().NoError(s.network.WaitForNextBlock())

return txBz
return rpc.NewBlockNumber(big.NewInt(int64(block) + 1)), txHash
}
Loading

0 comments on commit 3620875

Please sign in to comment.