improve linter and lint code (#58)

This commit is contained in:
noot
2021-12-11 11:26:06 -05:00
committed by GitHub
parent 3ce14925ec
commit d6aba125e4
38 changed files with 511 additions and 263 deletions

99
.golangci.yml Normal file
View File

@@ -0,0 +1,99 @@
run:
# timeout for analysis, e.g. 30s, 5m, default is 1m
deadline: 5m
# list of build tags, all linters use it. Default is empty list.
build-tags:
- integration
# all available settings of specific linters
linters-settings:
govet:
# report about shadowed variables
check-shadowing: true
maligned:
# print struct with more effective memory layout or not, false by default
suggest-new: true
dupl:
# tokens count to trigger issue, 150 by default
threshold: 100
misspell:
# Correct spellings using locale preferences for US or UK.
# Default is to use a neutral variety of English.
# Setting locale to US will correct the British spelling of 'colour' to 'color'.
locale: UK
gocritic:
# Enable multiple checks by tags, run `GL_DEBUG=gocritic golangci-lint` run to see all tags and checks.
# Empty list by default. See https://github.com/go-critic/go-critic#usage -> section "Tags".
enabled-tags:
- performance
settings: # settings passed to gocritic
captLocal: # must be valid enabled check name
paramsOnly: true
rangeValCopy:
sizeThreshold: 32
linters:
enable:
- bodyclose
- depguard
- errcheck
- goconst
- gocyclo
- gofmt
- goimports
- goimports
- goprintffuncname
- gosec
- gosimple
- govet
- ineffassign
- lll
- megacheck
- megacheck
- misspell
- nolintlint
- revive
- staticcheck
- unconvert
- unparam
- varcheck
fast: false
issues:
# List of regexps of issue texts to exclude, empty list by default.
# But independently from this option we use default exclude patterns,
# it can be disabled by `exclude-use-default: false`. To list all
# excluded by default patterns execute `golangci-lint run --help`
#exclude:
# Excluding configuration per-path, per-linter, per-text and per-source
exclude-rules:
# Exclude some linters from running on tests files.
- path: _test\.go
linters:
- gocyclo
- errcheck
- dupl
- gosec
- ineffassign
- text: 'G204: Subprocess launched with variable'
linters:
- gosec
# Independently from option `exclude` we use default exclude patterns,
# it can be disabled by this option. To list all
# excluded by default patterns execute `golangci-lint run --help`.
# Default value for this option is true.
exclude-use-default: false
# Maximum issues count per one linter. Set to 0 to disable. Default is 50.
max-per-linter: 0
# Maximum count of issues with the same text. Set to 0 to disable. Default is 3.
max-same-issues: 0

View File

@@ -6,7 +6,7 @@ import (
"github.com/noot/atomic-swap/common"
"github.com/noot/atomic-swap/net"
"github.com/fatih/color"
"github.com/fatih/color" //nolint:misspell
)
func (a *alice) Provides() common.ProvidesCoin {
@@ -60,7 +60,7 @@ func (a *alice) initiate(providesAmount common.EtherAmount, desiredAmount common
return err
}
// check user's balance and that they actualy have what they will provide
// check user's balance and that they actually have what they will provide
if balance.Cmp(providesAmount.BigInt()) <= 0 {
return errors.New("balance lower than amount to be provided")
}

View File

@@ -49,6 +49,7 @@ type alice struct {
swapState *swapState
}
// Config contains the configuration values for a new Alice instance.
type Config struct {
Ctx context.Context
Basepath string
@@ -64,7 +65,7 @@ type Config struct {
// NewAlice returns a new instance of Alice.
// It accepts an endpoint to a monero-wallet-rpc instance where Alice will generate
// the account in which the XMR will be deposited.
func NewAlice(cfg *Config) (*alice, error) {
func NewAlice(cfg *Config) (*alice, error) { //nolint
pk, err := crypto.HexToECDSA(cfg.EthereumPrivateKey)
if err != nil {
return nil, err

View File

@@ -14,10 +14,10 @@ import (
"github.com/ethereum/go-ethereum/accounts/abi/bind"
ethcommon "github.com/ethereum/go-ethereum/common"
"github.com/fatih/color"
"github.com/fatih/color" //nolint:misspell
)
var nextID uint64 = 0
var nextID uint64
var (
errMissingKeys = errors.New("did not receive Bob's public spend or private view key")
@@ -250,7 +250,8 @@ func (s *swapState) HandleProtocolMessage(msg net.Message) (net.Message, bool, e
// TODO: also check that the balance isn't unlocked only after an unreasonable amount of blocks
if balance.Balance < float64(s.desiredAmount) {
return nil, true, fmt.Errorf("locked XMR amount is less than expected: got %v, expected %v", balance.Balance, float64(s.desiredAmount))
return nil, true, fmt.Errorf("locked XMR amount is less than expected: got %v, expected %v",
balance.Balance, float64(s.desiredAmount))
}
if err := s.alice.client.CloseWallet(); err != nil {

View File

@@ -6,7 +6,7 @@ import (
"github.com/noot/atomic-swap/common"
"github.com/noot/atomic-swap/net"
"github.com/fatih/color"
"github.com/fatih/color" //nolint:misspell
)
func (b *bob) Provides() common.ProvidesCoin {
@@ -35,7 +35,7 @@ func (b *bob) initiate(providesAmount common.MoneroAmount, desiredAmount common.
return err
}
// check user's balance and that they actualy have what they will provide
// check user's balance and that they actually have what they will provide
if balance.UnlockedBalance <= float64(providesAmount) {
return errors.New("balance lower than amount to be provided")
}

View File

@@ -51,6 +51,7 @@ type bob struct {
swapState *swapState
}
// Config contains the configuration values for a new Bob instance.
type Config struct {
Ctx context.Context
Basepath string
@@ -67,7 +68,7 @@ type Config struct {
// NewBob returns a new instance of Bob.
// It accepts an endpoint to a monero-wallet-rpc instance where account 0 contains Bob's XMR.
func NewBob(cfg *Config) (*bob, error) {
func NewBob(cfg *Config) (*bob, error) { //nolint
if cfg.Environment == common.Development && cfg.MoneroDaemonEndpoint == "" {
return nil, errors.New("environment is development, must provide monero daemon endpoint")
}

View File

@@ -13,7 +13,7 @@ import (
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
ethcommon "github.com/ethereum/go-ethereum/common"
"github.com/fatih/color"
"github.com/fatih/color" //nolint:misspell
"github.com/noot/atomic-swap/common"
"github.com/noot/atomic-swap/monero"
@@ -21,7 +21,7 @@ import (
"github.com/noot/atomic-swap/swap-contract"
)
var nextID uint64 = 0
var nextID uint64
var (
errMissingKeys = errors.New("did not receive Alice's public spend or view key")

View File

@@ -56,7 +56,7 @@ func newTestBob(t *testing.T) (*bob, *swapState) {
bobAddr, err := bob.client.GetAddress(0)
require.NoError(t, err)
_ = bob.daemonClient.GenerateBlocks(bobAddr.Address, 61)
_ = bob.daemonClient.GenerateBlocks(bobAddr.Address, 121)
swapState, err := newSwapState(bob, common.MoneroAmount(33), desiredAmout)
require.NoError(t, err)
@@ -84,7 +84,8 @@ func TestSwapState_ClaimFunds(t *testing.T) {
var claimKey [32]byte
copy(claimKey[:], common.Reverse(swapState.privkeys.SpendKey().Public().Bytes()))
swapState.contractAddr, _, swapState.contract, err = swap.DeploySwap(swapState.txOpts, conn, claimKey, [32]byte{}, bob.ethAddress, defaultTimeoutDuration)
swapState.contractAddr, _, swapState.contract, err = swap.DeploySwap(swapState.txOpts, conn,
claimKey, [32]byte{}, bob.ethAddress, defaultTimeoutDuration)
require.NoError(t, err)
_, err = swapState.contract.SetReady(swapState.txOpts)
@@ -118,7 +119,8 @@ func TestSwapState_handleSendKeysMessage(t *testing.T) {
require.Equal(t, alicePubKeys.ViewKey().Hex(), s.alicePublicKeys.ViewKey().Hex())
}
func deploySwap(t *testing.T, bob *bob, swapState *swapState, refundKey [32]byte, amount *big.Int, timeout time.Duration) (ethcommon.Address, *swap.Swap) {
func deploySwap(t *testing.T, bob *bob, swapState *swapState, refundKey [32]byte, amount *big.Int,
timeout time.Duration) (ethcommon.Address, *swap.Swap) {
conn, err := ethclient.Dial(common.DefaultEthEndpoint)
require.NoError(t, err)

View File

@@ -7,6 +7,7 @@ import (
"github.com/noot/atomic-swap/rpcclient"
)
// Addresses calls net_addresses.
func (c *Client) Addresses() ([]string, error) {
const (
method = "net_addresses"

View File

@@ -1,9 +1,11 @@
package client
// Client represents a swap client, used to interact with a swap daemon via JSON-RPC calls.
type Client struct {
endpoint string
}
// NewClient ...
func NewClient(endpoint string) *Client {
return &Client{
endpoint: endpoint,

View File

@@ -8,6 +8,7 @@ import (
"github.com/noot/atomic-swap/rpcclient"
)
// Discover calls net_discover.
func (c *Client) Discover(provides common.ProvidesCoin, searchTime uint64) ([][]string, error) {
const (
method = "net_discover"

View File

@@ -9,7 +9,9 @@ import (
"github.com/noot/atomic-swap/rpcclient"
)
func (c *Client) Initiate(maddr string, provides common.ProvidesCoin, providesAmount, desiredAmount float64) (bool, error) {
// Initiate calls net_initiate.
func (c *Client) Initiate(maddr string, provides common.ProvidesCoin,
providesAmount, desiredAmount float64) (bool, error) {
const (
method = "net_initiate"
)

View File

@@ -7,6 +7,7 @@ import (
"github.com/noot/atomic-swap/rpcclient"
)
// Query calls net_query.
func (c *Client) Query(maddr string) (*rpc.QueryPeerResponse, error) {
const (
method = "net_queryPeer"

View File

@@ -62,7 +62,7 @@ var (
},
&cli.StringFlag{
Name: "basepath",
Usage: "path to store swap artifacts",
Usage: "path to store swap artefacts",
},
&cli.StringFlag{
Name: "libp2p-key",
@@ -140,13 +140,13 @@ func main() {
}
}
func runDaemon(c *cli.Context) error {
var (
moneroEndpoint, daemonEndpoint, ethEndpoint, ethPrivKeyFile, ethPrivKey string
env common.Environment
cfg common.Config
)
type protocolHandler interface {
net.Handler
rpc.Protocol
SetMessageSender(net.MessageSender)
}
func runDaemon(c *cli.Context) error {
isAlice := c.Bool("alice")
isBob := c.Bool("bob")
@@ -154,63 +154,9 @@ func runDaemon(c *cli.Context) error {
return errors.New("must specify only one of --alice or --bob")
}
switch c.String("env") {
case "mainnet":
env = common.Mainnet
cfg = common.MainnetConfig
case "stagenet":
env = common.Stagenet
cfg = common.StagenetConfig
case "dev":
env = common.Development
cfg = common.DevelopmentConfig
case "":
env = defaultEnvironment
cfg = common.DevelopmentConfig
default:
return errors.New("--env must be one of mainnet, stagenet, or dev")
}
if c.String("monero-endpoint") != "" {
moneroEndpoint = c.String("monero-endpoint")
} else {
if isAlice {
moneroEndpoint = common.DefaultAliceMoneroEndpoint
} else {
moneroEndpoint = common.DefaultBobMoneroEndpoint
}
}
if c.String("ethereum-endpoint") != "" {
ethEndpoint = c.String("ethereum-endpoint")
} else {
ethEndpoint = common.DefaultEthEndpoint
}
// TODO: if env isn't development, require a private key
if c.String("ethereum-privkey") != "" {
ethPrivKeyFile = c.String("ethereum-privkey")
key, err := os.ReadFile(filepath.Clean(ethPrivKeyFile))
if err != nil {
return fmt.Errorf("failed to read ethereum-privkey file: %w", err)
}
if key[len(key)-1] == '\n' {
key = key[:len(key)-1]
}
ethPrivKey = string(key)
} else {
if env != common.Development {
return errors.New("must provide --ethereum-privkey file for non-development environment")
}
log.Warn("no ethereum private key file provided, using ganache deterministic key")
if isAlice {
ethPrivKey = common.DefaultPrivKeyAlice
} else {
ethPrivKey = common.DefaultPrivKeyBob
}
env, cfg, err := getEnvironment(c)
if err != nil {
return err
}
chainID := int64(c.Uint("ethereum-chain-id"))
@@ -218,81 +164,15 @@ func runDaemon(c *cli.Context) error {
chainID = cfg.EthereumChainID
}
if c.String("monero-daemon-endpoint") != "" {
daemonEndpoint = c.String("monero-daemon-endpoint")
} else {
daemonEndpoint = cfg.MoneroDaemonEndpoint
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
type Handler interface {
net.Handler
rpc.Protocol
SetMessageSender(net.MessageSender)
handler, err := getProtocolHandler(ctx, c, env, cfg, chainID, isAlice, isBob)
if err != nil {
return err
}
var gasPrice *big.Int
if c.Uint("gas-price") != 0 {
gasPrice = big.NewInt(int64(c.Uint("gas-price")))
}
// TODO: add configs for different eth testnets + L2 and set gas limit based on those, if not set
var (
handler Handler
err error
)
switch {
case isAlice:
aliceCfg := &alice.Config{
Ctx: ctx,
Basepath: cfg.Basepath,
MoneroWalletEndpoint: moneroEndpoint,
EthereumEndpoint: ethEndpoint,
EthereumPrivateKey: ethPrivKey,
Environment: env,
ChainID: chainID,
GasPrice: gasPrice,
GasLimit: uint64(c.Uint("gas-limit")),
}
handler, err = alice.NewAlice(aliceCfg)
if err != nil {
return err
}
case isBob:
walletFile := c.String("wallet-file")
if walletFile == "" {
return errors.New("must provide --wallet-file")
}
// empty password is ok
walletPassword := c.String("wallet-password")
bobCfg := &bob.Config{
Ctx: ctx,
Basepath: cfg.Basepath,
MoneroWalletEndpoint: moneroEndpoint,
MoneroDaemonEndpoint: daemonEndpoint,
WalletFile: walletFile,
WalletPassword: walletPassword,
EthereumEndpoint: ethEndpoint,
EthereumPrivateKey: ethPrivKey,
Environment: env,
ChainID: chainID,
GasPrice: gasPrice,
GasLimit: uint64(c.Uint("gas-limit")),
}
handler, err = bob.NewBob(bobCfg)
if err != nil {
return err
}
}
amount := float64(c.Float64("max-amount"))
amount := c.Float64("max-amount")
var bootnodes []string
if c.String("bootnodes") != "" {
@@ -399,3 +279,143 @@ func runDaemon(c *cli.Context) error {
wait(ctx)
return nil
}
func getEnvironment(c *cli.Context) (env common.Environment, cfg common.Config, err error) {
switch c.String("env") {
case "mainnet":
env = common.Mainnet
cfg = common.MainnetConfig
case "stagenet":
env = common.Stagenet
cfg = common.StagenetConfig
case "dev":
env = common.Development
cfg = common.DevelopmentConfig
case "":
env = defaultEnvironment
cfg = common.DevelopmentConfig
default:
return 0, common.Config{}, errors.New("--env must be one of mainnet, stagenet, or dev")
}
return env, cfg, nil
}
func getEthereumPrivateKey(c *cli.Context, env common.Environment, isAlice bool) (ethPrivKey string, err error) {
if c.String("ethereum-privkey") != "" {
ethPrivKeyFile := c.String("ethereum-privkey")
key, err := os.ReadFile(filepath.Clean(ethPrivKeyFile))
if err != nil {
return "", fmt.Errorf("failed to read ethereum-privkey file: %w", err)
}
if key[len(key)-1] == '\n' {
key = key[:len(key)-1]
}
ethPrivKey = string(key)
} else {
if env != common.Development {
return "", errors.New("must provide --ethereum-privkey file for non-development environment")
}
log.Warn("no ethereum private key file provided, using ganache deterministic key")
if isAlice {
ethPrivKey = common.DefaultPrivKeyAlice
} else {
ethPrivKey = common.DefaultPrivKeyBob
}
}
return ethPrivKey, nil
}
func getProtocolHandler(ctx context.Context, c *cli.Context, env common.Environment, cfg common.Config,
chainID int64, isAlice, isBob bool) (handler protocolHandler, err error) {
var (
moneroEndpoint, daemonEndpoint, ethEndpoint string
)
if c.String("monero-endpoint") != "" {
moneroEndpoint = c.String("monero-endpoint")
} else {
if isAlice {
moneroEndpoint = common.DefaultAliceMoneroEndpoint
} else {
moneroEndpoint = common.DefaultBobMoneroEndpoint
}
}
if c.String("ethereum-endpoint") != "" {
ethEndpoint = c.String("ethereum-endpoint")
} else {
ethEndpoint = common.DefaultEthEndpoint
}
ethPrivKey, err := getEthereumPrivateKey(c, env, isAlice)
if err != nil {
return nil, err
}
if c.String("monero-daemon-endpoint") != "" {
daemonEndpoint = c.String("monero-daemon-endpoint")
} else {
daemonEndpoint = cfg.MoneroDaemonEndpoint
}
// TODO: add configs for different eth testnets + L2 and set gas limit based on those, if not set
var gasPrice *big.Int
if c.Uint("gas-price") != 0 {
gasPrice = big.NewInt(int64(c.Uint("gas-price")))
}
switch {
case isAlice:
aliceCfg := &alice.Config{
Ctx: ctx,
Basepath: cfg.Basepath,
MoneroWalletEndpoint: moneroEndpoint,
EthereumEndpoint: ethEndpoint,
EthereumPrivateKey: ethPrivKey,
Environment: env,
ChainID: chainID,
GasPrice: gasPrice,
GasLimit: uint64(c.Uint("gas-limit")),
}
handler, err = alice.NewAlice(aliceCfg)
if err != nil {
return nil, err
}
case isBob:
walletFile := c.String("wallet-file")
if walletFile == "" {
return nil, errors.New("must provide --wallet-file")
}
// empty password is ok
walletPassword := c.String("wallet-password")
bobCfg := &bob.Config{
Ctx: ctx,
Basepath: cfg.Basepath,
MoneroWalletEndpoint: moneroEndpoint,
MoneroDaemonEndpoint: daemonEndpoint,
WalletFile: walletFile,
WalletPassword: walletPassword,
EthereumEndpoint: ethEndpoint,
EthereumPrivateKey: ethPrivKey,
Environment: env,
ChainID: chainID,
GasPrice: gasPrice,
GasLimit: uint64(c.Uint("gas-limit")),
}
handler, err = bob.NewBob(bobCfg)
if err != nil {
return nil, err
}
}
return handler, nil
}

View File

@@ -15,18 +15,21 @@ type Config struct {
Bootnodes []string // TODO: when it's ready for users to test, add some bootnodes
}
// MainnetConfig is the mainnet ethereum and monero configuration
var MainnetConfig = Config{
Basepath: fmt.Sprintf("%s/.atomicswap/mainnet", homeDir),
MoneroDaemonEndpoint: "http://127.0.0.1:18081/json_rpc",
EthereumChainID: MainnetChainID,
}
// StagenetConfig is the monero stagenet and ethereum ropsten configuration
var StagenetConfig = Config{
Basepath: fmt.Sprintf("%s/.atomicswap/stagenet", homeDir),
MoneroDaemonEndpoint: "http://127.0.0.1:38081/json_rpc",
EthereumChainID: RopstenChainID,
}
// DevelopmentConfig is the monero and ethereum development environment configuration
var DevelopmentConfig = Config{
Basepath: fmt.Sprintf("%s/.atomicswap/dev", homeDir),
MoneroDaemonEndpoint: "http://127.0.0.1:18081/json_rpc",

View File

@@ -6,7 +6,7 @@ import (
)
const (
MainnetChainID = 1
MainnetChainID = 1 //nolint
RopstenChainID = 3
GanacheChainID = 1337
@@ -27,23 +27,29 @@ var (
numMoneroUnits = math.Pow(10, 12)
)
// MoneroAmount represents some amount of piconero (the smallest denomination of monero)
type MoneroAmount uint64
// MoneroToPiconero converts an amount of standard monero and returns it as a MoneroAmount
func MoneroToPiconero(amount float64) MoneroAmount {
return MoneroAmount(amount * numMoneroUnits)
}
// Uint64 ...
func (a MoneroAmount) Uint64() uint64 {
return uint64(a)
}
// EtherAmount represents some amout of ether in the smallest denomination (wei)
type EtherAmount big.Int
// NewEtherAmount converts some amount of wei into an EtherAmount.
func NewEtherAmount(amount int64) EtherAmount {
i := big.NewInt(amount)
return EtherAmount(*i)
}
// EtherToWei converts some amount of standard ether to an EtherAmount.
func EtherToWei(amount float64) EtherAmount {
amt := big.NewFloat(amount)
mult := big.NewFloat(numEtherUnits)
@@ -51,11 +57,13 @@ func EtherToWei(amount float64) EtherAmount {
return EtherAmount(*res)
}
// BigInt returns the given EtherAmount as a *big.Int
func (a EtherAmount) BigInt() *big.Int {
i := big.Int(a)
return &i
}
// String ...
func (a EtherAmount) String() string {
return a.BigInt().String()
}

View File

@@ -5,10 +5,12 @@ package common
// ie. an ExchangeRate of 0.1 means that the node considers 1 ETH = 10 XMR.
type ExchangeRate float64
// ToXMR converts an ether amount to a monero amount with the given exchange rate
func (r ExchangeRate) ToXMR(ethAmount uint64) uint64 {
return uint64(float64(ethAmount) / float64(r))
}
// ToETH converts a moenro amount to an eth amount with the given exchange rate
func (r ExchangeRate) ToETH(xmrAmount uint64) uint64 {
return uint64(float64(r) * float64(xmrAmount))
}

View File

@@ -1,13 +1,15 @@
package common
// Environment represents the environment the swap will run in (ie. mainnet, stagenet, or development)
type Environment byte
const (
Mainnet Environment = iota
Mainnet Environment = iota //nolint
Stagenet
Development
)
// String ...
func (env Environment) String() string {
switch env {
case Mainnet:

View File

@@ -2,13 +2,15 @@ package common
import "errors"
// ProvidesCoin represents a coin that a swap participant can provide.
type ProvidesCoin string
var (
ProvidesXMR ProvidesCoin = "XMR"
ProvidesETH ProvidesCoin = "ETH"
ProvidesXMR ProvidesCoin = "XMR" //nolint
ProvidesETH ProvidesCoin = "ETH" //nolint
)
// NewProvidesCoin converts a string to a ProvidesCoin.
func NewProvidesCoin(s string) (ProvidesCoin, error) {
switch s {
case "XMR":

View File

@@ -21,6 +21,7 @@ var (
log = logging.Logger("common")
)
// Reverse reverses the byte slice and returns it.
func Reverse(s []byte) []byte {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
@@ -28,6 +29,7 @@ func Reverse(s []byte) []byte {
return s
}
// WaitForReceipt waits for the receipt for the given transaction to be available and returns it.
func WaitForReceipt(ctx context.Context, ethclient *ethclient.Client, txHash ethcommon.Hash) (*ethtypes.Receipt, bool) {
for i := 0; i < maxRetries; i++ {
receipt, err := ethclient.TransactionReceipt(ctx, txHash)

View File

@@ -7,6 +7,7 @@ import (
"strings"
)
// BASE58 ...
const BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
var base58Lookup = map[string]int{
@@ -50,6 +51,7 @@ func decodeChunk(encoded string) (result []byte) {
return
}
// EncodeMoneroBase58 encodes byte data using base-58
func EncodeMoneroBase58(data ...[]byte) (result string) {
var combined []byte
for _, item := range data {
@@ -66,6 +68,7 @@ func EncodeMoneroBase58(data ...[]byte) (result string) {
return
}
// DecodeMoneroBase58 decodes base-58 encoded data into a byte slice
func DecodeMoneroBase58(data string) (result []byte) {
length := len(data)
rounds := length / 11

View File

@@ -23,7 +23,8 @@ type client struct {
endpoint string
}
func NewClient(endpoint string) *client {
// NewClient returns a new monero-wallet-rpc client.
func NewClient(endpoint string) *client { //nolint:revive
return &client{
endpoint: endpoint,
}

View File

@@ -83,8 +83,9 @@ func TestClient_Transfer(t *testing.T) {
// generate spend account for A+B
skAKPriv := SumPrivateSpendKeys(kpA.sk, kpB.sk)
err = cB.callGenerateFromKeys(skAKPriv, vkABPriv, kpABPub.Address(common.Mainnet), fmt.Sprintf("test-wallet-spaghet%d", r), "")
require.NoError(t, err)
// ignore the error for now, as it can error with "Wallet already exists."
_ = cB.callGenerateFromKeys(skAKPriv, vkABPriv, kpABPub.Address(common.Mainnet),
fmt.Sprintf("test-wallet-%d", r), "")
err = cB.refresh()
require.NoError(t, err)

View File

@@ -20,10 +20,12 @@ const (
addressPrefixStagenet byte = 24
)
func PublicSpendOnSecp256k1(k []byte) (a, b *big.Int) {
// PublicSpendOnSecp256k1 returns a public spend key on the secp256k1 curve
func PublicSpendOnSecp256k1(k []byte) (x, y *big.Int) {
return secp256k1.S256().ScalarBaseMult(k)
}
// SumSpendAndViewKeys sums two PublicKeyPairs, returning another PublicKeyPair.
func SumSpendAndViewKeys(a, b *PublicKeyPair) *PublicKeyPair {
return &PublicKeyPair{
sk: SumPublicKeys(a.sk, b.sk),
@@ -31,7 +33,7 @@ func SumSpendAndViewKeys(a, b *PublicKeyPair) *PublicKeyPair {
}
}
// Sum sums two public keys (points)
// SumPublicKeys sums two public keys (points)
func SumPublicKeys(a, b *PublicKey) *PublicKey {
s := ed25519.NewIdentityPoint().Add(a.key, b.key)
return &PublicKey{
@@ -39,7 +41,7 @@ func SumPublicKeys(a, b *PublicKey) *PublicKey {
}
}
// Sum sums two private spend keys (scalars)
// SumPrivateSpendKeys sums two private spend keys (scalars)
func SumPrivateSpendKeys(a, b *PrivateSpendKey) *PrivateSpendKey {
s := ed25519.NewScalar().Add(a.key, b.key)
return &PrivateSpendKey{
@@ -47,7 +49,7 @@ func SumPrivateSpendKeys(a, b *PrivateSpendKey) *PrivateSpendKey {
}
}
// Sum sums two private view keys (scalars)
// SumPrivateViewKeys sums two private view keys (scalars)
func SumPrivateViewKeys(a, b *PrivateViewKey) *PrivateViewKey {
s := ed25519.NewScalar().Add(a.key, b.key)
return &PrivateViewKey{
@@ -55,6 +57,7 @@ func SumPrivateViewKeys(a, b *PrivateViewKey) *PrivateViewKey {
}
}
// Keccak256 returns the keccak256 hash of the data.
func Keccak256(data ...[]byte) (result [32]byte) {
h := keccak.New256()
for _, b := range data {
@@ -77,11 +80,14 @@ var (
errInvalidInput = errors.New("input is not 32 bytes")
)
// PrivateKeyPair represents a monero private spend and view key.
type PrivateKeyPair struct {
sk *PrivateSpendKey
vk *PrivateViewKey
}
// NewPrivateKeyPair returns a new PrivateKeyPair from the given PrivateSpendKey and PrivateViewKey.
// It does not validate if the view key corresponds to the spend key.
func NewPrivateKeyPair(sk *PrivateSpendKey, vk *PrivateViewKey) *PrivateKeyPair {
return &PrivateKeyPair{
sk: sk,
@@ -89,6 +95,8 @@ func NewPrivateKeyPair(sk *PrivateSpendKey, vk *PrivateViewKey) *PrivateKeyPair
}
}
// NewPrivateKeyPairFromBytes returns a new PrivateKeyPair given the canonical byte representation of
// a private spend and view key.
func NewPrivateKeyPairFromBytes(skBytes, vkBytes []byte) (*PrivateKeyPair, error) {
if len(skBytes) != privateKeySize || len(vkBytes) != privateKeySize {
return nil, errInvalidInput
@@ -110,6 +118,7 @@ func NewPrivateKeyPairFromBytes(skBytes, vkBytes []byte) (*PrivateKeyPair, error
}, nil
}
// AddressBytes returns the address as bytes for a PrivateKeyPair with the given environment (ie. mainnet or stagenet)
func (kp *PrivateKeyPair) AddressBytes(env common.Environment) []byte {
psk := kp.sk.Public().key.Bytes()
pvk := kp.vk.Public().key.Bytes()
@@ -131,14 +140,18 @@ func (kp *PrivateKeyPair) AddressBytes(env common.Environment) []byte {
return addr
}
// SpendKeyBytes returns the canoncail byte encoding of the private spend key.
func (kp *PrivateKeyPair) SpendKeyBytes() []byte {
return kp.sk.key.Bytes()
}
// Address returns the base58-encoded address for a PrivateKeyPair with the given environment
// (ie. mainnet or stagenet)
func (kp *PrivateKeyPair) Address(env common.Environment) Address {
return Address(EncodeMoneroBase58(kp.AddressBytes(env)))
}
// PublicKeyPair returns the PublicKeyPair corresponding to the PrivateKeyPair
func (kp *PrivateKeyPair) PublicKeyPair() *PublicKeyPair {
return &PublicKeyPair{
sk: kp.sk.Public(),
@@ -146,14 +159,18 @@ func (kp *PrivateKeyPair) PublicKeyPair() *PublicKeyPair {
}
}
// SpendKey returns the keypair's spend key
func (kp *PrivateKeyPair) SpendKey() *PrivateSpendKey {
return kp.sk
}
// ViewKey returns the keypair's view key
func (kp *PrivateKeyPair) ViewKey() *PrivateViewKey {
return kp.vk
}
// Marshal JSON-marshals the private key pair, providing its PrivateSpendKey, PrivateViewKey, Address,
// and Environment. This is intended to be written to a file, which someone can use to regenerate the wallet.
func (kp *PrivateKeyPair) Marshal(env common.Environment) ([]byte, error) {
m := make(map[string]string)
m["PrivateSpendKey"] = kp.sk.Hex()
@@ -163,10 +180,12 @@ func (kp *PrivateKeyPair) Marshal(env common.Environment) ([]byte, error) {
return json.Marshal(m)
}
// PrivateSpendKey represents a monero private spend key
type PrivateSpendKey struct {
key *ed25519.Scalar
}
// NewPrivateSpendKey returns a new PrivateSpendKey from the given canonically-encoded scalar.
func NewPrivateSpendKey(b []byte) (*PrivateSpendKey, error) {
if len(b) != privateKeySize {
return nil, errors.New("input is not 32 bytes")
@@ -182,6 +201,7 @@ func NewPrivateSpendKey(b []byte) (*PrivateSpendKey, error) {
}, nil
}
// Public returns the public key corresponding to the private key.
func (k *PrivateSpendKey) Public() *PublicKey {
pk := ed25519.NewIdentityPoint().ScalarBaseMult(k.key)
return &PublicKey{
@@ -189,10 +209,12 @@ func (k *PrivateSpendKey) Public() *PublicKey {
}
}
// Hex returns the hex-encoded canonical byte representation of the PrivateSpendKey.
func (k *PrivateSpendKey) Hex() string {
return hex.EncodeToString(k.key.Bytes())
}
// AsPrivateKeyPair returns the PrivateSpendKey as a PrivateKeyPair.
func (k *PrivateSpendKey) AsPrivateKeyPair() (*PrivateKeyPair, error) {
vk, err := k.View()
if err != nil {
@@ -205,6 +227,7 @@ func (k *PrivateSpendKey) AsPrivateKeyPair() (*PrivateKeyPair, error) {
}, nil
}
// View returns the private view key corresponding to the PrivateSpendKey.
func (k *PrivateSpendKey) View() (*PrivateViewKey, error) {
h := Keccak256(k.key.Bytes())
vk, err := ed25519.NewScalar().SetBytesWithClamping(h[:])
@@ -228,10 +251,12 @@ func (k *PrivateSpendKey) HashString() string {
return hex.EncodeToString(h[:])
}
// PrivateViewKey represents a monero private view key.
type PrivateViewKey struct {
key *ed25519.Scalar
}
// Public returns the PublicKey corresponding to this PrivateViewKey.
func (k *PrivateViewKey) Public() *PublicKey {
pk := ed25519.NewIdentityPoint().ScalarBaseMult(k.key)
return &PublicKey{
@@ -239,10 +264,12 @@ func (k *PrivateViewKey) Public() *PublicKey {
}
}
// Hex returns the hex-encoded canonical byte representation of the PrivateViewKey.
func (k *PrivateViewKey) Hex() string {
return hex.EncodeToString(k.key.Bytes())
}
// NewPrivateViewKeyFromHex returns a new PrivateViewKey from the given canonically- and hex-encoded scalar.
func NewPrivateViewKeyFromHex(vkHex string) (*PrivateViewKey, error) {
vkBytes, err := hex.DecodeString(vkHex)
if err != nil {
@@ -277,10 +304,12 @@ func NewPrivateViewKeyFromHash(hash string) (*PrivateViewKey, error) {
}, nil
}
// PublicKey represents a monero public spend or view key.
type PublicKey struct {
key *ed25519.Point
}
// NewPublicKeyFromHex returns a new PublicKey from the given canonically- and hex-encoded point.
func NewPublicKeyFromHex(s string) (*PublicKey, error) {
b, err := hex.DecodeString(s)
if err != nil {
@@ -297,10 +326,12 @@ func NewPublicKeyFromHex(s string) (*PublicKey, error) {
}, nil
}
// Hex returns the hex-encoded canonical byte representation of the PublicKey.
func (k *PublicKey) Hex() string {
return hex.EncodeToString(k.key.Bytes())
}
// Bytes returns the canonical byte representation of the PublicKey.
func (k *PublicKey) Bytes() []byte {
return k.key.Bytes()
}
@@ -311,6 +342,7 @@ type PublicKeyPair struct {
vk *PublicKey
}
// NewPublicKeyPairFromHex returns a new PublicKeyPair from the given canonically- and hex-encoded points.
func NewPublicKeyPairFromHex(skHex, vkHex string) (*PublicKeyPair, error) {
skBytes, err := hex.DecodeString(skHex)
if err != nil {
@@ -338,6 +370,7 @@ func NewPublicKeyPairFromHex(skHex, vkHex string) (*PublicKeyPair, error) {
}, nil
}
// NewPublicKeyPair returns a new PublicKeyPair from the given public spend and view keys.
func NewPublicKeyPair(sk, vk *PublicKey) *PublicKeyPair {
return &PublicKeyPair{
sk: sk,
@@ -345,14 +378,17 @@ func NewPublicKeyPair(sk, vk *PublicKey) *PublicKeyPair {
}
}
// SpendKey returns the keypair's spend key.
func (kp *PublicKeyPair) SpendKey() *PublicKey {
return kp.sk
}
// ViewKey returns the keypair's view key.
func (kp *PublicKeyPair) ViewKey() *PublicKey {
return kp.vk
}
// AddressBytes returns the address as bytes for a PublicKeyPair with the given environment (ie. mainnet or stagenet)
func (kp *PublicKeyPair) AddressBytes(env common.Environment) []byte {
psk := kp.sk.key.Bytes()
pvk := kp.vk.key.Bytes()
@@ -374,6 +410,8 @@ func (kp *PublicKeyPair) AddressBytes(env common.Environment) []byte {
return addr
}
// Address returns the base58-encoded address for a PublicKeyPair with the given environment
// (ie. mainnet or stagenet)
func (kp *PublicKeyPair) Address(env common.Environment) Address {
return Address(EncodeMoneroBase58(kp.AddressBytes(env)))
}

View File

@@ -24,7 +24,8 @@ type generateFromKeysResponse struct {
Info string `json:"info"`
}
func (c *client) callGenerateFromKeys(sk *PrivateSpendKey, vk *PrivateViewKey, address Address, filename, password string) error {
func (c *client) callGenerateFromKeys(sk *PrivateSpendKey, vk *PrivateViewKey, address Address,
filename, password string) error {
const (
method = "generate_from_keys"
successMessage = "Wallet has been generated successfully."
@@ -69,6 +70,7 @@ func (c *client) callGenerateFromKeys(sk *PrivateSpendKey, vk *PrivateViewKey, a
return fmt.Errorf("got unexpected Info string: %s", res.Info)
}
// Destination represents a transfer destination
type Destination struct {
Amount uint `json:"amount"`
Address string `json:"address"`
@@ -80,6 +82,7 @@ type transferRequest struct {
Priority uint `json:"priority"`
}
// TransferResponse ...
type TransferResponse struct {
Amount uint `json:"amount"`
Fee uint `json:"fee"`
@@ -128,6 +131,7 @@ type getBalanceRequest struct {
AccountIndex uint `json:"account_index"`
}
// GetBalanceResponse ...
type GetBalanceResponse struct {
Balance float64 `json:"balance"`
BlocksToUnlock uint `json:"blocks_to_unlock"`

View File

@@ -28,7 +28,8 @@ type discovery struct {
provides []common.ProvidesCoin
}
func newDiscovery(ctx context.Context, h libp2phost.Host, bnsFunc func() []peer.AddrInfo, provides ...common.ProvidesCoin) (*discovery, error) {
func newDiscovery(ctx context.Context, h libp2phost.Host, bnsFunc func() []peer.AddrInfo,
provides ...common.ProvidesCoin) (*discovery, error) {
dhtOpts := []dual.Option{
dual.DHTOption(kaddht.BootstrapPeersFunc(bnsFunc)),
dual.DHTOption(kaddht.Mode(kaddht.ModeAutoServer)),
@@ -102,7 +103,8 @@ func (d *discovery) advertise() {
}
}
func (d *discovery) discover(provides common.ProvidesCoin, searchTime time.Duration) ([]peer.AddrInfo, error) { //nolint:unused
func (d *discovery) discover(provides common.ProvidesCoin,
searchTime time.Duration) ([]peer.AddrInfo, error) {
log.Debugf("attempting to find DHT peers that provide %s for %s...", provides, searchTime)
peerCh, err := d.rd.FindPeers(d.ctx, string(provides))

View File

@@ -28,6 +28,7 @@ const (
var log = logging.Logger("net")
var _ Host = &host{}
// Host represents a peer-to-peer node (ie. a hash)
type Host interface {
Start() error
Stop() error
@@ -38,6 +39,7 @@ type Host interface {
MessageSender
}
// MessageSender is implemented by a Host
type MessageSender interface {
SendSwapMessage(Message) error
}
@@ -76,7 +78,8 @@ type Config struct {
Handler Handler
}
func NewHost(cfg *Config) (*host, error) {
// NewHost returns a new host
func NewHost(cfg *Config) (*host, error) { //nolint:revive
if cfg.KeyFile == "" {
cfg.KeyFile = defaultKeyFile
}
@@ -269,7 +272,8 @@ func readStream(stream libp2pnetwork.Stream, buf []byte) (int, error) {
}
if length > uint64(len(buf)) {
log.Warn("received message with size greater than allocated message buffer", "length", length, "buffer size", len(buf))
log.Warn("received message with size greater than allocated message buffer",
"length", length, "buffer size", len(buf))
return 0, fmt.Errorf("message size greater than allocated message buffer: got %d", length)
}

View File

@@ -9,7 +9,7 @@ import (
)
const (
QueryResponseType byte = iota
QueryResponseType byte = iota //nolint
InitiateMessageType
SendKeysMessageType
NotifyContractDeployedType
@@ -19,6 +19,7 @@ const (
NotifyRefundType
)
// Message must be implemented by all network messages
type Message interface {
String() string
Encode() ([]byte, error)
@@ -78,12 +79,14 @@ func decodeMessage(b []byte) (Message, error) {
}
}
// QueryResponse ...
type QueryResponse struct {
Provides []common.ProvidesCoin
MaximumAmount []float64
ExchangeRate common.ExchangeRate
}
// String ...
func (m *QueryResponse) String() string {
return fmt.Sprintf("QueryResponse Provides=%v MaximumAmount=%v ExchangeRate=%v",
m.Provides,
@@ -92,6 +95,7 @@ func (m *QueryResponse) String() string {
)
}
// Encode ...
func (m *QueryResponse) Encode() ([]byte, error) {
b, err := json.Marshal(m)
if err != nil {
@@ -101,10 +105,12 @@ func (m *QueryResponse) Encode() ([]byte, error) {
return append([]byte{QueryResponseType}, b...), nil
}
// Type ...
func (m *QueryResponse) Type() byte {
return QueryResponseType
}
// InitiateMessage is sent by a node who wishes to initate a swap with the remote peer.
type InitiateMessage struct {
Provides common.ProvidesCoin
ProvidesAmount float64
@@ -112,6 +118,7 @@ type InitiateMessage struct {
*SendKeysMessage
}
// String ...
func (m *InitiateMessage) String() string {
return fmt.Sprintf("InitiateMessage Provides=%v ProvidesAmount=%v DesiredAmount=%v Keys=%s",
m.Provides,
@@ -121,6 +128,7 @@ func (m *InitiateMessage) String() string {
)
}
// Encode ...
func (m *InitiateMessage) Encode() ([]byte, error) {
b, err := json.Marshal(m)
if err != nil {
@@ -130,6 +138,7 @@ func (m *InitiateMessage) Encode() ([]byte, error) {
return append([]byte{InitiateMessageType}, b...), nil
}
// Type ...
func (m *InitiateMessage) Type() byte {
return InitiateMessageType
}
@@ -145,6 +154,7 @@ type SendKeysMessage struct {
EthAddress string
}
// String ...
func (m *SendKeysMessage) String() string {
return fmt.Sprintf("SendKeysMessage PublicSpendKey=%s PublicViewKey=%s PrivateViewKey=%s EthAddress=%s",
m.PublicSpendKey,
@@ -154,6 +164,7 @@ func (m *SendKeysMessage) String() string {
)
}
// Encode ...
func (m *SendKeysMessage) Encode() ([]byte, error) {
b, err := json.Marshal(m)
if err != nil {
@@ -163,6 +174,7 @@ func (m *SendKeysMessage) Encode() ([]byte, error) {
return append([]byte{SendKeysMessageType}, b...), nil
}
// Type ...
func (m *SendKeysMessage) Type() byte {
return SendKeysMessageType
}
@@ -173,10 +185,12 @@ type NotifyContractDeployed struct {
Address string
}
// String ...
func (m *NotifyContractDeployed) String() string {
return "NotifyContractDeployed"
}
// Encode ...
func (m *NotifyContractDeployed) Encode() ([]byte, error) {
b, err := json.Marshal(m)
if err != nil {
@@ -186,6 +200,7 @@ func (m *NotifyContractDeployed) Encode() ([]byte, error) {
return append([]byte{NotifyContractDeployedType}, b...), nil
}
// Type ...
func (m *NotifyContractDeployed) Type() byte {
return NotifyContractDeployedType
}
@@ -195,10 +210,12 @@ type NotifyXMRLock struct {
Address string
}
// String ...
func (m *NotifyXMRLock) String() string {
return "NotifyXMRLock"
}
// Encode ...
func (m *NotifyXMRLock) Encode() ([]byte, error) {
b, err := json.Marshal(m)
if err != nil {
@@ -208,6 +225,7 @@ func (m *NotifyXMRLock) Encode() ([]byte, error) {
return append([]byte{NotifyXMRLockType}, b...), nil
}
// Type ...
func (m *NotifyXMRLock) Type() byte {
return NotifyXMRLockType
}
@@ -215,10 +233,12 @@ func (m *NotifyXMRLock) Type() byte {
// NotifyReady is sent by Alice to Bob after calling Ready() on the contract.
type NotifyReady struct{}
// String ...
func (m *NotifyReady) String() string {
return "NotifyReady"
}
// Encode ...
func (m *NotifyReady) Encode() ([]byte, error) {
b, err := json.Marshal(m)
if err != nil {
@@ -228,6 +248,7 @@ func (m *NotifyReady) Encode() ([]byte, error) {
return append([]byte{NotifyReadyType}, b...), nil
}
// Type ...
func (m *NotifyReady) Type() byte {
return NotifyReadyType
}
@@ -237,10 +258,12 @@ type NotifyClaimed struct {
TxHash string
}
// String ...
func (m *NotifyClaimed) String() string {
return fmt.Sprintf("NotifyClaimed %s", m.TxHash)
}
// Encode ...
func (m *NotifyClaimed) Encode() ([]byte, error) {
b, err := json.Marshal(m)
if err != nil {
@@ -250,6 +273,7 @@ func (m *NotifyClaimed) Encode() ([]byte, error) {
return append([]byte{NotifyClaimedType}, b...), nil
}
// Type ...
func (m *NotifyClaimed) Type() byte {
return NotifyClaimedType
}
@@ -259,10 +283,12 @@ type NotifyRefund struct {
TxHash string
}
// String ...
func (m *NotifyRefund) String() string {
return fmt.Sprintf("NotifyClaimed %s", m.TxHash)
}
// Encode ...
func (m *NotifyRefund) Encode() ([]byte, error) {
b, err := json.Marshal(m)
if err != nil {
@@ -272,6 +298,7 @@ func (m *NotifyRefund) Encode() ([]byte, error) {
return append([]byte{NotifyRefundType}, b...), nil
}
// Type ...
func (m *NotifyRefund) Type() byte {
return NotifyRefundType
}

View File

@@ -16,7 +16,7 @@ import (
ma "github.com/multiformats/go-multiaddr"
)
// StringToAddrInfos converts a single string peer id to AddrInfo
// StringToAddrInfo converts a single string peer id to AddrInfo
func StringToAddrInfo(s string) (peer.AddrInfo, error) {
maddr, err := ma.NewMultiaddr(s)
if err != nil {

View File

@@ -11,12 +11,15 @@ import (
"github.com/gorilla/rpc/v2/json2"
)
// Codec ...
type Codec struct{}
// NewCodec ...
func NewCodec() *Codec {
return new(Codec)
}
// NewRequest ...
func (c *Codec) NewRequest(req *http.Request) rpc.CodecRequest {
outer := &CodecRequest{}
inner := json2.NewCodec().NewRequest(req)
@@ -24,10 +27,12 @@ func (c *Codec) NewRequest(req *http.Request) rpc.CodecRequest {
return outer
}
// CodecRequest ...
type CodecRequest struct {
*json2.CodecRequest
}
// Method ...
func (cr *CodecRequest) Method() (string, error) {
method, err := cr.CodecRequest.Method()
if err != nil {

View File

@@ -14,6 +14,7 @@ import (
const defaultSearchTime = time.Second * 12
// Net contains the functions required by the rpc service into the network.
type Net interface {
Addresses() []string
Discover(provides common.ProvidesCoin, searchTime time.Duration) ([]peer.AddrInfo, error)
@@ -21,17 +22,20 @@ type Net interface {
Initiate(who peer.AddrInfo, msg *net.InitiateMessage, s net.SwapState) error
}
// Protocol represents the functions required by the rpc service into the protocol handler.
type Protocol interface {
Provides() common.ProvidesCoin
InitiateProtocol(providesAmount, desiredAmount float64) (net.SwapState, error)
SetGasPrice(gasPrice uint64)
}
// NetService is the RPC service prefixed by net_.
type NetService struct {
net Net
protocol Protocol
}
// NewNetService ...
func NewNetService(net Net, protocol Protocol) *NetService {
return &NetService{
net: net,
@@ -39,20 +43,24 @@ func NewNetService(net Net, protocol Protocol) *NetService {
}
}
// AddressesResponse ...
type AddressesResponse struct {
Addrs []string `json:"addresses"`
}
// Addresses returns the multiaddresses this node is listening on.
func (s *NetService) Addresses(_ *http.Request, _ *interface{}, resp *AddressesResponse) error {
resp.Addrs = s.net.Addresses()
return nil
}
// DiscoverRequest ...
type DiscoverRequest struct {
Provides common.ProvidesCoin `json:"provides"`
SearchTime uint64 `json:"searchTime"` // in seconds
}
// DiscoverResponse ...
type DiscoverResponse struct {
Peers [][]string `json:"peers"`
}
@@ -68,7 +76,7 @@ func (s *NetService) Discover(_ *http.Request, req *DiscoverRequest, resp *Disco
searchTime = defaultSearchTime
}
peers, err := s.net.Discover(common.ProvidesCoin(req.Provides), searchTime)
peers, err := s.net.Discover(req.Provides, searchTime)
if err != nil {
return err
}
@@ -89,17 +97,20 @@ func addrInfoToStrings(addrInfo peer.AddrInfo) []string {
return strs
}
// QueryPeerRequest ...
type QueryPeerRequest struct {
// Multiaddr of peer to query
Multiaddr string `json:"multiaddr"`
}
// QueryPeerResponse ...
type QueryPeerResponse struct {
Provides []common.ProvidesCoin `json:"provides"`
MaximumAmount []float64 `json:"maximumAmount"`
ExchangeRate common.ExchangeRate `json:"exchangeRate"`
}
// QueryPeer queries a peer for the coins they provide, their maximum amounts, and desired exchange rate.
func (s *NetService) QueryPeer(_ *http.Request, req *QueryPeerRequest, resp *QueryPeerResponse) error {
who, err := net.StringToAddrInfo(req.Multiaddr)
if err != nil {
@@ -117,6 +128,7 @@ func (s *NetService) QueryPeer(_ *http.Request, req *QueryPeerRequest, resp *Que
return nil
}
// InitiateRequest ...
type InitiateRequest struct {
Multiaddr string `json:"multiaddr"`
ProvidesCoin common.ProvidesCoin `json:"provides"`
@@ -124,10 +136,12 @@ type InitiateRequest struct {
DesiredAmount float64 `json:"desiredAmount"`
}
// InitiateResponse ...
type InitiateResponse struct {
Success bool `json:"success"`
}
// Initiate initiates a swap with the given peer.
func (s *NetService) Initiate(_ *http.Request, req *InitiateRequest, resp *InitiateResponse) error {
if req.ProvidesCoin == "" {
return errors.New("must specify 'provides' coin")
@@ -164,10 +178,12 @@ func (s *NetService) Initiate(_ *http.Request, req *InitiateRequest, resp *Initi
return nil
}
// SetGasPriceRequest ...
type SetGasPriceRequest struct {
GasPrice uint64
}
// SetGasPrice sets the gas price (in wei) to be used for ethereum transactions.
func (s *NetService) SetGasPrice(_ *http.Request, req *SetGasPriceRequest, _ *interface{}) error {
s.protocol.SetGasPrice(req.GasPrice)
return nil

View File

@@ -12,17 +12,20 @@ import (
var log = logging.Logger("rpc")
// Server represents the JSON-RPC server
type Server struct {
s *rpc.Server
port uint16
}
// Config ...
type Config struct {
Port uint16
Net Net
Protocol Protocol
}
// NewServer ...
func NewServer(cfg *Config) (*Server, error) {
s := rpc.NewServer()
s.RegisterCodec(NewCodec(), "application/json")
@@ -36,6 +39,7 @@ func NewServer(cfg *Config) (*Server, error) {
}, nil
}
// Start starts the JSON-RPC server.
func (s *Server) Start() <-chan error {
errCh := make(chan error)

View File

@@ -1,7 +1,7 @@
#!/bin/bash
if [[ -d "./monero-x86_64-linux-gnu-v0.17.2.3" ]]; then
echo "monero-x86_64-linux-gnu-v0.17.2.3 already installed"
if [[ -d "./monero-x86_64-linux-gnu-v0.17.3.0" ]]; then
echo "monero-x86_64-linux-gnu-v0.17.3.0 already installed"
exit 0
fi

View File

@@ -3,12 +3,12 @@
# install monero and run daemon and wallet RPC servers for alice and bob
bash ./scripts/install-monero-linux.sh
echo "starting monerod..."
./monero-x86_64-linux-gnu-v0.17.2.3/monerod --detach --regtest --offline --fixed-difficulty=1 --rpc-bind-port 18081 &
./monero-x86_64-linux-gnu-v0.17.3.0/monerod --detach --regtest --offline --fixed-difficulty=1 --rpc-bind-port 18081 &
sleep 5
echo "starting monero-wallet-rpc on port 18083..."
mkdir bob-test-keys
./monero-x86_64-linux-gnu-v0.17.2.3/monero-wallet-rpc --rpc-bind-port 18083 --disable-rpc-login --wallet-dir ./bob-test-keys &> monero-wallet-cli-bob.log &
./monero-x86_64-linux-gnu-v0.17.3.0/monero-wallet-rpc --rpc-bind-port 18083 --disable-rpc-login --wallet-dir ./bob-test-keys &> monero-wallet-cli-bob.log &
MONERO_WALLET_CLI_BOB_PID=$!
sleep 5
@@ -16,7 +16,7 @@ curl http://localhost:18083/json_rpc -d '{"jsonrpc":"2.0","id":"0","method":"cre
echo "starting monero-wallet-rpc on port 18084..."
mkdir alice-test-keys
./monero-x86_64-linux-gnu-v0.17.2.3/monero-wallet-rpc --rpc-bind-port 18084 --disable-rpc-login --wallet-dir ./alice-test-keys &> monero-wallet-cli-alice.log &
./monero-x86_64-linux-gnu-v0.17.3.0/monero-wallet-rpc --rpc-bind-port 18084 --disable-rpc-login --wallet-dir ./alice-test-keys &> monero-wallet-cli-alice.log &
MONERO_WALLET_CLI_ALICE_PID=$!
# install ganache and run

View File

@@ -3,12 +3,12 @@
# install monero and run daemon and wallet RPC servers for alice and bob
bash ./scripts/install-monero-linux.sh
echo "starting monerod..."
./monero-x86_64-linux-gnu-v0.17.2.3/monerod --detach --regtest --offline --fixed-difficulty=1 --rpc-bind-port 18081 &
./monero-x86_64-linux-gnu-v0.17.3.0/monerod --detach --regtest --offline --fixed-difficulty=1 --rpc-bind-port 18081 &
sleep 5
echo "starting monero-wallet-rpc on port 18083..."
mkdir bob-test-keys
./monero-x86_64-linux-gnu-v0.17.2.3/monero-wallet-rpc --rpc-bind-port 18083 --disable-rpc-login --wallet-dir ./bob-test-keys &> monero-wallet-cli-bob.log &
./monero-x86_64-linux-gnu-v0.17.3.0/monero-wallet-rpc --rpc-bind-port 18083 --disable-rpc-login --wallet-dir ./bob-test-keys &> monero-wallet-cli-bob.log &
MONERO_WALLET_CLI_BOB_PID=$!
sleep 5
@@ -16,7 +16,7 @@ curl http://localhost:18083/json_rpc -d '{"jsonrpc":"2.0","id":"0","method":"cre
echo "starting monero-wallet-rpc on port 18084..."
mkdir alice-test-keys
./monero-x86_64-linux-gnu-v0.17.2.3/monero-wallet-rpc --rpc-bind-port 18084 --disable-rpc-login --wallet-dir ./alice-test-keys &> monero-wallet-cli-alice.log &
./monero-x86_64-linux-gnu-v0.17.3.0/monero-wallet-rpc --rpc-bind-port 18084 --disable-rpc-login --wallet-dir ./alice-test-keys &> monero-wallet-cli-alice.log &
MONERO_WALLET_CLI_ALICE_PID=$!
# install ganache and run

View File

@@ -2,14 +2,14 @@
bash ./scripts/install-monero-linux.sh
echo "starting monerod..."
./monero-x86_64-linux-gnu-v0.17.2.3/monerod --detach --stagenet --rpc-bind-port 18081 &
./monero-x86_64-linux-gnu-v0.17.3.0/monerod --detach --stagenet --rpc-bind-port 18081 &
sleep 5
echo "starting monero-wallet-rpc on port 18083..."
./monero-x86_64-linux-gnu-v0.17.2.3/monero-wallet-rpc --rpc-bind-port 18083 --disable-rpc-login --wallet-dir ./bob-test-keys --stagenet --trusted-daemon
./monero-x86_64-linux-gnu-v0.17.3.0/monero-wallet-rpc --rpc-bind-port 18083 --disable-rpc-login --wallet-dir ./bob-test-keys --stagenet --trusted-daemon
echo "starting monero-wallet-rpc on port 18084..."
./monero-x86_64-linux-gnu-v0.17.2.3/monero-wallet-rpc --rpc-bind-port 18084 --disable-rpc-login --wallet-dir ./alice-test-keys --stagenet --trusted-daemon
./monero-x86_64-linux-gnu-v0.17.3.0/monero-wallet-rpc --rpc-bind-port 18084 --disable-rpc-login --wallet-dir ./alice-test-keys --stagenet --trusted-daemon
# open Bob's wallet (must have funds)
sleep 5

View File

@@ -24,13 +24,14 @@ func TestDeploySwap(t *testing.T) {
conn, err := ethclient.Dial(common.DefaultEthEndpoint)
require.NoError(t, err)
pk_a, err := crypto.HexToECDSA(common.DefaultPrivKeyAlice)
pkA, err := crypto.HexToECDSA(common.DefaultPrivKeyAlice)
require.NoError(t, err)
authAlice, err := bind.NewKeyedTransactorWithChainID(pk_a, big.NewInt(common.GanacheChainID))
authAlice, err := bind.NewKeyedTransactorWithChainID(pkA, big.NewInt(common.GanacheChainID))
require.NoError(t, err)
address, tx, swapContract, err := DeploySwap(authAlice, conn, [32]byte{}, [32]byte{}, ethcommon.Address{}, defaultTimeoutDuration)
address, tx, swapContract, err := DeploySwap(authAlice, conn, [32]byte{}, [32]byte{},
ethcommon.Address{}, defaultTimeoutDuration)
require.NoError(t, err)
require.NotEqual(t, ethcommon.Address{}, address)
require.NotNil(t, tx)
@@ -57,15 +58,15 @@ func TestSwap_Claim(t *testing.T) {
conn, err := ethclient.Dial("ws://127.0.0.1:8545")
require.NoError(t, err)
pk_a, err := crypto.HexToECDSA(common.DefaultPrivKeyAlice)
pkA, err := crypto.HexToECDSA(common.DefaultPrivKeyAlice)
require.NoError(t, err)
pk_b, err := crypto.HexToECDSA(common.DefaultPrivKeyBob)
pkB, err := crypto.HexToECDSA(common.DefaultPrivKeyBob)
require.NoError(t, err)
authAlice, err := bind.NewKeyedTransactorWithChainID(pk_a, big.NewInt(common.GanacheChainID))
authAlice, err := bind.NewKeyedTransactorWithChainID(pkA, big.NewInt(common.GanacheChainID))
authAlice.Value = big.NewInt(1000000000000)
require.NoError(t, err)
authBob, err := bind.NewKeyedTransactorWithChainID(pk_b, big.NewInt(common.GanacheChainID))
authBob, err := bind.NewKeyedTransactorWithChainID(pkB, big.NewInt(common.GanacheChainID))
require.NoError(t, err)
aliceBalanceBefore, err := conn.BalanceAt(context.Background(), authAlice.From, nil)
@@ -77,10 +78,11 @@ func TestSwap_Claim(t *testing.T) {
require.NoError(t, err)
fmt.Println("BobBalanceBefore: ", bobBalanceBefore)
bobPub := pk_b.Public().(*ecdsa.PublicKey)
bobPub := pkB.Public().(*ecdsa.PublicKey)
bobAddr := crypto.PubkeyToAddress(*bobPub)
contractAddress, deployTx, swap, err := DeploySwap(authAlice, conn, pkBobFixed, pkAliceFixed, bobAddr, defaultTimeoutDuration)
contractAddress, deployTx, swap, err := DeploySwap(authAlice, conn, pkBobFixed, pkAliceFixed, bobAddr,
defaultTimeoutDuration)
require.NoError(t, err)
fmt.Println("Deploy Tx Gas Cost:", deployTx.Gas())
@@ -158,12 +160,12 @@ func TestSwap_Refund_Within_T0(t *testing.T) {
conn, err := ethclient.Dial("ws://127.0.0.1:8545")
require.NoError(t, err)
pk_a, err := crypto.HexToECDSA(common.DefaultPrivKeyAlice)
pkA, err := crypto.HexToECDSA(common.DefaultPrivKeyAlice)
require.NoError(t, err)
pk_b, err := crypto.HexToECDSA(common.DefaultPrivKeyBob)
pkB, err := crypto.HexToECDSA(common.DefaultPrivKeyBob)
require.NoError(t, err)
authAlice, err := bind.NewKeyedTransactorWithChainID(pk_a, big.NewInt(1337)) // ganache chainID
authAlice, err := bind.NewKeyedTransactorWithChainID(pkA, big.NewInt(1337)) // ganache chainID
require.NoError(t, err)
authAlice.Value = big.NewInt(10)
@@ -171,7 +173,7 @@ func TestSwap_Refund_Within_T0(t *testing.T) {
require.NoError(t, err)
fmt.Println("AliceBalanceBefore: ", aliceBalanceBefore)
bobPub := pk_b.Public().(*ecdsa.PublicKey)
bobPub := pkB.Public().(*ecdsa.PublicKey)
bobAddr := crypto.PubkeyToAddress(*bobPub)
contractAddress, _, swap, err := DeploySwap(authAlice, conn, pkBobFixed, pkAliceFixed, bobAddr, defaultTimeoutDuration)
require.NoError(t, err)
@@ -181,7 +183,7 @@ func TestSwap_Refund_Within_T0(t *testing.T) {
Signer: authAlice.Signer,
}
// Alice never calls set_ready on the contract, instead she just tries to Refund immidiately
// Alice never calls set_ready on the contract, instead she just tries to Refund immediately
var sa [32]byte
copy(sa[:], common.Reverse(secretAlice))
_, err = swap.Refund(txOpts, sa)
@@ -218,12 +220,12 @@ func TestSwap_Refund_After_T1(t *testing.T) {
conn, err := ethclient.Dial("ws://127.0.0.1:8545")
require.NoError(t, err)
pk_a, err := crypto.HexToECDSA(common.DefaultPrivKeyAlice)
pkA, err := crypto.HexToECDSA(common.DefaultPrivKeyAlice)
require.NoError(t, err)
pk_b, err := crypto.HexToECDSA(common.DefaultPrivKeyBob)
pkB, err := crypto.HexToECDSA(common.DefaultPrivKeyBob)
require.NoError(t, err)
authAlice, err := bind.NewKeyedTransactorWithChainID(pk_a, big.NewInt(1337)) // ganache chainID
authAlice, err := bind.NewKeyedTransactorWithChainID(pkA, big.NewInt(1337)) // ganache chainID
authAlice.Value = big.NewInt(10)
require.NoError(t, err)
@@ -231,7 +233,7 @@ func TestSwap_Refund_After_T1(t *testing.T) {
require.NoError(t, err)
fmt.Println("AliceBalanceBefore: ", aliceBalanceBefore)
bobPub := pk_b.Public().(*ecdsa.PublicKey)
bobPub := pkB.Public().(*ecdsa.PublicKey)
bobAddr := crypto.PubkeyToAddress(*bobPub)
contractAddress, _, swap, err := DeploySwap(authAlice, conn, pkBobFixed, pkAliceFixed, bobAddr, defaultTimeoutDuration)
require.NoError(t, err)

View File

@@ -35,16 +35,16 @@ func TestDeploySwapDLEQ(t *testing.T) {
conn, err := ethclient.Dial("http://127.0.0.1:8545")
require.NoError(t, err)
pk_a, err := crypto.HexToECDSA(common.DefaultPrivKeyAlice)
pkA, err := crypto.HexToECDSA(common.DefaultPrivKeyAlice)
require.NoError(t, err)
pk_b, err := crypto.HexToECDSA(common.DefaultPrivKeyBob)
pkB, err := crypto.HexToECDSA(common.DefaultPrivKeyBob)
require.NoError(t, err)
authAlice, err := bind.NewKeyedTransactorWithChainID(pk_a, big.NewInt(common.GanacheChainID))
authAlice, err := bind.NewKeyedTransactorWithChainID(pkA, big.NewInt(common.GanacheChainID))
require.NoError(t, err)
address, tx, swapContract, err := DeploySwapDLEQ(authAlice, conn, pk_a.X, pk_a.Y, pk_b.X, pk_b.Y)
address, tx, swapContract, err := DeploySwapDLEQ(authAlice, conn, pkA.X, pkA.Y, pkB.X, pkB.Y)
require.NoError(t, err)
t.Log(address)
@@ -60,37 +60,37 @@ func TestSwap_Claim(t *testing.T) {
// Alice generates key
keyPairAlice, err := monero.GenerateKeys()
require.NoError(t, err)
// pubKeyAlice := keyPairAlice.PublicKeyPair().SpendKey().Bytes()
pubKeyAliceX, pubKeyAliceY := monero.PublicSpendOnSecp256k1(keyPairAlice.SpendKeyBytes())
fmt.Println("pubKeyAliceX: ", hex.EncodeToString(pubKeyAliceX.Bytes()), "pubKeyAliceY: ", hex.EncodeToString(pubKeyAliceY.Bytes()))
fmt.Println("pubKeyAliceX: ", hex.EncodeToString(pubKeyAliceX.Bytes()),
"pubKeyAliceY: ", hex.EncodeToString(pubKeyAliceY.Bytes()))
// Alice generates DLEQ proof - this binary file is transmitted to Bob via some offchain protocol
fmt.Println("kAlice: ", keyPairAlice.SpendKeyBytes())
kAliceHex := hex.EncodeToString(keyPairAlice.SpendKeyBytes())
fmt.Println("kAliceHex: ", kAliceHex)
out, err := exec.Command("../target/debug/dleq-gen", kAliceHex, "../dleq-file-exchange/dleq_proof_alice.dat").Output()
aliceHex := hex.EncodeToString(keyPairAlice.SpendKeyBytes())
fmt.Println("aliceHex: ", aliceHex)
out, err := exec.Command("../target/debug/dleq-gen", aliceHex, "../dleq-file-exchange/dleq_proof_alice.dat").Output()
require.NoError(t, err)
fmt.Printf("%s\n", out)
// keyAlease, err := hex.DecodeString("e32ad36ce8e59156aa416da9c9f41a7abc59f6b5f1dd1c2079e8ff4e14503090")
keyAlease, err := hex.DecodeString("a6e51afb9662bf2173d807ceaf88938d09a82d1ab2cea3eeb1706eeeb8b6ba03")
require.NoError(t, err)
pubKeyAleaseX, pubKeyAleaseY := monero.PublicSpendOnSecp256k1(keyAlease)
fmt.Println("PubKey:", hex.EncodeToString(reverse(pubKeyAleaseX.Bytes())), hex.EncodeToString(reverse(pubKeyAleaseY.Bytes())))
fmt.Println("PubKey:", hex.EncodeToString(reverse(pubKeyAleaseX.Bytes())),
hex.EncodeToString(reverse(pubKeyAleaseY.Bytes())))
// Bob generates key
keyPairBob, err := monero.GenerateKeys()
require.NoError(t, err)
secretBob := keyPairBob.SpendKeyBytes()
pubKeyBobX, pubKeyBobY := monero.PublicSpendOnSecp256k1(secretBob)
fmt.Println("pubKeyBobX: ", hex.EncodeToString(pubKeyBobX.Bytes()), "pubKeyBobY: ", hex.EncodeToString(pubKeyBobY.Bytes()))
// pubKeyBob := keyPairBob.PublicKeyPair().SpendKey().Bytes()
fmt.Println("pubKeyBobX: ", hex.EncodeToString(pubKeyBobX.Bytes()),
"pubKeyBobY: ", hex.EncodeToString(pubKeyBobY.Bytes()))
kBobHex := hex.EncodeToString(keyPairBob.SpendKeyBytes())
fmt.Println("kBobHex: ", kBobHex)
out, err = exec.Command("../target/debug/dleq-gen", kBobHex, "../dleq-file-exchange/dleq_proof_bob.dat").Output()
bobHex := hex.EncodeToString(keyPairBob.SpendKeyBytes())
fmt.Println("bobHex: ", bobHex)
out, err = exec.Command("../target/debug/dleq-gen", bobHex, "../dleq-file-exchange/dleq_proof_bob.dat").Output()
require.NoError(t, err)
fmt.Println("dleq-gen out: ", (string(out)))
@@ -98,9 +98,6 @@ func TestSwap_Claim(t *testing.T) {
// alice verifies bob's dleq
out, err = exec.Command("../target/debug/dleq-verify", "../dleq-file-exchange/dleq_proof_bob.dat").Output()
// if err != nil {
// fmt.Println("proof verification failed:", err)
// }
require.NoError(t, err)
fmt.Printf("%s\n", out)
BobStrings := strings.Fields(string(out))
@@ -127,15 +124,15 @@ func TestSwap_Claim(t *testing.T) {
conn, err := ethclient.Dial("ws://127.0.0.1:8545")
require.NoError(t, err)
pk_a, err := crypto.HexToECDSA(common.DefaultPrivKeyAlice)
pkA, err := crypto.HexToECDSA(common.DefaultPrivKeyAlice)
require.NoError(t, err)
pk_b, err := crypto.HexToECDSA(common.DefaultPrivKeyBob)
pkB, err := crypto.HexToECDSA(common.DefaultPrivKeyBob)
require.NoError(t, err)
authAlice, err := bind.NewKeyedTransactorWithChainID(pk_a, big.NewInt(common.GanacheChainID))
authAlice, err := bind.NewKeyedTransactorWithChainID(pkA, big.NewInt(common.GanacheChainID))
authAlice.Value = big.NewInt(10)
require.NoError(t, err)
authBob, err := bind.NewKeyedTransactorWithChainID(pk_b, big.NewInt(common.GanacheChainID))
authBob, err := bind.NewKeyedTransactorWithChainID(pkB, big.NewInt(common.GanacheChainID))
require.NoError(t, err)
aliceBalanceBefore, err := conn.BalanceAt(context.Background(), authAlice.From, nil)
@@ -160,7 +157,8 @@ func TestSwap_Claim(t *testing.T) {
// copy(pkBobFixedY[:], reverse(pubKeyBobY.Bytes()))
copy(pkBobFixedY[:], reverse(secp256k1BobY))
contractAddress, deployTx, swap, err := DeploySwapDLEQ(authAlice, conn, setBigIntLE(pkBobFixedX[:]), setBigIntLE(pkBobFixedY[:]), setBigIntLE(pkAliceFixedX[:]), setBigIntLE(pkAliceFixedY[:]))
contractAddress, deployTx, swap, err := DeploySwapDLEQ(authAlice, conn, setBigIntLE(pkBobFixedX[:]),
setBigIntLE(pkBobFixedY[:]), setBigIntLE(pkAliceFixedX[:]), setBigIntLE(pkAliceFixedY[:]))
require.NoError(t, err)
fmt.Println("Deploy Tx Gas Cost:", deployTx.Gas())
@@ -185,7 +183,8 @@ func TestSwap_Claim(t *testing.T) {
// Bob tries to claim before Alice has called ready, should fail
s := big.NewInt(0).SetBytes(reverse(secretBob))
fmt.Println("Secret:", hex.EncodeToString(reverse(secretBob)))
fmt.Println("PubKey:", hex.EncodeToString(reverse(pubKeyBobX.Bytes())), hex.EncodeToString(reverse(pubKeyBobY.Bytes())))
fmt.Println("PubKey:", hex.EncodeToString(reverse(pubKeyBobX.Bytes())),
hex.EncodeToString(reverse(pubKeyBobY.Bytes())))
_, err = swap.Claim(txOptsBob, s)
require.Regexp(t, ".*'isReady == false' cannot claim yet!", err)
@@ -226,35 +225,36 @@ func TestSwap_Refund_Within_T0(t *testing.T) {
require.NoError(t, err)
// pubKeyAlice := keyPairAlice.PublicKeyPair().SpendKey().Bytes()
pubKeyAliceX, pubKeyAliceY := monero.PublicSpendOnSecp256k1(keyPairAlice.SpendKeyBytes())
fmt.Println("pubKeyAliceX: ", hex.EncodeToString(pubKeyAliceX.Bytes()), "pubKeyAliceY: ", hex.EncodeToString(pubKeyAliceY.Bytes()))
fmt.Println("pubKeyAliceX: ", hex.EncodeToString(pubKeyAliceX.Bytes()),
"pubKeyAliceY: ", hex.EncodeToString(pubKeyAliceY.Bytes()))
// Alice generates DLEQ proof - this binary file is transmitted to Bob via some offchain protocol
fmt.Println("kAlice: ", keyPairAlice.SpendKeyBytes())
kAliceHex := hex.EncodeToString(keyPairAlice.SpendKeyBytes())
fmt.Println("kAliceHex: ", kAliceHex)
out, err := exec.Command("../target/debug/dleq-gen", kAliceHex, "../dleq-file-exchange/dleq_proof_alice.dat").Output()
aliceHex := hex.EncodeToString(keyPairAlice.SpendKeyBytes())
fmt.Println("aliceHex: ", aliceHex)
out, err := exec.Command("../target/debug/dleq-gen", aliceHex, "../dleq-file-exchange/dleq_proof_alice.dat").Output()
require.NoError(t, err)
fmt.Printf("%s\n", out)
// keyAlease, err := hex.DecodeString("e32ad36ce8e59156aa416da9c9f41a7abc59f6b5f1dd1c2079e8ff4e14503090")
keyAlease, err := hex.DecodeString("a6e51afb9662bf2173d807ceaf88938d09a82d1ab2cea3eeb1706eeeb8b6ba03")
require.NoError(t, err)
pubKeyAleaseX, pubKeyAleaseY := monero.PublicSpendOnSecp256k1(keyAlease)
fmt.Println("PubKey:", hex.EncodeToString(reverse(pubKeyAleaseX.Bytes())), hex.EncodeToString(reverse(pubKeyAleaseY.Bytes())))
fmt.Println("PubKey:", hex.EncodeToString(reverse(pubKeyAleaseX.Bytes())),
hex.EncodeToString(reverse(pubKeyAleaseY.Bytes())))
// Bob generates key
keyPairBob, err := monero.GenerateKeys()
require.NoError(t, err)
secretBob := keyPairBob.SpendKeyBytes()
pubKeyBobX, pubKeyBobY := monero.PublicSpendOnSecp256k1(secretBob)
fmt.Println("pubKeyBobX: ", hex.EncodeToString(pubKeyBobX.Bytes()), "pubKeyBobY: ", hex.EncodeToString(pubKeyBobY.Bytes()))
// pubKeyBob := keyPairBob.PublicKeyPair().SpendKey().Bytes()
fmt.Println("pubKeyBobX: ", hex.EncodeToString(pubKeyBobX.Bytes()),
"pubKeyBobY: ", hex.EncodeToString(pubKeyBobY.Bytes()))
kBobHex := hex.EncodeToString(keyPairBob.SpendKeyBytes())
fmt.Println("kBobHex: ", kBobHex)
out, err = exec.Command("../target/debug/dleq-gen", kBobHex, "../dleq-file-exchange/dleq_proof_bob.dat").Output()
bobHex := hex.EncodeToString(keyPairBob.SpendKeyBytes())
fmt.Println("bobHex: ", bobHex)
out, err = exec.Command("../target/debug/dleq-gen", bobHex, "../dleq-file-exchange/dleq_proof_bob.dat").Output()
require.NoError(t, err)
fmt.Println("dleq-gen out: ", (string(out)))
@@ -262,9 +262,6 @@ func TestSwap_Refund_Within_T0(t *testing.T) {
// alice verifies bob's dleq
out, err = exec.Command("../target/debug/dleq-verify", "../dleq-file-exchange/dleq_proof_bob.dat").Output()
// if err != nil {
// fmt.Println("proof verification failed:", err)
// }
require.NoError(t, err)
fmt.Printf("%s\n", out)
BobStrings := strings.Fields(string(out))
@@ -291,10 +288,10 @@ func TestSwap_Refund_Within_T0(t *testing.T) {
conn, err := ethclient.Dial("ws://127.0.0.1:8545")
require.NoError(t, err)
pk_a, err := crypto.HexToECDSA(common.DefaultPrivKeyAlice)
pkA, err := crypto.HexToECDSA(common.DefaultPrivKeyAlice)
require.NoError(t, err)
authAlice, err := bind.NewKeyedTransactorWithChainID(pk_a, big.NewInt(common.GanacheChainID))
authAlice, err := bind.NewKeyedTransactorWithChainID(pkA, big.NewInt(common.GanacheChainID))
require.NoError(t, err)
authAlice.Value = big.NewInt(10)
@@ -314,7 +311,8 @@ func TestSwap_Refund_Within_T0(t *testing.T) {
var pkBobFixedY [32]byte
// copy(pkBobFixedY[:], reverse(pubKeyBobY.Bytes()))
copy(pkBobFixedY[:], reverse(secp256k1BobY))
contractAddress, deployTx, swap, err := DeploySwapDLEQ(authAlice, conn, setBigIntLE(pkBobFixedX[:]), setBigIntLE(pkBobFixedY[:]), setBigIntLE(pkAliceFixedX[:]), setBigIntLE(pkAliceFixedY[:]))
contractAddress, deployTx, swap, err := DeploySwapDLEQ(authAlice, conn, setBigIntLE(pkBobFixedX[:]),
setBigIntLE(pkBobFixedY[:]), setBigIntLE(pkAliceFixedX[:]), setBigIntLE(pkAliceFixedY[:]))
require.NoError(t, err)
fmt.Println("Deploy Tx Gas Cost:", deployTx.Gas())
@@ -327,7 +325,7 @@ func TestSwap_Refund_Within_T0(t *testing.T) {
Signer: authAlice.Signer,
}
// Alice never calls set_ready on the contract, instead she just tries to Refund immidiately
// Alice never calls set_ready on the contract, instead she just tries to Refund immediately
s := big.NewInt(0).SetBytes(reverse(secretAlice))
_, err = swap.Refund(txOpts, s)
require.NoError(t, err)
@@ -336,12 +334,6 @@ func TestSwap_Refund_Within_T0(t *testing.T) {
contractBalance, err := conn.BalanceAt(context.Background(), contractAddress, nil)
require.NoError(t, err)
require.Equal(t, contractBalance.Uint64(), big.NewInt(0).Uint64())
// bytecode, err := conn.CodeAt(context.Background(), contractAddress, nil) // nil is latest block
// require.NoError(t, err)
// require.Empty(t, bytecode)
// require.Equal(t, big.NewInt(0).Sub(bobBalanceAfter, bobBalanceBefore), 10)
}
func TestSwap_Refund_After_T1(t *testing.T) {
@@ -355,35 +347,36 @@ func TestSwap_Refund_After_T1(t *testing.T) {
require.NoError(t, err)
// pubKeyAlice := keyPairAlice.PublicKeyPair().SpendKey().Bytes()
pubKeyAliceX, pubKeyAliceY := monero.PublicSpendOnSecp256k1(keyPairAlice.SpendKeyBytes())
fmt.Println("pubKeyAliceX: ", hex.EncodeToString(pubKeyAliceX.Bytes()), "pubKeyAliceY: ", hex.EncodeToString(pubKeyAliceY.Bytes()))
fmt.Println("pubKeyAliceX: ", hex.EncodeToString(pubKeyAliceX.Bytes()),
"pubKeyAliceY: ", hex.EncodeToString(pubKeyAliceY.Bytes()))
// Alice generates DLEQ proof - this binary file is transmitted to Bob via some offchain protocol
fmt.Println("kAlice: ", keyPairAlice.SpendKeyBytes())
kAliceHex := hex.EncodeToString(keyPairAlice.SpendKeyBytes())
fmt.Println("kAliceHex: ", kAliceHex)
out, err := exec.Command("../target/debug/dleq-gen", kAliceHex, "../dleq-file-exchange/dleq_proof_alice.dat").Output()
aliceHex := hex.EncodeToString(keyPairAlice.SpendKeyBytes())
fmt.Println("aliceHex: ", aliceHex)
out, err := exec.Command("../target/debug/dleq-gen", aliceHex, "../dleq-file-exchange/dleq_proof_alice.dat").Output()
require.NoError(t, err)
fmt.Printf("%s\n", out)
// keyAlease, err := hex.DecodeString("e32ad36ce8e59156aa416da9c9f41a7abc59f6b5f1dd1c2079e8ff4e14503090")
keyAlease, err := hex.DecodeString("a6e51afb9662bf2173d807ceaf88938d09a82d1ab2cea3eeb1706eeeb8b6ba03")
require.NoError(t, err)
pubKeyAleaseX, pubKeyAleaseY := monero.PublicSpendOnSecp256k1(keyAlease)
fmt.Println("PubKey:", hex.EncodeToString(reverse(pubKeyAleaseX.Bytes())), hex.EncodeToString(reverse(pubKeyAleaseY.Bytes())))
fmt.Println("PubKey:", hex.EncodeToString(reverse(pubKeyAleaseX.Bytes())),
hex.EncodeToString(reverse(pubKeyAleaseY.Bytes())))
// Bob generates key
keyPairBob, err := monero.GenerateKeys()
require.NoError(t, err)
secretBob := keyPairBob.SpendKeyBytes()
pubKeyBobX, pubKeyBobY := monero.PublicSpendOnSecp256k1(secretBob)
fmt.Println("pubKeyBobX: ", hex.EncodeToString(pubKeyBobX.Bytes()), "pubKeyBobY: ", hex.EncodeToString(pubKeyBobY.Bytes()))
// pubKeyBob := keyPairBob.PublicKeyPair().SpendKey().Bytes()
fmt.Println("pubKeyBobX: ", hex.EncodeToString(pubKeyBobX.Bytes()),
"pubKeyBobY: ", hex.EncodeToString(pubKeyBobY.Bytes()))
kBobHex := hex.EncodeToString(keyPairBob.SpendKeyBytes())
fmt.Println("kBobHex: ", kBobHex)
out, err = exec.Command("../target/debug/dleq-gen", kBobHex, "../dleq-file-exchange/dleq_proof_bob.dat").Output()
bobHex := hex.EncodeToString(keyPairBob.SpendKeyBytes())
fmt.Println("bobHex: ", bobHex)
out, err = exec.Command("../target/debug/dleq-gen", bobHex, "../dleq-file-exchange/dleq_proof_bob.dat").Output()
require.NoError(t, err)
fmt.Println("dleq-gen out: ", (string(out)))
@@ -391,9 +384,6 @@ func TestSwap_Refund_After_T1(t *testing.T) {
// alice verifies bob's dleq
out, err = exec.Command("../target/debug/dleq-verify", "../dleq-file-exchange/dleq_proof_bob.dat").Output()
// if err != nil {
// fmt.Println("proof verification failed:", err)
// }
require.NoError(t, err)
fmt.Printf("%s\n", out)
BobStrings := strings.Fields(string(out))
@@ -420,10 +410,10 @@ func TestSwap_Refund_After_T1(t *testing.T) {
conn, err := ethclient.Dial("ws://127.0.0.1:8545")
require.NoError(t, err)
pk_a, err := crypto.HexToECDSA(common.DefaultPrivKeyAlice)
pkA, err := crypto.HexToECDSA(common.DefaultPrivKeyAlice)
require.NoError(t, err)
authAlice, err := bind.NewKeyedTransactorWithChainID(pk_a, big.NewInt(common.GanacheChainID))
authAlice, err := bind.NewKeyedTransactorWithChainID(pkA, big.NewInt(common.GanacheChainID))
require.NoError(t, err)
authAlice.Value = big.NewInt(10)
@@ -443,7 +433,8 @@ func TestSwap_Refund_After_T1(t *testing.T) {
var pkBobFixedY [32]byte
// copy(pkBobFixedY[:], reverse(pubKeyBobY.Bytes()))
copy(pkBobFixedY[:], reverse(secp256k1BobY))
contractAddress, deployTx, swap, err := DeploySwapDLEQ(authAlice, conn, setBigIntLE(pkBobFixedX[:]), setBigIntLE(pkBobFixedY[:]), setBigIntLE(pkAliceFixedX[:]), setBigIntLE(pkAliceFixedY[:]))
contractAddress, deployTx, swap, err := DeploySwapDLEQ(authAlice, conn, setBigIntLE(pkBobFixedX[:]),
setBigIntLE(pkBobFixedY[:]), setBigIntLE(pkAliceFixedX[:]), setBigIntLE(pkAliceFixedY[:]))
require.NoError(t, err)
fmt.Println("Deploy Tx Gas Cost:", deployTx.Gas())