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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use cdk_common::{database, AuthToken};
use tokio::sync::RwLock as TokioRwLock;
use zeroize::Zeroize;
use crate::cdk_database::WalletDatabase;
use crate::error::Error;
use crate::mint_url::MintUrl;
use crate::nuts::CurrencyUnit;
use crate::wallet::auth::{AuthMintConnector, AuthWallet};
use crate::wallet::mint_connector::transport::{Async, RateLimitedTransport};
use crate::wallet::mint_connector::{RateLimitedAuthHttpClient, RateLimitedHttpClient};
use crate::wallet::mint_metadata_cache::MintMetadataCache;
use crate::wallet::{
AuthHttpClient, HttpClient, MintConnector, RateLimitConfig, RateLimiterManager,
SubscriptionManager, Wallet,
};
/// Builder for creating a new [`Wallet`]
///
/// Rate limiting: unless a limiter is injected with
/// [`WalletBuilder::with_rate_limiter`], `build()` constructs the wallet's own
/// [`RateLimiterManager`]. Budgets are keyed by the host each request is
/// addressed to, so the wallet's mint, an LNURL service, and an OIDC provider
/// each pace separately. Two wallets built independently do not share a live
/// in-memory budget, only the persisted per-host budget in the KV store. To
/// share one live budget, build them through a
/// [`WalletRepository`](crate::wallet::WalletRepository), which injects one
/// manager into every wallet it creates.
pub struct WalletBuilder {
mint_url: Option<MintUrl>,
unit: Option<CurrencyUnit>,
localstore: Option<Arc<dyn WalletDatabase<database::Error> + Send + Sync>>,
target_proof_count: Option<usize>,
auth_wallet: Option<AuthWallet>,
auth_connector: Option<Arc<dyn AuthMintConnector + Send + Sync>>,
seed: Option<[u8; 64]>,
use_http_subscription: bool,
client: Option<Arc<dyn MintConnector + Send + Sync>>,
metadata_cache_ttl: Option<Duration>,
metadata_cache: Option<Arc<MintMetadataCache>>,
metadata_caches: HashMap<MintUrl, Arc<MintMetadataCache>>,
rate_limit: Option<RateLimitConfig>,
rate_limiter: Option<RateLimiterManager>,
auth_cat: Option<String>,
}
impl std::fmt::Debug for WalletBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WalletBuilder")
.field("mint_url", &self.mint_url)
.field("unit", &self.unit)
.field("target_proof_count", &self.target_proof_count)
.finish_non_exhaustive()
}
}
impl Default for WalletBuilder {
fn default() -> Self {
Self {
mint_url: None,
unit: None,
localstore: None,
target_proof_count: Some(3),
auth_wallet: None,
auth_connector: None,
seed: None,
client: None,
metadata_cache_ttl: Some(Duration::from_secs(3600)),
use_http_subscription: false,
metadata_cache: None,
metadata_caches: HashMap::new(),
rate_limit: Some(RateLimitConfig::default()),
rate_limiter: None,
auth_cat: None,
}
}
}
impl Drop for WalletBuilder {
fn drop(&mut self) {
self.seed.zeroize();
}
}
impl WalletBuilder {
/// Create a new WalletBuilder
pub fn new() -> Self {
Self::default()
}
/// Use HTTP for wallet subscriptions to mint events
pub fn use_http_subscription(mut self) -> Self {
self.use_http_subscription = true;
self
}
/// Set metadata_cache_ttl
///
/// The TTL determines how often the wallet checks the mint for new keysets and information.
///
/// If `None`, the cache will never expire and the wallet will use cached data indefinitely
/// (unless manually refreshed).
///
/// The default value is 1 hour (3600 seconds).
pub fn set_metadata_cache_ttl(mut self, metadata_cache_ttl: Option<Duration>) -> Self {
self.metadata_cache_ttl = metadata_cache_ttl;
self
}
/// If WS is preferred (with fallback to HTTP is it is not supported by the mint) for the wallet
/// subscriptions to mint events
pub fn prefer_ws_subscription(mut self) -> Self {
self.use_http_subscription = false;
self
}
/// Set the mint URL
pub fn mint_url(mut self, mint_url: MintUrl) -> Self {
self.mint_url = Some(mint_url);
self
}
/// Set the currency unit
pub fn unit(mut self, unit: CurrencyUnit) -> Self {
self.unit = Some(unit);
self
}
/// Set the local storage backend
pub fn localstore(
mut self,
localstore: Arc<dyn WalletDatabase<database::Error> + Send + Sync>,
) -> Self {
self.localstore = Some(localstore);
self
}
/// Set the target proof count
pub fn target_proof_count(mut self, count: usize) -> Self {
self.target_proof_count = Some(count);
self
}
/// Set the auth wallet
pub fn auth_wallet(mut self, auth_wallet: AuthWallet) -> Self {
self.auth_wallet = Some(auth_wallet);
self
}
/// Set the auth connector used when an auth wallet is created from mint info
pub fn auth_connector(
mut self,
auth_connector: Arc<dyn AuthMintConnector + Send + Sync>,
) -> Self {
self.auth_connector = Some(auth_connector);
self
}
/// Set the seed bytes
pub fn seed(mut self, seed: [u8; 64]) -> Self {
self.seed.zeroize();
self.seed = Some(seed);
self
}
/// Set a custom client connector
pub fn client<C: MintConnector + 'static + Send + Sync>(mut self, client: C) -> Self {
self.client = Some(Arc::new(client));
self
}
/// Set a custom client connector from Arc
pub fn shared_client(mut self, client: Arc<dyn MintConnector + Send + Sync>) -> Self {
self.client = Some(client);
self
}
/// Set a shared MintMetadataCache
///
/// This allows multiple wallets to share the same metadata cache instance for
/// optimal performance and memory usage. If not provided, a new cache
/// will be created for each wallet.
pub fn metadata_cache(mut self, metadata_cache: Arc<MintMetadataCache>) -> Self {
self.metadata_cache = Some(metadata_cache);
self
}
/// Set a HashMap of MintMetadataCaches for reusing across multiple wallets
///
/// This allows the builder to reuse existing cache instances or create new ones.
/// Useful when creating multiple wallets that share metadata caches.
pub fn metadata_caches(
mut self,
metadata_caches: HashMap<MintUrl, Arc<MintMetadataCache>>,
) -> Self {
self.metadata_caches = metadata_caches;
self
}
/// Set the rate-limiting configuration.
///
/// Rate limiting is enabled by default with [`RateLimitConfig::default`].
/// This config is only used when `build()` constructs the wallet's own
/// limiter; a limiter injected with [`Self::with_rate_limiter`] carries its
/// own config and overrides this, regardless of call order.
pub fn with_rate_limiting_config(mut self, config: RateLimitConfig) -> Self {
self.rate_limit = Some(config);
self
}
/// Use a pre-built, possibly shared [`RateLimiterManager`] for pacing.
///
/// An injected limiter takes precedence over
/// [`Self::with_rate_limiting_config`]: `build()` uses it verbatim instead of
/// constructing a per-wallet one, so several wallets can share one live set
/// of per-host budgets. [`Self::without_rate_limiting`] still clears it.
pub fn with_rate_limiter(mut self, limiter: RateLimiterManager) -> Self {
self.rate_limiter = Some(limiter);
self
}
/// Disable client-side rate limiting.
///
/// This drops the limiter entirely rather than turning it off, so the
/// runtime setters become permanent no-ops and [`Wallet::is_rate_limited`]
/// stays false. A caller who wants a reversible off switch builds with a
/// config and calls [`Wallet::disable_rate_limiting`] instead.
pub fn without_rate_limiting(mut self) -> Self {
self.rate_limit = None;
self.rate_limiter = None;
self
}
/// Set auth CAT (Clear Auth Token)
///
/// The auth wallet is constructed in [`WalletBuilder::build`] so its HTTP
/// client can share the same rate-limit budget as the main client.
///
/// # Errors
///
/// Returns an error if `mint_url` or `localstore` have not been set on the builder.
pub fn set_auth_cat(mut self, cat: String) -> Result<Self, Error> {
if self.mint_url.is_none() {
return Err(Error::Custom("Mint URL required".to_string()));
}
if self.localstore.is_none() {
return Err(Error::Custom("Localstore required".to_string()));
}
self.auth_cat = Some(cat);
self.auth_wallet = None;
Ok(self)
}
/// Build the wallet
pub fn build(mut self) -> Result<Wallet, Error> {
let mint_url = self
.mint_url
.take()
.ok_or(Error::Custom("Mint url required".to_string()))?;
let unit = self
.unit
.take()
.ok_or(Error::Custom("Unit required".to_string()))?;
let localstore = self
.localstore
.take()
.ok_or(Error::Custom("Localstore required".to_string()))?;
let seed: [u8; 64] = self
.seed
.ok_or(Error::Custom("Seed required".to_string()))?;
let metadata_cache = self.metadata_cache.take().unwrap_or_else(|| {
// Check if we already have a cache for this mint in the HashMap
if let Some(cache) = self.metadata_caches.get(&mint_url) {
cache.clone()
} else {
// Create a new one
Arc::new(MintMetadataCache::new(mint_url.clone()))
}
});
metadata_cache.set_ttl(self.metadata_cache_ttl);
// A single rate-limited transport, shared by the main client and the
// blind-auth client so both draw down one persisted budget per host and
// reuse one connection pool. An injected limiter (e.g. the one
// WalletRepository shares across all its wallets) wins over building a
// per-wallet one.
let rate_limiter = match self.rate_limiter.take() {
Some(limiter) => Some(limiter),
None => self
.rate_limit
.take()
.map(|config| RateLimiterManager::new(config, Some(localstore.clone()))),
};
let shared_transport = rate_limiter.clone().map(|limiter| {
Arc::new(RateLimitedTransport::with_manager(
Async::default(),
limiter,
))
});
// The limiter only paces traffic through a client the wallet itself
// builds around `shared_transport`: the main client (unless a custom one
// replaces it) and the blind-auth client (only on the CAT path). If a
// custom client is supplied and there is no CAT, the limiter is wired to
// nothing, so keep it off the wallet rather than exposing runtime setters
// that mutate a disconnected limiter.
let has_custom_client = self.client.is_some();
let has_auth_cat = self.auth_cat.is_some();
let limiter_is_wired = rate_limiter.is_some() && (!has_custom_client || has_auth_cat);
// The auth wallet comes either from a CAT set on the builder (built here
// so it can share the transport) or from a pre-built wallet supplied
// directly, which is used verbatim.
let auth_wallet = match self.auth_cat.take() {
Some(cat) => {
let cat = AuthToken::ClearAuth(cat);
let auth_client: Arc<dyn AuthMintConnector + Send + Sync> = match &shared_transport
{
Some(transport) => Arc::new(RateLimitedAuthHttpClient::with_shared_transport(
mint_url.clone(),
transport.clone(),
Some(cat),
)),
None => Arc::new(AuthHttpClient::new(mint_url.clone(), Some(cat))),
};
Some(AuthWallet::with_auth_client(
mint_url.clone(),
localstore.clone(),
metadata_cache.clone(),
HashMap::new(),
None,
auth_client,
))
}
None => self.auth_wallet.take(),
};
let client = match self.client.take() {
Some(client) => client,
None => match shared_transport {
Some(transport) => Arc::new(RateLimitedHttpClient::with_shared_transport(
mint_url.clone(),
transport,
auth_wallet.clone(),
)) as Arc<dyn MintConnector + Send + Sync>,
None => Arc::new(HttpClient::new(mint_url.clone(), auth_wallet.clone()))
as Arc<dyn MintConnector + Send + Sync>,
},
};
Ok(Wallet {
mint_url,
unit,
localstore,
metadata_cache,
target_proof_count: self.target_proof_count.unwrap_or(3),
auth_wallet: Arc::new(TokioRwLock::new(auth_wallet)),
auth_connector: self.auth_connector.take(),
#[cfg(feature = "npubcash")]
npubcash_client: Arc::new(TokioRwLock::new(None)),
seed,
client: client.clone(),
subscription: SubscriptionManager::new(client, self.use_http_subscription),
rate_limiter: if limiter_is_wired { rate_limiter } else { None },
})
}
}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use super::*;
#[test]
fn test_default_ttl() {
let builder = WalletBuilder::default();
assert_eq!(builder.metadata_cache_ttl, Some(Duration::from_secs(3600)));
}
#[test]
fn rate_limiting_on_by_default() {
let builder = WalletBuilder::default();
assert!(builder.rate_limit.is_some());
}
#[test]
fn without_rate_limiting_clears_it() {
let builder = WalletBuilder::default().without_rate_limiting();
assert!(builder.rate_limit.is_none());
}
#[tokio::test]
async fn set_auth_cat_defers_construction() {
let mint_url = MintUrl::from_str("https://mint.example.com").unwrap();
let store = Arc::new(cdk_sqlite::wallet::memory::empty().await.unwrap());
let builder = WalletBuilder::default()
.mint_url(mint_url)
.localstore(store)
.set_auth_cat("cat".to_string())
.unwrap();
// Construction is deferred to build(): only the raw CAT is stored.
assert_eq!(builder.auth_cat.as_deref(), Some("cat"));
assert!(builder.auth_wallet.is_none());
}
#[test]
fn set_auth_cat_requires_mint_and_store() {
let err = WalletBuilder::default().set_auth_cat("cat".to_string());
assert!(err.is_err());
}
async fn base_builder() -> WalletBuilder {
let store = Arc::new(cdk_sqlite::wallet::memory::empty().await.unwrap());
WalletBuilder::default()
.mint_url(MintUrl::from_str("https://mint.example.com").unwrap())
.unit(crate::nuts::CurrencyUnit::Sat)
.localstore(store)
.seed([0u8; 64])
}
#[tokio::test]
async fn build_with_rate_limiting_and_auth_cat() {
// Exercises the shared-bucket path: a rate-limited auth client plus a
// rate-limited main client, both built in build().
let wallet = base_builder()
.await
.set_auth_cat("cat".to_string())
.unwrap()
.build()
.unwrap();
assert!(wallet.auth_wallet.read().await.is_some());
}
#[tokio::test]
async fn build_without_rate_limiting_and_auth_cat() {
// Exercises the plain path: a plain auth client plus a plain main client.
let wallet = base_builder()
.await
.without_rate_limiting()
.set_auth_cat("cat".to_string())
.unwrap()
.build()
.unwrap();
assert!(wallet.auth_wallet.read().await.is_some());
}
#[tokio::test]
async fn default_build_keeps_the_rate_limiter() {
// No custom client: the limiter paces the main client, so it is retained
// and the runtime setters have something to act on.
let wallet = base_builder().await.build().unwrap();
assert!(wallet.rate_limiter.is_some());
assert!(wallet.is_rate_limited());
}
#[tokio::test]
async fn disabling_at_runtime_is_reversible() {
let wallet = base_builder().await.build().unwrap();
wallet.disable_rate_limiting();
assert!(!wallet.is_rate_limited());
wallet.set_rate_limiting_config(RateLimitConfig::default());
assert!(wallet.is_rate_limited());
}
#[tokio::test]
async fn without_rate_limiting_cannot_be_turned_back_on() {
// The limiter is never built, so the runtime setter has nothing to act
// on and the wallet stays unpaced forever.
let wallet = base_builder()
.await
.without_rate_limiting()
.build()
.unwrap();
assert!(!wallet.is_rate_limited());
wallet.set_rate_limiting_config(RateLimitConfig::default());
assert!(!wallet.is_rate_limited());
}
#[tokio::test]
async fn custom_client_drops_the_rate_limiter() {
// A custom client replaces the wallet's rate-limited transport and there
// is no CAT, so the limiter is wired to nothing. The wallet must not keep
// it, otherwise the runtime setters would silently mutate a disconnected
// limiter that never touches the main client's traffic.
use crate::wallet::test_utils::MockMintConnector;
let wallet = base_builder()
.await
.shared_client(Arc::new(MockMintConnector::new()))
.build()
.unwrap();
assert!(wallet.rate_limiter.is_none());
assert!(!wallet.is_rate_limited());
}
#[tokio::test]
async fn custom_client_with_auth_cat_keeps_limiter_for_auth() {
// With a custom main client but a CAT, the limiter still paces the
// blind-auth client the wallet builds, so it is retained: the setters
// then reconfigure the auth client's pacing.
use crate::wallet::test_utils::MockMintConnector;
let wallet = base_builder()
.await
.shared_client(Arc::new(MockMintConnector::new()))
.set_auth_cat("cat".to_string())
.unwrap()
.build()
.unwrap();
assert!(wallet.rate_limiter.is_some());
}
}