1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
//! NpubCash integration for CDK Wallet
//!
//! This module provides integration between the CDK wallet and the NpubCash service,
//! allowing wallets to sync quotes, subscribe to updates, and manage NpubCash settings.
use std::sync::Arc;
use cdk_npubcash::{JwtAuthProvider, NpubCashClient, Quote};
use tracing::instrument;
use crate::error::Error;
use crate::nuts::SecretKey;
use crate::wallet::types::{MintQuote, TransactionDirection};
use crate::wallet::Wallet;
/// KV store namespace for npubcash-related data
pub const NPUBCASH_KV_NAMESPACE: &str = "npubcash";
/// KV store key for the last fetch timestamp (stored as u64 Unix timestamp)
const LAST_FETCH_TIMESTAMP_KEY: &str = "last_fetch_timestamp";
/// KV store key for the active mint URL
pub const ACTIVE_MINT_KEY: &str = "active_mint";
impl Wallet {
/// Enable NpubCash integration for this wallet
///
/// # Arguments
///
/// * `npubcash_url` - Base URL of the NpubCash service (e.g., "<https://npubx.cash>")
///
/// # Errors
///
/// Returns an error if the NpubCash client cannot be initialized
#[instrument(skip(self))]
pub async fn enable_npubcash(&self, npubcash_url: String) -> Result<(), Error> {
let keys = self.derive_npubcash_keys()?;
let auth_provider = Arc::new(JwtAuthProvider::new(npubcash_url.clone(), keys));
let client = Arc::new(NpubCashClient::new(npubcash_url.clone(), auth_provider));
let mut npubcash = self.npubcash_client.write().await;
*npubcash = Some(client.clone());
drop(npubcash);
tracing::info!("NpubCash integration enabled");
// Automatically set the mint URL on the NpubCash server
let mint_url = self.mint_url.to_string();
match client.set_mint_url(&mint_url).await {
Ok(_) => {
tracing::info!(
"Mint URL '{}' set on NpubCash server at '{}'",
mint_url,
npubcash_url
);
}
Err(e) => {
tracing::warn!(
"Failed to set mint URL on NpubCash server: {}. Quotes may use server default.",
e
);
}
}
Ok(())
}
/// Derive Nostr keys from wallet seed for NpubCash authentication
///
/// This uses the first 32 bytes of the wallet seed to derive a Nostr keypair.
///
/// # Errors
///
/// Returns an error if the key derivation fails
fn derive_npubcash_keys(&self) -> Result<nostr_sdk::Keys, Error> {
use nostr_sdk::SecretKey;
let secret_key = SecretKey::from_slice(&self.seed[..32])
.map_err(|e| Error::Custom(format!("Failed to derive Nostr keys: {}", e)))?;
Ok(nostr_sdk::Keys::new(secret_key))
}
/// Get the Nostr keys used for NpubCash authentication
///
/// Returns the derived Nostr keys from the wallet seed.
/// These keys are used for authenticating with the NpubCash service.
///
/// # Errors
///
/// Returns an error if the key derivation fails
pub fn get_npubcash_keys(&self) -> Result<nostr_sdk::Keys, Error> {
self.derive_npubcash_keys()
}
/// Helper to get NpubCash client reference
///
/// # Errors
///
/// Returns an error if NpubCash is not enabled
async fn get_npubcash_client(&self) -> Result<Arc<NpubCashClient>, Error> {
self.npubcash_client
.read()
.await
.clone()
.ok_or_else(|| Error::Custom("NpubCash not enabled".to_string()))
}
/// Helper to process npubcash quotes and add them to the wallet
///
/// # Errors
///
/// Returns an error if adding quotes fails
async fn process_npubcash_quotes(&self, quotes: Vec<Quote>) -> Result<Vec<MintQuote>, Error> {
let mut mint_quotes = Vec::with_capacity(quotes.len());
for quote in quotes {
if let Some(mint_quote) = self.add_npubcash_mint_quote(quote).await? {
mint_quotes.push(mint_quote);
}
}
Ok(mint_quotes)
}
/// Sync quotes from NpubCash and add them to the wallet
///
/// This method fetches quotes from the last stored fetch timestamp and updates
/// the timestamp after successful fetch. If no timestamp is stored, it fetches
/// all quotes.
///
/// # Errors
///
/// Returns an error if NpubCash is not enabled or the sync fails
#[instrument(skip(self))]
pub async fn sync_npubcash_quotes(&self) -> Result<Vec<MintQuote>, Error> {
let client = self.get_npubcash_client().await?;
// Get the last fetch timestamp from KV store
let since = self.get_last_npubcash_fetch_timestamp().await?;
let quotes = client
.get_quotes(since)
.await
.map_err(|e| Error::Custom(format!("Failed to sync quotes: {}", e)))?;
// Update the last fetch timestamp to the max created_at from fetched quotes
if let Some(max_ts) = quotes.iter().map(|q| q.created_at).max() {
self.set_last_npubcash_fetch_timestamp(max_ts).await?;
}
self.process_npubcash_quotes(quotes).await
}
/// Sync quotes from NpubCash since a specific timestamp and add them to the wallet
///
/// # Arguments
///
/// * `since` - Unix timestamp to fetch quotes from
///
/// # Errors
///
/// Returns an error if NpubCash is not enabled or the sync fails
#[instrument(skip(self))]
pub async fn sync_npubcash_quotes_since(&self, since: u64) -> Result<Vec<MintQuote>, Error> {
let client = self.get_npubcash_client().await?;
let quotes = client
.get_quotes(Some(since))
.await
.map_err(|e| Error::Custom(format!("Failed to sync quotes: {}", e)))?;
self.process_npubcash_quotes(quotes).await
}
/// Create a stream that continuously polls NpubCash and yields proofs as payments arrive
///
/// # Arguments
///
/// * `split_target` - How to split the minted proofs
/// * `spending_conditions` - Optional spending conditions for the minted proofs
/// * `poll_interval` - How often to check for new quotes
pub fn npubcash_proof_stream(
&self,
split_target: cdk_common::amount::SplitTarget,
spending_conditions: Option<crate::nuts::SpendingConditions>,
poll_interval: std::time::Duration,
) -> crate::wallet::streams::npubcash::WalletNpubCashProofStream {
crate::wallet::streams::npubcash::WalletNpubCashProofStream::new(
self.clone(),
poll_interval,
split_target,
spending_conditions,
)
}
/// Set the mint URL in NpubCash settings
///
/// # Arguments
///
/// * `mint_url` - The mint URL to set
///
/// # Errors
///
/// Returns an error if NpubCash is not enabled or the update fails
#[instrument(skip(self, mint_url))]
pub async fn set_npubcash_mint_url(
&self,
mint_url: impl Into<String>,
) -> Result<cdk_npubcash::UserResponse, Error> {
let client = self.get_npubcash_client().await?;
client
.set_mint_url(mint_url)
.await
.map_err(|e| Error::Custom(e.to_string()))
}
/// Add an NpubCash quote to the wallet's mint quote database
///
/// Converts an NpubCash quote to a wallet MintQuote and stores it using the
/// NpubCash-derived secret key for signing.
///
/// # Arguments
///
/// * `npubcash_quote` - The NpubCash quote to add
///
/// # Errors
///
/// Returns an error if the conversion fails or the database operation fails
#[instrument(skip(self))]
pub async fn add_npubcash_mint_quote(
&self,
npubcash_quote: cdk_npubcash::Quote,
) -> Result<Option<MintQuote>, Error> {
let npubcash_keys = self.derive_npubcash_keys()?;
let secret_key = SecretKey::from_slice(&npubcash_keys.secret_key().to_secret_bytes())
.map_err(|e| Error::Custom(format!("Failed to convert secret key: {}", e)))?;
let mut mint_quote: MintQuote = npubcash_quote.into();
mint_quote.secret_key = Some(secret_key);
let exists = self
.list_transactions(Some(TransactionDirection::Incoming))
.await?
.iter()
.any(|tx| tx.quote_id.as_ref() == Some(&mint_quote.id));
if exists {
return Ok(None);
}
self.localstore.add_mint_quote(mint_quote.clone()).await?;
tracing::info!("Added NpubCash quote {} to wallet database", mint_quote.id);
Ok(Some(mint_quote))
}
/// Get reference to the NpubCash client if enabled
pub async fn npubcash_client(&self) -> Option<Arc<NpubCashClient>> {
self.npubcash_client.read().await.clone()
}
/// Check if NpubCash is enabled for this wallet
pub async fn is_npubcash_enabled(&self) -> bool {
self.npubcash_client.read().await.is_some()
}
/// Get the last fetch timestamp from KV store
///
/// Returns the Unix timestamp of the last successful npubcash fetch,
/// or `None` if no fetch has been recorded yet.
async fn get_last_npubcash_fetch_timestamp(&self) -> Result<Option<u64>, Error> {
let value = self
.localstore
.kv_read(NPUBCASH_KV_NAMESPACE, "", LAST_FETCH_TIMESTAMP_KEY)
.await?;
match value {
Some(bytes) => {
let timestamp =
u64::from_be_bytes(bytes.try_into().map_err(|_| {
Error::Custom("Invalid timestamp format in KV store".into())
})?);
Ok(Some(timestamp))
}
None => Ok(None),
}
}
/// Store the last fetch timestamp in KV store
///
/// # Arguments
///
/// * `timestamp` - Unix timestamp of the fetch
async fn set_last_npubcash_fetch_timestamp(&self, timestamp: u64) -> Result<(), Error> {
self.localstore
.kv_write(
NPUBCASH_KV_NAMESPACE,
"",
LAST_FETCH_TIMESTAMP_KEY,
×tamp.to_be_bytes(),
)
.await?;
Ok(())
}
}