rpc

package
v0.4.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 14, 2023 License: LGPL-3.0 Imports: 43 Imported by: 0

Documentation

Overview

Package rpc provides the HTTP server for incoming JSON-RPC and websocket requests to swapd from the local host. The answers to these queries come from 3 subsystems: net, personal and swap.

Index

Constants

View Source
const (
	DaemonNamespace   = "daemon"   //nolint:revive
	DatabaseNamespace = "database" //nolint:revive
	NetNamespace      = "net"      //nolint:revive
	PersonalName      = "personal" //nolint:revive
	SwapNamespace     = "swap"     //nolint:revive
)

Variables

This section is empty.

Functions

func AllNamespaces

func AllNamespaces() map[string]struct{}

AllNamespaces returns a map with all RPC namespaces set for usage in the config.

func NewPrometheusRegistry added in v0.2.2

func NewPrometheusRegistry() (*prometheus.Registry, error)

NewPrometheusRegistry returns a new prometheus registry with default collectors registered

Types

type CancelRequest

type CancelRequest struct {
	OfferID types.Hash `json:"offerID" validate:"required"`
}

CancelRequest ...

type CancelResponse

type CancelResponse struct {
	Status types.Status `json:"status" validate:"required"`
}

CancelResponse ...

type ClearOffersRequest

type ClearOffersRequest struct {
	OfferIDs []types.Hash `json:"offerIDs" validate:"dive,required"`
}

ClearOffersRequest ...

type Codec

type Codec struct{}

Codec ...

func NewCodec

func NewCodec() *Codec

NewCodec ...

func (*Codec) NewRequest

func (c *Codec) NewRequest(req *http.Request) rpc.CodecRequest

NewRequest ...

type CodecRequest

type CodecRequest struct {
	*json2.CodecRequest
}

CodecRequest ...

func (*CodecRequest) Method

func (cr *CodecRequest) Method() (string, error)

Method ...

type Config

type Config struct {
	Ctx             context.Context
	Env             common.Environment
	Address         string // "IP:port"
	Net             Net
	XMRTaker        XMRTaker        // nil on bootnodes
	XMRMaker        XMRMaker        // nil on bootnodes
	ProtocolBackend ProtocolBackend // nil on bootnodes
	RecoveryDB      RecoveryDB      // nil on bootnodes
	Namespaces      map[string]struct{}
}

Config ...

type DaemonService

type DaemonService struct {
	// contains filtered or unexported fields
}

DaemonService handles RPC requests for swapd version, administration and (in the future) status requests.

func NewDaemonService

func NewDaemonService(stopServer func(), env common.Environment, swapCreatorAddr *ethcommon.Address) *DaemonService

NewDaemonService creates a new daemon service. `swapCreatorAddr` is optional and not set by bootnodes.

func (*DaemonService) Shutdown

func (s *DaemonService) Shutdown(_ *http.Request, _ *any, _ *any) error

Shutdown swapd

func (*DaemonService) Version

func (s *DaemonService) Version(_ *http.Request, _ *any, resp *VersionResponse) error

Version returns version & misc info about swapd and its dependencies

type DatabaseService

type DatabaseService struct {
	// contains filtered or unexported fields
}

DatabaseService ...

func NewDatabaseService

func NewDatabaseService(rdb RecoveryDB) *DatabaseService

NewDatabaseService returns a new DatabaseService.

func (*DatabaseService) GetContractSwapInfo

func (s *DatabaseService) GetContractSwapInfo(
	_ *http.Request,
	req *GetContractSwapInfoRequest,
	resp *GetContractSwapInfoResponse,
) error

GetContractSwapInfo returns the contract swap info for the given swap ID from the database.

func (*DatabaseService) GetSwapSecret

func (s *DatabaseService) GetSwapSecret(
	_ *http.Request,
	req *GetSwapSecretRequest,
	resp *GetSwapSecretResponse,
) error

GetSwapSecret returns our swap secret for the given swap ID from the database.

type GetContractSwapInfoRequest

type GetContractSwapInfoRequest struct {
	OfferID types.Hash `json:"offerID" validate:"required"`
}

GetContractSwapInfoRequest ...

type GetContractSwapInfoResponse

type GetContractSwapInfoResponse struct {
	StartNumber     *big.Int                   `json:"startBlockNumber" validate:"required"`
	SwapID          types.Hash                 `json:"swapID" validate:"required"`
	Swap            *contracts.SwapCreatorSwap `json:"swap" validate:"required"`
	SwapCreatorAddr ethcommon.Address          `json:"swapCreatorAddr" validate:"required"`
}

GetContractSwapInfoResponse ...

type GetOffersResponse

type GetOffersResponse struct {
	PeerID peer.ID        `json:"peerID" validate:"required"`
	Offers []*types.Offer `json:"offers" validate:"dive,required"`
}

GetOffersResponse ...

type GetOngoingRequest

type GetOngoingRequest struct {
	OfferID *types.Hash `json:"offerID,omitempty"`
}

GetOngoingRequest ...

type GetOngoingResponse

type GetOngoingResponse struct {
	Swaps []*OngoingSwap `json:"swaps" validate:"dive,required"`
}

GetOngoingResponse ...

type GetPastRequest

type GetPastRequest struct {
	OfferID *types.Hash `json:"offerID,omitempty"`
}

GetPastRequest ...

type GetPastResponse

type GetPastResponse struct {
	Swaps []*PastSwap `json:"swaps" validate:"dive,required"`
}

GetPastResponse ...

type GetStatusRequest

type GetStatusRequest struct {
	ID types.Hash `json:"id" validate:"required"`
}

GetStatusRequest ...

type GetStatusResponse

type GetStatusResponse struct {
	Status      types.Status `json:"status" validate:"required"`
	Description string       `json:"info" validate:"required"`
	StartTime   time.Time    `json:"startTime" validate:"required"`
}

GetStatusResponse ...

type GetSwapSecretRequest

type GetSwapSecretRequest struct {
	OfferID types.Hash `json:"offerID" validate:"required"`
}

GetSwapSecretRequest ...

type GetSwapSecretResponse

type GetSwapSecretResponse struct {
	Secret *mcrypto.PrivateSpendKey `json:"secret" validate:"required"`
}

GetSwapSecretResponse ...

type GetSwapTimeoutResponse

type GetSwapTimeoutResponse struct {
	Timeout uint64 `json:"timeout"` // timeout in seconds
}

GetSwapTimeoutResponse ...

type ManualTransactionRequest added in v0.2.1

type ManualTransactionRequest struct {
	OfferID types.Hash `json:"offerID" validate:"required"`
}

ManualTransactionRequest is used to call swap_claim or swap_refund.

type ManualTransactionResponse added in v0.2.1

type ManualTransactionResponse struct {
	TxHash types.Hash `json:"txHash" validate:"required"`
}

ManualTransactionResponse is returned from swap_claim or swap_refund and contains the transaction hash of the claim or refund transaction.

type Metrics added in v0.2.2

type Metrics struct {
	// contains filtered or unexported fields
}

Metrics represents our prometheus metrics

func SetupMetrics added in v0.2.2

func SetupMetrics(
	ctx context.Context,
	reg *prometheus.Registry,
	net Net,
	pb ProtocolBackend,
	maker XMRMaker,
) *Metrics

SetupMetrics creates prometheus metrics and returns a new Metrics

type Net

type Net interface {
	PeerID() peer.ID
	ConnectedPeers() []string
	Addresses() []ma.Multiaddr
	Discover(provides string, searchTime time.Duration) ([]peer.ID, error)
	Query(who peer.ID) (*message.QueryResponse, error)
	Initiate(who peer.AddrInfo, sendKeysMessage common.Message, s common.SwapStateNet) error
	CloseProtocolStream(types.Hash)
}

Net contains the network-related functions required by the rpc service.

type NetService

type NetService struct {
	// contains filtered or unexported fields
}

NetService is the RPC service prefixed by net_.

func NewNetService

func NewNetService(
	ctx context.Context,
	net Net,
	xmrtaker XMRTaker,
	xmrmaker XMRMaker,
	pb ProtocolBackend,
	sm swap.Manager,
	isBootnode bool,
) *NetService

NewNetService ...

func (*NetService) Addresses

func (s *NetService) Addresses(_ *http.Request, _ *interface{}, resp *rpctypes.AddressesResponse) error

Addresses returns the local listening multi-addresses. Note that local listening addresses do not correspond to what remote peers connect to unless your host has a public IP directly attached to a local interface.

func (*NetService) Discover

Discover discovers peers over the network that provide a certain coin up for `SearchTime` duration of time.

func (*NetService) MakeOffer

MakeOffer creates and advertises a new swap offer.

func (*NetService) Pairs added in v0.4.2

Pairs returns all currently available pairs from offers of all peers

func (*NetService) Peers

func (s *NetService) Peers(_ *http.Request, _ *interface{}, resp *rpctypes.PeersResponse) error

Peers returns the peers that this node is currently connected to.

func (*NetService) QueryAll

QueryAll discovers peers who provide a certain coin and queries all of them for their current offers.

func (*NetService) QueryPeer

QueryPeer queries a peer for the coins they provide, their maximum amounts, and desired exchange rate.

func (*NetService) TakeOffer

func (s *NetService) TakeOffer(
	_ *http.Request,
	req *rpctypes.TakeOfferRequest,
	_ *interface{},
) error

TakeOffer initiates a swap with the given peer by taking an offer they've made.

type OngoingSwap

type OngoingSwap struct {
	ID                        types.Hash          `json:"id" validate:"required"`
	Provided                  coins.ProvidesCoin  `json:"provided" validate:"required"`
	EthAsset                  types.EthAsset      `json:"ethAsset"`
	ProvidedAmount            *apd.Decimal        `json:"providedAmount" validate:"required"`
	ExpectedAmount            *apd.Decimal        `json:"expectedAmount" validate:"required"`
	ExchangeRate              *coins.ExchangeRate `json:"exchangeRate" validate:"required"`
	Status                    types.Status        `json:"status" validate:"required"`
	LastStatusUpdateTime      time.Time           `json:"lastStatusUpdateTime" validate:"required"`
	StartTime                 time.Time           `json:"startTime" validate:"required"`
	Timeout1                  *time.Time          `json:"timeout1"`
	Timeout2                  *time.Time          `json:"timeout2"`
	EstimatedTimeToCompletion time.Duration       `json:"estimatedTimeToCompletion" validate:"required"`
}

OngoingSwap represents an ongoing swap returned by swap_getOngoing.

type PastSwap

type PastSwap struct {
	ID             types.Hash          `json:"id" validate:"required"`
	Provided       coins.ProvidesCoin  `json:"provided" validate:"required"`
	EthAsset       types.EthAsset      `json:"ethAsset"`
	ProvidedAmount *apd.Decimal        `json:"providedAmount" validate:"required"`
	ExpectedAmount *apd.Decimal        `json:"expectedAmount" validate:"required"`
	RelayerFee     *apd.Decimal        `json:"relayerFee"`
	ExchangeRate   *coins.ExchangeRate `json:"exchangeRate" validate:"required"`
	Status         types.Status        `json:"status" validate:"required"`
	StartTime      time.Time           `json:"startTime" validate:"required"`
	EndTime        *time.Time          `json:"endTime"`
}

PastSwap represents a past swap returned by swap_getPast.

type PersonalService

type PersonalService struct {
	// contains filtered or unexported fields
}

PersonalService handles private keys and wallets.

func NewPersonalService

func NewPersonalService(ctx context.Context, xmrmaker XMRMaker, pb ProtocolBackend) *PersonalService

NewPersonalService ...

func (*PersonalService) Balances

Balances returns combined information of both the Monero and Ethereum account addresses and balances.

func (*PersonalService) GetSwapTimeout

func (s *PersonalService) GetSwapTimeout(_ *http.Request, _ *interface{}, resp *GetSwapTimeoutResponse) error

GetSwapTimeout ...

func (*PersonalService) SetGasPrice

func (s *PersonalService) SetGasPrice(_ *http.Request, req *SetGasPriceRequest, _ *interface{}) error

SetGasPrice sets the gas price (in Wei) to be used for ethereum transactions.

func (*PersonalService) SetSwapTimeout

func (s *PersonalService) SetSwapTimeout(_ *http.Request, req *SetSwapTimeoutRequest, _ *interface{}) error

SetSwapTimeout ...

func (*PersonalService) SweepETH added in v0.3.0

func (s *PersonalService) SweepETH(_ *http.Request, req *SweepETHRequest, resp *SweepETHResponse) error

SweepETH sweeps all ETH out of the swapd wallet.

func (*PersonalService) SweepXMR added in v0.2.1

func (s *PersonalService) SweepXMR(_ *http.Request, req *SweepXMRRequest, resp *SweepXMRResponse) error

SweepXMR sweeps XMR from the swapd wallet.

func (*PersonalService) TokenInfo

TokenInfo looks up the ERC20 token's metadata

func (*PersonalService) TransferETH added in v0.2.1

func (s *PersonalService) TransferETH(_ *http.Request, req *TransferETHRequest, resp *TransferETHResponse) error

TransferETH transfers ETH from the swapd wallet.

func (*PersonalService) TransferXMR added in v0.2.1

func (s *PersonalService) TransferXMR(_ *http.Request, req *TransferXMRRequest, resp *TransferXMRResponse) error

TransferXMR transfers XMR from the swapd wallet.

type Protocol

type Protocol interface {
	Provides() coins.ProvidesCoin
	GetOngoingSwapState(types.Hash) common.SwapState
}

Protocol represents the functions required by the rpc service into the protocol handler.

type ProtocolBackend

type ProtocolBackend interface {
	Ctx() context.Context
	Env() common.Environment
	SetSwapTimeout(timeout time.Duration)
	SwapTimeout() time.Duration
	SwapManager() swap.Manager
	SwapCreatorAddr() ethcommon.Address
	SetXMRDepositAddress(*mcrypto.Address, types.Hash)
	ClearXMRDepositAddress(types.Hash)
	ETHClient() extethclient.EthClient
	TransferXMR(to *mcrypto.Address, amount *coins.PiconeroAmount) (string, error)
	SweepXMR(to *mcrypto.Address) ([]string, error)
	TransferETH(to ethcommon.Address, amount *coins.WeiAmount, gasLimit *uint64) (*ethtypes.Receipt, error)
	SweepETH(to ethcommon.Address) (*ethtypes.Receipt, error)
}

ProtocolBackend represents protocol/backend.Backend

type RecoveryDB

type RecoveryDB interface {
	GetContractSwapInfo(id types.Hash) (*db.EthereumSwapInfo, error)
	GetSwapPrivateKey(id types.Hash) (*mcrypto.PrivateSpendKey, error)
	GetCounterpartySwapPrivateKey(id types.Hash) (*mcrypto.PrivateSpendKey, error)
}

RecoveryDB contains methods for retrieving swap recovery info from the database.

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server represents the JSON-RPC server

func NewServer

func NewServer(cfg *Config) (*Server, error)

NewServer ...

func (*Server) Port added in v0.3.0

func (s *Server) Port() uint16

Port returns the localhost port used for HTTP and websocket requests

func (*Server) Start

func (s *Server) Start() error

Start starts the JSON-RPC and Websocket server.

func (*Server) Stop

func (s *Server) Stop() error

Stop the JSON-RPC and websockets server. If server's context is not cancelled, a graceful shutdown happens where existing connections are serviced until disconnected. If the context is cancelled, the shutdown is immediate.

type SetGasPriceRequest

type SetGasPriceRequest struct {
	GasPrice uint64 `json:"gasPrice" validate:"required"`
}

SetGasPriceRequest ...

type SetSwapTimeoutRequest

type SetSwapTimeoutRequest struct {
	Timeout uint64 `json:"timeout" validate:"required"` // timeout in seconds
}

SetSwapTimeoutRequest ...

type SuggestedExchangeRateResponse

type SuggestedExchangeRateResponse struct {
	ETHUpdatedAt time.Time           `json:"ethUpdatedAt" validate:"required"`
	ETHPrice     *apd.Decimal        `json:"ethPrice" validate:"required"`
	XMRUpdatedAt time.Time           `json:"xmrUpdatedAt" validate:"required"`
	XMRPrice     *apd.Decimal        `json:"xmrPrice" validate:"required"`
	ExchangeRate *coins.ExchangeRate `json:"exchangeRate" validate:"required"`
}

SuggestedExchangeRateResponse ...

type SwapService

type SwapService struct {
	// contains filtered or unexported fields
}

SwapService handles information about ongoing or past swaps.

func NewSwapService

func NewSwapService(
	ctx context.Context,
	sm swap.Manager,
	xmrtaker XMRTaker,
	xmrmaker XMRMaker,
	net Net,
	b ProtocolBackend,
	rdb RecoveryDB,
) *SwapService

NewSwapService ...

func (*SwapService) Cancel

func (s *SwapService) Cancel(_ *http.Request, req *CancelRequest, resp *CancelResponse) error

Cancel attempts to cancel the currently ongoing swap, if there is one.

func (*SwapService) Claim added in v0.2.1

Claim calls the `claim` method on the swap contract given swap's offer ID. It uses the swap recovery info stored in the database to do so. It does not require the swap to be ongoing. This is meant as a fail-safe in case of some unknown swap error. It returns the transaction hash of the claim transaction.

func (*SwapService) ClearOffers

func (s *SwapService) ClearOffers(_ *http.Request, req *ClearOffersRequest, _ *interface{}) error

ClearOffers clears our provided offers. If there are no offers provided, it clears all offers.

func (*SwapService) GetOffers

func (s *SwapService) GetOffers(_ *http.Request, _ *interface{}, resp *GetOffersResponse) error

GetOffers returns our currently available offers.

func (*SwapService) GetOngoing

func (s *SwapService) GetOngoing(_ *http.Request, req *GetOngoingRequest, resp *GetOngoingResponse) error

GetOngoing returns information about an ongoing swap given its ID. If no ID is provided, all ongoing swaps are returned. It sorts them in order from newest to oldest.

func (*SwapService) GetPast

func (s *SwapService) GetPast(_ *http.Request, req *GetPastRequest, resp *GetPastResponse) error

GetPast returns information about a past swap given its ID. If no ID is provided, all past swaps are returned. It sorts them in order from newest to oldest.

func (*SwapService) GetStatus

func (s *SwapService) GetStatus(_ *http.Request, req *GetStatusRequest, resp *GetStatusResponse) error

GetStatus returns the status of the ongoing swap, if there is one.

func (*SwapService) Refund added in v0.2.1

Refund calls the `refund` method on the swap contract given swap's offer ID. It uses the swap recovery info stored in the database to do so. It does not require the swap to be ongoing. This is meant as a fail-safe in case of some unknown swap error. It returns the transaction hash of the refund transaction.

func (*SwapService) SuggestedExchangeRate

func (s *SwapService) SuggestedExchangeRate(_ *http.Request, _ *interface{}, resp *SuggestedExchangeRateResponse) error

SuggestedExchangeRate returns the current mainnet exchange rate, expressed as the XMR/ETH price.

type SweepETHRequest added in v0.3.0

type SweepETHRequest struct {
	To ethcommon.Address `json:"to" validate:"required"`
}

SweepETHRequest is JSON-RPC request object for SweepETH

type SweepETHResponse added in v0.3.0

type SweepETHResponse struct {
	TxHash ethcommon.Hash `json:"txHash"` // Hash of sweep transfer transaction
}

SweepETHResponse is JSON-RPC response object for SweepETH

type SweepXMRRequest added in v0.2.1

type SweepXMRRequest struct {
	To *mcrypto.Address `json:"to" validate:"required"`
}

SweepXMRRequest ...

type SweepXMRResponse added in v0.2.1

type SweepXMRResponse struct {
	TxIDs []string `json:"txIds"`
}

SweepXMRResponse ...

type TransferETHRequest added in v0.2.1

type TransferETHRequest struct {
	To       ethcommon.Address `json:"to" validate:"required"`
	Amount   *apd.Decimal      `json:"amount" validate:"required"`
	GasLimit *uint64           `json:"gasLimit,omitempty"`
}

TransferETHRequest is JSON-RPC request object for TransferETH

type TransferETHResponse added in v0.2.1

type TransferETHResponse struct {
	TxHash   ethcommon.Hash `json:"txHash"`
	GasLimit *uint64        `json:"gasLimit,omitempty"`
}

TransferETHResponse is JSON-RPC response object for TransferETH

type TransferXMRRequest added in v0.2.1

type TransferXMRRequest struct {
	To     *mcrypto.Address `json:"to" validate:"required"`
	Amount *apd.Decimal     `json:"amount" validate:"required"`
}

TransferXMRRequest ...

type TransferXMRResponse added in v0.2.1

type TransferXMRResponse struct {
	TxID string `json:"txID"`
}

TransferXMRResponse ...

type VersionResponse

type VersionResponse struct {
	SwapdVersion    string             `json:"swapdVersion" validate:"required"`
	P2PVersion      string             `json:"p2pVersion" validate:"required"`
	Env             common.Environment `json:"env" validate:"required"`
	SwapCreatorAddr *ethcommon.Address `json:"swapCreatorAddress,omitempty"`
}

VersionResponse contains the version response provided by both swapd and bootnodes. In the case of bootnodes, the swapCreatorAddress is nil.

type XMRMaker

type XMRMaker interface {
	Protocol
	MakeOffer(offer *types.Offer, useRelayer bool) (*types.OfferExtra, error)
	GetOffers() []*types.Offer
	ClearOffers([]types.Hash) error
	GetMoneroBalance() (*mcrypto.Address, *wallet.GetBalanceResponse, error)
}

XMRMaker ...

type XMRTaker

type XMRTaker interface {
	Protocol
	InitiateProtocol(peerID peer.ID, providesAmount *apd.Decimal, offer *types.Offer) (common.SwapState, error)
	ExternalSender(offerID types.Hash) (*txsender.ExternalSender, error)
}

XMRTaker ...

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL