Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RPC and WS endpoints share the same port #187

Merged
merged 9 commits into from
Sep 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
155 changes: 77 additions & 78 deletions cmd/client/main.go

Large diffs are not rendered by default.

51 changes: 10 additions & 41 deletions cmd/daemon/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,6 @@ const (
defaultRPCPort = 5005
defaultXMRTakerRPCPort = 5001
defaultXMRMakerRPCPort = 5002

defaultWSPort = 6005
defaultXMRTakerWSPort = 8081
defaultXMRMakerWSPort = 8082
)

var (
Expand All @@ -59,7 +55,6 @@ var (

const (
flagRPCPort = "rpc-port"
flagWSPort = "ws-port"
flagDataDir = "data-dir"
flagLibp2pKey = "libp2p-key"
flagLibp2pPort = "libp2p-port"
Expand Down Expand Up @@ -88,20 +83,17 @@ const (

var (
app = &cli.App{
Name: "swapd",
Usage: "A program for doing atomic swaps between ETH and XMR",
Action: runDaemon,
Name: "swapd",
Usage: "A program for doing atomic swaps between ETH and XMR",
Action: runDaemon,
EnableBashCompletion: true,
Suggest: true,
Flags: []cli.Flag{
&cli.UintFlag{
Name: flagRPCPort,
Usage: "Port for the daemon RPC server to run on",
Value: defaultRPCPort,
},
&cli.UintFlag{
Name: flagWSPort,
Usage: "Port for the daemon RPC websockets server to run on",
Value: defaultWSPort,
},
&cli.StringFlag{
Name: flagDataDir,
Usage: "Path to store swap artifacts", //nolint:misspell
Expand Down Expand Up @@ -198,8 +190,7 @@ var (

func main() {
if err := app.Run(os.Args); err != nil {
log.Error(err)
os.Exit(1)
log.Fatal(err)
}
}

Expand Down Expand Up @@ -387,21 +378,11 @@ func (d *daemon) make(c *cli.Context) error {
rpcPort = defaultXMRMakerRPCPort
}
}

wsPort := uint16(c.Uint(flagWSPort))
if !c.IsSet(flagWSPort) {
switch {
case devXMRTaker:
wsPort = defaultXMRTakerWSPort
case devXMRMaker:
wsPort = defaultXMRMakerWSPort
}
}
listenAddr := fmt.Sprintf("127.0.0.1:%d", rpcPort)

rpcCfg := &rpc.Config{
Ctx: d.ctx,
Port: rpcPort,
WsPort: wsPort,
Address: listenAddr,
Net: host,
XMRTaker: a,
XMRMaker: b,
Expand All @@ -413,20 +394,8 @@ func (d *daemon) make(c *cli.Context) error {
return err
}

errCh := s.Start()
go func() {
select {
case <-d.ctx.Done():
return
case err := <-errCh:
log.Errorf("failed to start RPC server: %s", err)
d.cancel()
os.Exit(1)
}
}()
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Start() now blocks and it internally uses the context that was passed to rpcCfg.


log.Infof("started swapd with data-dir %s", cfg.DataDir)
return nil
log.Infof("starting swapd with data-dir %s", cfg.DataDir)
return s.Start()
}

func errFlagsMutuallyExclusive(flag1, flag2 string) error {
Expand Down
28 changes: 24 additions & 4 deletions cmd/daemon/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import (
"context"
"flag"
"fmt"
"sync"
"testing"
"time"

"github.com/stretchr/testify/require"
"github.com/urfave/cli/v2"
Expand Down Expand Up @@ -65,8 +67,17 @@ func TestDaemon_DevXMRTaker(t *testing.T) {
cancel: cancel,
}

err := d.make(c)
require.NoError(t, err)
var wg sync.WaitGroup
wg.Add(1)

go func() {
err := d.make(c) // blocks on RPC server start
require.ErrorIs(t, err, context.Canceled)
wg.Done()
}()
time.Sleep(500 * time.Millisecond) // let the server start
cancel()
wg.Wait()
}

func TestDaemon_DevXMRMaker(t *testing.T) {
Expand All @@ -88,8 +99,17 @@ func TestDaemon_DevXMRMaker(t *testing.T) {
cancel: cancel,
}

err := d.make(c)
require.NoError(t, err)
var wg sync.WaitGroup
wg.Add(1)

go func() {
err := d.make(c) // blocks on RPC server start
require.ErrorIs(t, err, context.Canceled)
wg.Done()
}()
time.Sleep(500 * time.Millisecond) // let the server start
cancel()
wg.Wait()
}

func Test_expandBootnodes(t *testing.T) {
Expand Down
8 changes: 5 additions & 3 deletions cmd/recover/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,11 @@ var (

var (
app = &cli.App{
Name: "swaprecover",
Usage: "A program for recovering swap funds due to unexpected shutdowns",
Action: runRecover,
Name: "swaprecover",
Usage: "A program for recovering swap funds due to unexpected shutdowns",
Action: runRecover,
EnableBashCompletion: true,
Suggest: true,
Flags: []cli.Flag{
&cli.StringFlag{
Name: flagEnv,
Expand Down
7 changes: 7 additions & 0 deletions common/coins.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package common
import (
"math"
"math/big"
"strconv"
)

var (
Expand Down Expand Up @@ -73,3 +74,9 @@ func (a EtherAmount) ToDecimals(decimals uint8) float64 {
func (a EtherAmount) String() string {
return a.BigInt().String()
}

// FmtFloat creates a string from a floating point value that keeps maximum precision,
// does not use exponent notation, and has no trailing zeros after the decimal point.
func FmtFloat(f float64) string {
return strconv.FormatFloat(f, 'f', -1, 64)
}
4 changes: 2 additions & 2 deletions common/coins_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func TestEtherAmount(t *testing.T) {

func TestToDecimals(t *testing.T) {
val := NewEtherAmount(123456)
require.Equal(t, fmt.Sprint(val.ToDecimals(5)), "1.23456")
require.Equal(t, "1.23456", FmtFloat(val.ToDecimals(5)))
val = NewEtherAmount(1234567890)
require.Equal(t, fmt.Sprint(val.ToDecimals(6)), "1234.56789")
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The expected/actual values here were reversed and it seemed like as good a place as any to use the FmtFloat function added by this PR. I've never used fmt.Sprint like above, but I imagine it behaves like "%v" in a formatted string, which in some cases prints undesirable exponent notation.

require.Equal(t, "1234.56789", FmtFloat(val.ToDecimals(6)))
}
8 changes: 4 additions & 4 deletions docs/local.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ Create a wallet for "Bob", who will own XMR later on:
./monero-wallet-cli // you will be prompted to create a wallet. In the next steps, we will go with "Bob", without password. Remember the name and optionally the password for the upcoming steps
```

You do not need to mine blocks, and you can exit the the wallet-cli once Bob's account has been created by typing "exit".
You do not need to mine blocks, and you can exit the wallet-cli once Bob's account has been created by typing "exit".

Start monero-wallet-rpc for Bob on port 18083. Make sure `--wallet-dir` corresponds to the directory the wallet from the previous step is in:
```bash
Expand Down Expand Up @@ -98,13 +98,13 @@ In terminal 3, we will interact with the swap daemon using `swapcli`.

Firstly, we need Bob to make an offer and advertise it, so that Alice can take it:
```bash
./swapcli make --min-amount 0.1 --max-amount 1 --exchange-rate 0.05 --daemon-addr=http://localhost:5002
./swapcli make --min-amount 0.1 --max-amount 1 --exchange-rate 0.05 --swapd-port 5002
# Published offer with ID cf4bf01a0775a0d13fa41b14516e4b89034300707a1754e0d99b65f6cb6fffb9
```

Alternatively, you can make the offer via websockets and get notified when the swap is taken:
```bash
./swapcli make --min-amount 0.1 --max-amount 1 --exchange-rate 0.05 --daemon-addr=ws://localhost:8082 --subscribe
./swapcli make --min-amount 0.1 --max-amount 1 --exchange-rate 0.05 --swapd-port 5002 --subscribe
```

Now, we can have Alice begin discovering peers who have offers advertised.
Expand All @@ -127,7 +127,7 @@ Now, we can tell Alice to initiate the protocol w/ the peer (Bob), the offer (co

Alternatively, you can take the offer via websockets and get notified when the swap status updates:
```bash
./swapcli take --multiaddr /ip4/127.0.0.1/tcp/9934/p2p/12D3KooWHLUrLnJtUbaGzTSi6azZavKhNgUZTtSiUZ9Uy12v1eZ7 --offer-id cf4bf01a0775a0d13fa41b14516e4b89034300707a1754e0d99b65f6cb6fffb9 --provides-amount 0.05 --subscribe --daemon-addr=ws://localhost:8081
./swapcli take --multiaddr /ip4/127.0.0.1/tcp/9934/p2p/12D3KooWHLUrLnJtUbaGzTSi6azZavKhNgUZTtSiUZ9Uy12v1eZ7 --offer-id cf4bf01a0775a0d13fa41b14516e4b89034300707a1754e0d99b65f6cb6fffb9 --provides-amount 0.05 --subscribe --swapd-port 5001
```

If all goes well, you should see Alice and Bob successfully exchange messages and execute the swap protocol. The result is that Alice now owns the private key to a Monero account (and is the only owner of that key) and Bob has the ETH transferred to him. On Alice's side, a Monero wallet will be generated in the `--wallet-dir` provided in the `monero-wallet-rpc` step for Alice.
Expand Down
8 changes: 4 additions & 4 deletions docs/rpc.md
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ Returns:

Example:
```bash
wscat -c ws://localhost:8081
wscat -c ws://localhost:5001/ws
# Connected (press CTRL+C to quit)
# > {"jsonrpc":"2.0", "method":"swap_subscribeStatus", "params": {"id": "7492ceb4d0f5f45ecd5d06923b35cae406d1406cd685ce1ba184f2a40c683ac2"}, "id": 0}
# < {"jsonrpc":"2.0","result":{"stage":"ETHLocked"},"error":null,"id":null}
Expand All @@ -282,7 +282,7 @@ Returns:

Example (including notifications when swap is taken):
```bash
wscat -c ws://localhost:8082
wscat -c ws://localhost:5002/ws
# Connected (press CTRL+C to quit)
# > {"jsonrpc":"2.0", "method":"net_makeOfferAndSubscribe", "params": {"minimumAmount": 0.1, "maximumAmount": 1, "exchangeRate": 0.05}, "id": 0}
# < {"jsonrpc":"2.0","result":{"offerID":"cf4bf01a0775a0d13fa41b14516e4b89034300707a1754e0d99b65f6cb6fffb9"},"error":null,"id":null}
Expand All @@ -308,12 +308,12 @@ Returns:

Example:
```bash
wscat -c ws://localhost:8081
wscat -c ws://localhost:5001/ws
# Connected (press CTRL+C to quit)
# > {"jsonrpc":"2.0", "method":"net_takeOfferAndSubscribe", "params": {"multiaddr": "/ip4/192.168.0.101/tcp/9934/p2p/12D3KooWHLUrLnJtUbaGzTSi6azZavKhNgUZTtSiUZ9Uy12v1eZ7", "offerID": "cf4bf01a0775a0d13fa41b14516e4b89034300707a1754e0d99b65f6cb6fffb9", "providesAmount": 0.05}, "id": 0}
# < {"jsonrpc":"2.0","result":{"id":0},"error":null,"id":null}
# < {"jsonrpc":"2.0","result":{"stage":"ExpectingKeys"},"error":null,"id":null}
# < {"jsonrpc":"2.0","result":{"stage":"ETHLocked"},"error":null,"id":null}
# < {"jsonrpc":"2.0","result":{"stage":"ContractReady"},"error":null,"id":null}
# < {"jsonrpc":"2.0","result":{"stage":"Success"},"error":null,"id":null}
```
```
8 changes: 4 additions & 4 deletions docs/stagenet.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ yarn start

1. Search for existing XMR offers using `swapcli`:
```bash
./swapcli discover --provides XMR --search-time 3 --daemon-addr=http://localhost:5005
./swapcli discover --provides XMR --search-time 3 --swapd-port 5001
# [[/ip4/127.0.0.1/tcp/9934/p2p/12D3KooWC547RfLcveQi1vBxACjnT6Uv15V11ortDTuxRWuhubGv /ip4/127.0.0.1/tcp/9934/p2p/12D3KooWC547RfLcveQi1vBxACjnT6Uv15V11ortDTuxRWuhubGv]]
```

Expand All @@ -113,7 +113,7 @@ yarn start

3. b. Alternatively, you can take the offer via websockets and get notified when the swap status updates:
```bash
./swapcli take --multiaddr /ip4/127.0.0.1/tcp/9934/p2p/12D3KooWHLUrLnJtUbaGzTSi6azZavKhNgUZTtSiUZ9Uy12v1eZ7 --offer-id cf4bf01a0775a0d13fa41b14516e4b89034300707a1754e0d99b65f6cb6fffb9 --provides-amount 0.05 --subscribe --daemon-addr=ws://localhost:8081
./swapcli take --multiaddr /ip4/127.0.0.1/tcp/9934/p2p/12D3KooWHLUrLnJtUbaGzTSi6azZavKhNgUZTtSiUZ9Uy12v1eZ7 --offer-id cf4bf01a0775a0d13fa41b14516e4b89034300707a1754e0d99b65f6cb6fffb9 --provides-amount 0.05 --subscribe --swapd-port 5001
```

If all goes well, you should see the node execute the swap protocol. If the swap ends successfully, a Monero wallet will be generated in the `--wallet-dir` provided in the `monero-wallet-rpc` step (so `./node-keys`) named `swap-deposit-wallet`. This wallet will contained the received XMR.
Expand All @@ -140,13 +140,13 @@ If you don't have any luck with these, please message me on twitter/reddit (@eli

4. a. Make an offer with `swapcli`:
```bash
./swapcli make --min-amount 0.1 --max-amount 1 --exchange-rate 0.5 --daemon-addr http://localhost:5005
./swapcli make --min-amount 0.1 --max-amount 1 --exchange-rate 0.5 --swapd-port 5001
# Published offer with ID cf4bf01a0775a0d13fa41b14516e4b89034300707a1754e0d99b65f6cb6fffb9
```

4. b. Alternatively, make an offer and subscribe to updates on it with `swapcli`:
```bash
./swapcli make --min-amount 0.1 --max-amount 1 --exchange-rate 0.5 --daemon-addr ws://localhost:6005 --subscribe
./swapcli make --min-amount 0.1 --max-amount 1 --exchange-rate 0.5 --swapd-port 5001 --subscribe
# Published offer with ID cf4bf01a0775a0d13fa41b14516e4b89034300707a1754e0d99b65f6cb6fffb9
```

Expand Down
12 changes: 7 additions & 5 deletions monero/wallet_client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ func TestClient_Transfer(t *testing.T) {
require.NoError(t, err)

daemon := NewDaemonClient(common.DefaultMoneroDaemonEndpoint)
_ = daemon.GenerateBlocks(xmrmakerAddr.Address, 512)

time.Sleep(time.Second * 10)
err = daemon.GenerateBlocks(xmrmakerAddr.Address, 512)
require.NoError(t, err)
require.NoError(t, cXMRMaker.Refresh())

balance, err := cXMRMaker.GetBalance(0)
require.NoError(t, err)
Expand Down Expand Up @@ -76,12 +76,14 @@ func TestClient_Transfer(t *testing.T) {
break
}

_ = daemon.GenerateBlocks(xmrmakerAddr.Address, 1)
time.Sleep(time.Second)
err = daemon.GenerateBlocks(xmrmakerAddr.Address, 1)
require.NoError(t, err)
require.NoError(t, cXMRMaker.Refresh())
}

err = daemon.GenerateBlocks(xmrmakerAddr.Address, 16)
require.NoError(t, err)
require.NoError(t, cXMRMaker.Refresh())

// generate spend account for A+B
skAKPriv := mcrypto.SumPrivateSpendKeys(kpA.SpendKey(), kpB.SpendKey())
Expand Down
13 changes: 13 additions & 0 deletions net/discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,19 @@ func newDiscovery(ctx context.Context, h libp2phost.Host, bnsFunc func() []peer.
dual.DHTOption(kaddht.Mode(kaddht.ModeAutoServer)),
}

//
// There is libp2p bug when calling `dual.New` with a cancelled context creating a panic,
// so we added the extra guard below:
// Panic: https://github.com/jbenet/goprocess/blob/v0.1.4/impl-mutex.go#L99
// Caller: https://github.com/libp2p/go-libp2p-kad-dht/blob/v0.17.0/dht.go#L222
//
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
// not cancelled, continue on
}
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was mildly painful. We were introducing a context cancel in the TestDaemon_DevXMR[MT]aker tests in cmd/daemon to stop the http server and it was triggering a panic in this libp2p code. Apparently, this libp2p code has really slow startup times, as I even tried sleeping for a 2 whole seconds before issuing the context cancel and I was still getting panics.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good to know, also yeah that's painful


dht, err := dual.New(ctx, h, dhtOpts...)
if err != nil {
return nil, err
Expand Down
14 changes: 8 additions & 6 deletions protocol/xmrmaker/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"errors"
"fmt"
"strconv"

"github.com/athanorlabs/atomic-swap/common"
)

var (
Expand Down Expand Up @@ -41,8 +43,8 @@ type errBalanceTooLow struct {

func (e errBalanceTooLow) Error() string {
return fmt.Sprintf("balance of %s XMR is below provided %s XMR",
strconv.FormatFloat(e.unlockedBalance, 'f', -1, 64),
strconv.FormatFloat(e.providedAmount, 'f', -1, 64),
common.FmtFloat(e.unlockedBalance),
common.FmtFloat(e.providedAmount),
)
}

Expand All @@ -53,8 +55,8 @@ type errAmountProvidedTooLow struct {

func (e errAmountProvidedTooLow) Error() string {
return fmt.Sprintf("%s XMR provided by taker is under offer minimum of %s XMR",
strconv.FormatFloat(e.providedAmount, 'f', -1, 64),
strconv.FormatFloat(e.minAmount, 'f', -1, 64),
common.FmtFloat(e.providedAmount),
common.FmtFloat(e.minAmount),
)
}

Expand All @@ -65,8 +67,8 @@ type errAmountProvidedTooHigh struct {

func (e errAmountProvidedTooHigh) Error() string {
return fmt.Sprintf("%s XMR provided by taker is over offer maximum of %s XMR",
strconv.FormatFloat(e.providedAmount, 'f', -1, 64),
strconv.FormatFloat(e.maxAmount, 'f', -1, 64),
common.FmtFloat(e.providedAmount),
common.FmtFloat(e.maxAmount),
)
}

Expand Down
Loading