Skip to content

Commit

Permalink
dcr: Allow ticket purchasing for rpc spv wallets
Browse files Browse the repository at this point in the history
  • Loading branch information
JoeGruffins committed May 2, 2024
1 parent e87b19f commit ea5b703
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 14 deletions.
30 changes: 29 additions & 1 deletion client/asset/dcr/dcr.go
Original file line number Diff line number Diff line change
Expand Up @@ -5216,9 +5216,13 @@ func (dcr *ExchangeWallet) StakeStatus() (*asset.TicketStakingStatus, error) {
if !dcr.connected.Load() {
return nil, errors.New("not connected, login first")
}
// Try to get tickets first, because this will error for RPC + SPV wallets.
// Try to get tickets first, because this will error for older RPC + SPV
// wallets.
tickets, err := dcr.tickets(dcr.ctx)
if err != nil {
if errors.Is(err, oldSPVWalletErr) {
return nil, nil
}
return nil, fmt.Errorf("error retrieving tickets: %w", err)
}
sinfo, err := dcr.wallet.StakeInfo(dcr.ctx)
Expand All @@ -5232,6 +5236,16 @@ func (dcr *ExchangeWallet) StakeStatus() (*asset.TicketStakingStatus, error) {
if v := dcr.vspV.Load(); v != nil {
vspURL = v.(*vsp).URL
}
} else {
rpcW, ok := dcr.wallet.(*rpcWallet)
if !ok {
return nil, errors.New("wallet not an *rpcWallet")
}
walletInfo, err := rpcW.walletInfo(dcr.ctx)
if err != nil {
return nil, fmt.Errorf("error retrieving wallet info: %w", err)
}
vspURL = walletInfo.VSP
}
voteChoices, tSpends, treasuryPolicy, err := dcr.wallet.VotingPreferences(dcr.ctx)
if err != nil {
Expand Down Expand Up @@ -5380,6 +5394,20 @@ func (dcr *ExchangeWallet) PurchaseTickets(n int, feeSuggestion uint64) error {
if err != nil {
return fmt.Errorf("error getting balance: %v", err)
}
isRPC := !dcr.isNative()
if isRPC {
rpcW, ok := dcr.wallet.(*rpcWallet)
if !ok {
return errors.New("wallet not an *rpcWallet")
}
walletInfo, err := rpcW.walletInfo(dcr.ctx)
if err != nil {
return fmt.Errorf("error retrieving wallet info: %w", err)
}
if walletInfo.SPV && walletInfo.VSP == "" {
return errors.New("a vsp must best set to purchase tickets with an spv wallet")
}
}
sinfo, err := dcr.wallet.StakeInfo(dcr.ctx)
if err != nil {
return fmt.Errorf("stakeinfo error: %v", err)
Expand Down
3 changes: 3 additions & 0 deletions client/asset/dcr/dcr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -705,6 +705,9 @@ func (c *tRPCClient) RawRequest(_ context.Context, method string, params []json.
Complete: complete,
}
return json.Marshal(&res)

case methodWalletInfo:
return json.Marshal(new(walletjson.WalletInfoResult))
}

return nil, fmt.Errorf("method %v not implemented by (*tRPCClient).RawRequest", method)
Expand Down
56 changes: 44 additions & 12 deletions client/asset/dcr/rpcwallet.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ var (
{Major: 8, Minor: 0, Patch: 0}, // 1.8-pre, just dropped unused ticket RPCs
{Major: 7, Minor: 0, Patch: 0}, // 1.7 release, new gettxout args
}
// From vspWithSPVWalletRPCVersion and later the wallet's current "vsp"
// is included in the walletinfo response and the wallet will no longer
// error on GetTickets with an spv wallet.
vspWithSPVWalletRPCVersion = dex.Semver{Major: 9, Minor: 2, Patch: 0}
)

// RawRequest RPC methods
Expand All @@ -53,6 +57,7 @@ const (
methodSignRawTransaction = "signrawtransaction"
methodSyncStatus = "syncstatus"
methodGetPeerInfo = "getpeerinfo"
methodWalletInfo = "walletinfo"
)

// rpcWallet implements Wallet functionality using an rpc client to communicate
Expand All @@ -63,6 +68,8 @@ type rpcWallet struct {
rpcCfg *rpcclient.ConnConfig
accountsV atomic.Value // XCWalletAccounts

hasSPVTicketFunctions bool

rpcMtx sync.RWMutex
spvMode bool
// rpcConnector is a rpcclient.Client, does not need to be
Expand Down Expand Up @@ -331,56 +338,60 @@ func (w *rpcWallet) handleRPCClientReconnection(ctx context.Context) {
w.log.Debugf("dcrwallet reconnected (%d)", connectCount-1)
w.rpcMtx.RLock()
defer w.rpcMtx.RUnlock()
spv, err := checkRPCConnection(ctx, w.rpcConnector, w.rpcClient, w.log)
spv, hasSPVTicketFunctions, err := checkRPCConnection(ctx, w.rpcConnector, w.rpcClient, w.log)
if err != nil {
w.log.Errorf("dcrwallet reconnect handler error: %v", err)
}
w.spvMode = spv
w.hasSPVTicketFunctions = hasSPVTicketFunctions
}

// checkRPCConnection verifies the dcrwallet connection with the walletinfo RPC
// and sets the spvMode flag accordingly. The spvMode flag is only set after a
// successful check. This method is not safe for concurrent access, and the
// rpcMtx must be at least read locked.
func checkRPCConnection(ctx context.Context, connector rpcConnector, client rpcClient, log dex.Logger) (bool, error) {
func checkRPCConnection(ctx context.Context, connector rpcConnector, client rpcClient, log dex.Logger) (bool, bool, error) {
// Check the required API versions.
versions, err := connector.Version(ctx)
if err != nil {
return false, fmt.Errorf("dcrwallet version fetch error: %w", err)
return false, false, fmt.Errorf("dcrwallet version fetch error: %w", err)
}

ver, exists := versions["dcrwalletjsonrpcapi"]
if !exists {
return false, fmt.Errorf("dcrwallet.Version response missing 'dcrwalletjsonrpcapi'")
return false, false, fmt.Errorf("dcrwallet.Version response missing 'dcrwalletjsonrpcapi'")
}
walletSemver := dex.NewSemver(ver.Major, ver.Minor, ver.Patch)
if !dex.SemverCompatibleAny(compatibleWalletRPCVersions, walletSemver) {
return false, fmt.Errorf("advertised dcrwallet JSON-RPC version %v incompatible with %v",
return false, false, fmt.Errorf("advertised dcrwallet JSON-RPC version %v incompatible with %v",
walletSemver, compatibleWalletRPCVersions)
}

hasSPVTicketFunctions := walletSemver.Major >= vspWithSPVWalletRPCVersion.Major &&
walletSemver.Minor >= vspWithSPVWalletRPCVersion.Minor

ver, exists = versions["dcrdjsonrpcapi"]
if exists {
nodeSemver := dex.NewSemver(ver.Major, ver.Minor, ver.Patch)
if !dex.SemverCompatibleAny(compatibleNodeRPCVersions, nodeSemver) {
return false, fmt.Errorf("advertised dcrd JSON-RPC version %v incompatible with %v",
return false, false, fmt.Errorf("advertised dcrd JSON-RPC version %v incompatible with %v",
nodeSemver, compatibleNodeRPCVersions)
}
log.Infof("Connected to dcrwallet (JSON-RPC API v%s) proxying dcrd (JSON-RPC API v%s)",
walletSemver, nodeSemver)
return false, nil
return false, false, nil
}

// SPV maybe?
walletInfo, err := client.WalletInfo(ctx)
if err != nil {
return false, fmt.Errorf("walletinfo rpc error: %w", translateRPCCancelErr(err))
return false, false, fmt.Errorf("walletinfo rpc error: %w", translateRPCCancelErr(err))
}
if !walletInfo.SPV {
return false, fmt.Errorf("dcrwallet.Version response missing 'dcrdjsonrpcapi' for non-spv wallet")
return false, false, fmt.Errorf("dcrwallet.Version response missing 'dcrdjsonrpcapi' for non-spv wallet")
}
log.Infof("Connected to dcrwallet (JSON-RPC API v%s) in SPV mode", walletSemver)
return true, nil
return true, hasSPVTicketFunctions, nil
}

// Connect establishes a connection to the previously created rpc client. The
Expand Down Expand Up @@ -426,7 +437,7 @@ func (w *rpcWallet) Connect(ctx context.Context) error {
// fails and we return with a non-nil error, we must shutdown the
// rpc client otherwise subsequent reconnect attempts will be met
// with "websocket client has already connected".
spv, err := checkRPCConnection(ctx, w.rpcConnector, w.rpcClient, w.log)
spv, hasSPVTicketFunctions, err := checkRPCConnection(ctx, w.rpcConnector, w.rpcClient, w.log)
if err != nil {
// The client should still be connected, but if not, do not try to
// shutdown and wait as it could hang.
Expand All @@ -439,6 +450,7 @@ func (w *rpcWallet) Connect(ctx context.Context) error {
}

w.spvMode = spv
w.hasSPVTicketFunctions = hasSPVTicketFunctions

return nil
}
Expand Down Expand Up @@ -1013,10 +1025,16 @@ func (w *rpcWallet) PurchaseTickets(ctx context.Context, n int, _, _ string) ([]
return tickets, nil
}

var oldSPVWalletErr = errors.New("wallet is an older spv wallet")

// Tickets returns active tickets.
func (w *rpcWallet) Tickets(ctx context.Context) ([]*asset.Ticket, error) {
// GetTickets only works for clients with a dcrd backend after version
// 9.2.0
if w.spvMode && !w.hasSPVTicketFunctions {
return nil, oldSPVWalletErr
}
const includeImmature = true
// GetTickets only works for clients with a dcrd backend.
hashes, err := w.rpcClient.GetTickets(ctx, includeImmature)
if err != nil {
return nil, err
Expand Down Expand Up @@ -1199,3 +1217,17 @@ func isAccountLockedErr(err error) bool {
return errors.As(err, &rpcErr) && rpcErr.Code == dcrjson.ErrRPCWalletUnlockNeeded &&
strings.Contains(rpcErr.Message, "account is already locked")
}

// newWalletInfo is walletinfo with a new field found in version 9.2.0+.
//
// TODO: Just use *walletjson.WalletInfoResult after we update to dcrwallet/v4.
type newWalletInfo struct {
*walletjson.WalletInfoResult
VSP string `json:"vsp"`
}

func (w *rpcWallet) walletInfo(ctx context.Context) (*newWalletInfo, error) {
var walletInfo newWalletInfo
err := w.rpcClientRawRequest(ctx, methodWalletInfo, nil, &walletInfo)
return &walletInfo, translateRPCCancelErr(err)
}
2 changes: 1 addition & 1 deletion client/asset/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -1048,7 +1048,7 @@ type TicketStakingStatus struct {
// VSP is the currently set VSP address and fee.
VSP string `json:"vsp"`
// IsRPC will be true if this is an RPC wallet, in which case we can't
// set a new VSP and some other information may not be available.
// set a new VSP.
IsRPC bool `json:"isRPC"`
// Tickets returns current active tickets up until they are voted or
// revoked. Includes unconfirmed tickets.
Expand Down

0 comments on commit ea5b703

Please sign in to comment.