Skip to content

Commit

Permalink
server/eth: Allow geth connections using http and ws
Browse files Browse the repository at this point in the history
In order to test the connection using ws, in the eth backend's
rpc_harness_test, the delta node (the only one that has enabled
http and ws) is used to send funds instead of the alpha node.

The rpc_harness_test had pre-existing issues:
- panicing due to registering the test token twice
- incorrectly checking the difference in token balance.
These issues are now fixed.
  • Loading branch information
martonp committed Jan 12, 2023
1 parent 572a8d6 commit 57c1885
Show file tree
Hide file tree
Showing 9 changed files with 54 additions and 33 deletions.
2 changes: 1 addition & 1 deletion client/asset/eth/multirpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ func connectProviders(ctx context.Context, endpoints []string, log dex.Logger, c
// path discrimination, so I won't even try to validate the protocol.
if ec == nil {
var err error
rpcClient, err = rpc.Dial(endpoint)
rpcClient, err = rpc.DialContext(ctx, endpoint)
if err != nil {
log.Errorf("error creating http client for %q: %v", endpoint, err)
continue
Expand Down
1 change: 1 addition & 0 deletions dex/networks/erc20/contracts/TestToken.sol
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ contract TestToken {
_balances[0x4F8eF3892B65ED7fc356fF473a2eF2aE5EC27A06] = 11000000000000000000000;
_balances[0xdd93b447f7eBCA361805eBe056259853F3912E04] = 11000000000000000000000;
_balances[0x1D4F2ee206474B136Af4868B887C7b166693c194] = 11000000000000000000000;
_balances[0xd12aB7cf72CCf1f3882eC99DDc53CD415635C3bE] = 11000000000000000000000;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion dex/networks/eth/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func CheckAPIModules(c *rpc.Client, endpoint string, log dex.Logger, reqModules
for v := range reqModulesMap {
reqs = append(reqs, v)
}
return fmt.Errorf("needed apis not present: %v", strings.Join(reqs, " "))
return fmt.Errorf("needed apis not present: %v.", strings.Join(reqs, " "))
}
sort.Strings(haveModules)
log.Debugf("API endpoints supported by %s: %s", endpoint, strings.Join(haveModules, " "))
Expand Down
2 changes: 1 addition & 1 deletion dex/testing/dcrdex/harness.sh
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ if [ $ETH_ON -eq 0 ]; then
"network": "simnet",
"maxFeeRate": 200,
"swapConf": 2,
"configPath": "${TEST_ROOT}/eth/alpha/node/geth.ipc"
"configPath": "ws://localhost:38557"
},
"DEXTT_simnet": {
"bip44symbol": "dextt.eth",
Expand Down
2 changes: 1 addition & 1 deletion dex/testing/eth/create-node.sh
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ if [ "${SYNC_MODE}" = "snap" ]; then
else
# Start the eth node listening restricted to localhost and our custom
# configuration file.
tmux send-keys -t "$TMUX_WIN_ID" "${NODES_ROOT}/harness-ctl/${NAME} --nodiscover " \
tmux send-keys -t "$TMUX_WIN_ID" "${NODES_ROOT}/harness-ctl/${NAME} --nodiscover --allow-insecure-unlock " \
"--config ${NODE_DIR}/eth.conf --verbosity 5 ${HTTP_OPT} 2>&1 | tee " \
"${NODE_DIR}/${NAME}.log" C-m
fi
4 changes: 2 additions & 2 deletions dex/testing/eth/harness.sh

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions server/asset/eth/eth.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ func unconnectedETH(logger dex.Logger, net dex.Network) (*ETHBackend, error) {

// NewBackend is the exported constructor by which the DEX will import the
// Backend.
func NewBackend(ipc string, logger dex.Logger, net dex.Network) (*ETHBackend, error) {
func NewBackend(endpoint string, logger dex.Logger, net dex.Network) (*ETHBackend, error) {
switch net {
case dex.Simnet:
case dex.Testnet:
Expand All @@ -276,15 +276,15 @@ func NewBackend(ipc string, logger dex.Logger, net dex.Network) (*ETHBackend, er
return nil, fmt.Errorf("unknown network ID: %d", net)
}

if ipc == "" {
ipc = defaultIPC
if endpoint == "" {
endpoint = defaultIPC
}

eth, err := unconnectedETH(logger, net)
if err != nil {
return nil, err
}
eth.node = newRPCClient(eth.net, ipc)
eth.node = newRPCClient(eth.net, endpoint)
return eth, nil
}

Expand Down
31 changes: 21 additions & 10 deletions server/asset/eth/rpcclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"context"
"fmt"
"math/big"
"strings"

"decred.org/dcrdex/dex"
dexeth "decred.org/dcrdex/dex/networks/eth"
Expand All @@ -33,8 +34,8 @@ type ContextCaller interface {
}

type rpcclient struct {
net dex.Network
ipc string
net dex.Network
endpoint string
// ec wraps a *rpc.Client with some useful calls.
ec *ethclient.Client
// caller is a client for raw calls not implemented by *ethclient.Client.
Expand All @@ -48,24 +49,34 @@ type rpcclient struct {
tokens map[uint32]*tokener
}

func newRPCClient(net dex.Network, ipc string) *rpcclient {
func newRPCClient(net dex.Network, endpoint string) *rpcclient {
return &rpcclient{
net: net,
tokens: make(map[uint32]*tokener),
ipc: ipc,
net: net,
tokens: make(map[uint32]*tokener),
endpoint: endpoint,
}
}

// connect connects to an ipc socket. It then wraps ethclient's client and
// bundles commands in a form we can easily use.
func (c *rpcclient) connect(ctx context.Context, log dex.Logger) error {
client, err := rpc.DialIPC(ctx, c.ipc)
if err != nil {
return fmt.Errorf("unable to dial rpc: %v", err)
var client *rpc.Client
var err error
if strings.HasSuffix(c.endpoint, ".ipc") {
client, err = rpc.DialIPC(ctx, c.endpoint)
if err != nil {
return fmt.Errorf("unable to dial ipc: %v", err)
}
} else {
log.Debugf("dialing endpoint: %s", c.endpoint)
client, err = rpc.DialContext(ctx, c.endpoint)
if err != nil {
return fmt.Errorf("unable to dial rpc: %v", err)
}
}

reqModules := []string{"eth", "txpool"}
if err := dexeth.CheckAPIModules(client, c.ipc, log, reqModules); err != nil {
if err := dexeth.CheckAPIModules(client, c.endpoint, log, reqModules); err != nil {
return fmt.Errorf("error checking required modules: %v", err)
}

Expand Down
35 changes: 22 additions & 13 deletions server/asset/eth/rpcclient_harness_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//go:build harness && lgpl

// This test requires that the testnet harness be running and the unix socket
// be located at $HOME/dextest/eth/alpha/node/geth.ipc
// be located at $HOME/dextest/eth/delta/node/geth.ipc

package eth

Expand All @@ -24,12 +24,13 @@ import (
)

var (
homeDir = os.Getenv("HOME")
ipc = filepath.Join(homeDir, "dextest/eth/alpha/node/geth.ipc")
homeDir = os.Getenv("HOME")
// endpoint = filepath.Join(homeDir, "dextest/eth/delta/node/geth.ipc")
endpoint = "ws://localhost:38557"
contractAddrFile = filepath.Join(homeDir, "dextest", "eth", "eth_swap_contract_address.txt")
tokenSwapAddrFile = filepath.Join(homeDir, "dextest", "eth", "erc20_swap_contract_address.txt")
tokenErc20AddrFile = filepath.Join(homeDir, "dextest", "eth", "test_token_contract_address.txt")
alphaAddress = "18d65fb8d60c1199bb1ad381be47aa692b482605"
deltaAddress = "d12ab7cf72ccf1f3882ec99ddc53cd415635c3be"
gammaAddress = "41293c2032bac60aa747374e966f79f575d42379"
ethClient *rpcclient
ctx context.Context
Expand All @@ -40,7 +41,7 @@ func TestMain(m *testing.M) {
run := func() (int, error) {
var cancel context.CancelFunc
ctx, cancel = context.WithCancel(context.Background())
ethClient = newRPCClient(dex.Simnet, ipc)
ethClient = newRPCClient(dex.Simnet, endpoint)
defer func() {
cancel()
ethClient.shutdown()
Expand All @@ -51,7 +52,6 @@ func TestMain(m *testing.M) {
netToken := dexeth.Tokens[testTokenID].NetTokens[dex.Simnet]
netToken.Address = getContractAddrFromFile(tokenErc20AddrFile)
netToken.SwapContracts[0].Address = getContractAddrFromFile(tokenSwapAddrFile)
registerToken(testTokenID, 0)
logger := dex.StdOutLogger("ETHTEST", dex.LevelTrace)

if err := ethClient.connect(ctx, logger); err != nil {
Expand Down Expand Up @@ -131,7 +131,7 @@ func TestAccountBalance(t *testing.T) {
}

func testAccountBalance(t *testing.T, assetID uint32) {
addr := common.HexToAddress(alphaAddress)
addr := common.HexToAddress(deltaAddress)
const vGwei = 1e7

balBefore, err := ethClient.accountBalance(ctx, assetID, addr)
Expand All @@ -140,7 +140,7 @@ func testAccountBalance(t *testing.T, assetID uint32) {
}

if assetID == BipID {
err = tmuxSend(alphaAddress, gammaAddress, vGwei)
err = tmuxSend(deltaAddress, gammaAddress, vGwei)
} else {
err = tmuxSendToken(gammaAddress, vGwei)
}
Expand All @@ -153,9 +153,18 @@ func testAccountBalance(t *testing.T, assetID uint32) {
t.Fatalf("accountBalance error: %v", err)
}

diff := new(big.Int).Sub(balBefore, balAfter)
if diff.Cmp(dexeth.GweiToWei(vGwei)) <= 0 {
t.Fatalf("account balance changed by %d. expected > %d", dexeth.WeiToGwei(diff), uint64(vGwei))
if assetID == BipID {
diff := new(big.Int).Sub(balBefore, balAfter)
if diff.Cmp(dexeth.GweiToWei(vGwei)) <= 0 {
t.Fatalf("account balance changed by %d. expected > %d", dexeth.WeiToGwei(diff), uint64(vGwei))
}
}

if assetID == testTokenID {
diff := new(big.Int).Sub(balBefore, balAfter)
if diff.Cmp(dexeth.GweiToWei(vGwei)) != 0 {
t.Fatalf("account balance changed by %d. expected > %d", dexeth.WeiToGwei(diff), uint64(vGwei))
}
}
}

Expand All @@ -169,11 +178,11 @@ func tmuxRun(cmd string) error {
}

func tmuxSend(from, to string, v uint64) error {
return tmuxRun(fmt.Sprintf("./alpha attach --preload send.js --exec \"send(\\\"%s\\\",\\\"%s\\\",%s)\"", from, to, dexeth.GweiToWei(v)))
return tmuxRun(fmt.Sprintf("./delta attach --preload send.js --exec \"send(\\\"%s\\\",\\\"%s\\\",%s)\"", from, to, dexeth.GweiToWei(v)))
}

func tmuxSendToken(to string, v uint64) error {
return tmuxRun(fmt.Sprintf("./alpha attach --preload loadTestToken.js --exec \"testToken.transfer(\\\"0x%s\\\",%s)\"", to, dexeth.GweiToWei(v)))
return tmuxRun(fmt.Sprintf("./delta attach --preload loadTestToken.js --exec \"testToken.transfer(\\\"0x%s\\\",%s)\"", to, dexeth.GweiToWei(v)))
}

func getContractAddrFromFile(fileName string) common.Address {
Expand Down

0 comments on commit 57c1885

Please sign in to comment.