diff --git a/client/asset/dcr/dcr.go b/client/asset/dcr/dcr.go index f592033cdd..d7c8193729 100644 --- a/client/asset/dcr/dcr.go +++ b/client/asset/dcr/dcr.go @@ -5299,9 +5299,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) @@ -5315,6 +5319,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 { @@ -5463,6 +5477,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) diff --git a/client/asset/dcr/dcr_test.go b/client/asset/dcr/dcr_test.go index 92c0c711a3..99dc870e8a 100644 --- a/client/asset/dcr/dcr_test.go +++ b/client/asset/dcr/dcr_test.go @@ -701,6 +701,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) diff --git a/client/asset/dcr/rpcwallet.go b/client/asset/dcr/rpcwallet.go index 4030aea64c..e58771d2f8 100644 --- a/client/asset/dcr/rpcwallet.go +++ b/client/asset/dcr/rpcwallet.go @@ -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 @@ -53,8 +57,17 @@ const ( methodSignRawTransaction = "signrawtransaction" methodSyncStatus = "syncstatus" methodGetPeerInfo = "getpeerinfo" + methodWalletInfo = "walletinfo" ) +var ticketCacheExpiry = time.Second * 10 + +type ticketCache struct { + sync.Mutex + stamp time.Time + tickets []*asset.Ticket +} + // rpcWallet implements Wallet functionality using an rpc client to communicate // with the json-rpc server of an external dcrwallet daemon. type rpcWallet struct { @@ -63,6 +76,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 @@ -72,6 +87,10 @@ type rpcWallet struct { // or a stub for testing. rpcClient rpcClient + // Calling w.rpcClient.GetTickets too close together will return no + // tickets for the second call. A ticket cache alleviates this. + ticketCache *ticketCache + connectCount uint32 // atomic } @@ -177,6 +196,7 @@ func newRPCWallet(settings map[string]string, logger dex.Logger, net dex.Network rpcw := &rpcWallet{ chainParams: chainParams, log: log, + ticketCache: new(ticketCache), } certs, err := os.ReadFile(cfg.RPCCert) @@ -338,56 +358,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 @@ -433,7 +457,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. @@ -446,6 +470,7 @@ func (w *rpcWallet) Connect(ctx context.Context) error { } w.spvMode = spv + w.hasSPVTicketFunctions = hasSPVTicketFunctions return nil } @@ -1030,10 +1055,23 @@ 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) { - const includeImmature = true - // GetTickets only works for clients with a dcrd backend. + return w.tickets(ctx, true) +} + +func (w *rpcWallet) tickets(ctx context.Context, includeImmature bool) ([]*asset.Ticket, error) { + w.ticketCache.Lock() + defer w.ticketCache.Unlock() + if w.ticketCache.stamp.Add(ticketCacheExpiry).After(time.Now()) { + return w.ticketCache.tickets, nil + } + // GetTickets only works for spv clients after version 9.2.0 + if w.spvMode && !w.hasSPVTicketFunctions { + return nil, oldSPVWalletErr + } hashes, err := w.rpcClient.GetTickets(ctx, includeImmature) if err != nil { return nil, err @@ -1090,7 +1128,8 @@ func (w *rpcWallet) Tickets(ctx context.Context) ([]*asset.Ticket, error) { // Spender: ?, }) } - + w.ticketCache.tickets = tickets + w.ticketCache.stamp = time.Now() return tickets, nil } @@ -1216,3 +1255,23 @@ 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) +} + +var _ ticketPager = (*rpcWallet)(nil) + +func (w *rpcWallet) TicketPage(ctx context.Context, scanStart int32, n, skipN int) ([]*asset.Ticket, error) { + return make([]*asset.Ticket, 0), nil +}