Compare commits
5
Commits
master
..
feat/nip60
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c5b816ebf | ||
|
|
4b9e229532 | ||
|
|
d466cac99e | ||
|
|
c5dc0ca242 | ||
|
|
73962d351f |
Generated
+985
-8
File diff suppressed because it is too large
Load Diff
+14
-1
@@ -34,7 +34,7 @@ nostr-connect = { git = "https://github.com/rust-nostr/nostr" }
|
||||
nostr-browser-signer = { git = "https://github.com/rust-nostr/nostr" }
|
||||
nostr-sdk = { git = "https://github.com/rust-nostr/nostr" }
|
||||
nostr-sqlite = { git = "https://github.com/rust-nostr/nostr" }
|
||||
nostr = { git = "https://github.com/rust-nostr/nostr", features = [ "nip59", "nip49", "nip44", "nip98" ] }
|
||||
nostr = { git = "https://github.com/rust-nostr/nostr", features = [ "nip59", "nip49", "nip44", "nip60", "nip98" ] }
|
||||
|
||||
# Crypto (NIP-17 encrypted file messages)
|
||||
aes-gcm = "0.10"
|
||||
@@ -48,6 +48,13 @@ hmac = "0.12"
|
||||
# Pinned to the instance `nostr-sdk` already builds, so NIP-44 nonces share it
|
||||
rand = { version = "0.10", default-features = false, features = [ "std", "sys_rng", "thread_rng" ] }
|
||||
|
||||
# Cashu (NIP-60). From git: the published 0.18.x line targets nostr 0.44 and
|
||||
# cannot unify with the git rust-nostr used here, while main targets 0.45.x
|
||||
# (redirected to this repo by the [patch.crates-io] section below). redb
|
||||
# storage: pure Rust, avoids the libsqlite3-sys links clash with nostr-sqlite.
|
||||
cdk = { git = "https://github.com/cashubtc/cdk", default-features = false, features = [ "wallet" ] }
|
||||
cdk-redb = { git = "https://github.com/cashubtc/cdk", default-features = false, features = [ "wallet" ] }
|
||||
|
||||
# Others
|
||||
anyhow = "1.0.44"
|
||||
tts = { git = "https://github.com/ndarilek/tts-rs" }
|
||||
@@ -66,6 +73,12 @@ webbrowser = "1.0.4"
|
||||
tracing-subscriber = { version = "0.3.18", features = ["fmt"] }
|
||||
instant = "0.1"
|
||||
|
||||
# cdk's registry nostr/nostr-sdk requirements are redirected onto the same
|
||||
# git repo coop already uses, keeping a single copy of each in the graph.
|
||||
[patch.crates-io]
|
||||
nostr = { git = "https://github.com/rust-nostr/nostr" }
|
||||
nostr-sdk = { git = "https://github.com/rust-nostr/nostr" }
|
||||
|
||||
[profile.release]
|
||||
strip = true
|
||||
opt-level = "z"
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "nip60"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
state = { path = "../state" }
|
||||
common = { path = "../common" }
|
||||
|
||||
gpui.workspace = true
|
||||
gpui_tokio.workspace = true
|
||||
nostr.workspace = true
|
||||
nostr-sdk.workspace = true
|
||||
anyhow.workspace = true
|
||||
smallvec.workspace = true
|
||||
log.workspace = true
|
||||
flume.workspace = true
|
||||
serde_json.workspace = true
|
||||
hkdf.workspace = true
|
||||
sha2.workspace = true
|
||||
tokio = { version = "1", default-features = false, features = [ "rt" ] }
|
||||
|
||||
cdk.workspace = true
|
||||
cdk-redb.workspace = true
|
||||
@@ -0,0 +1,292 @@
|
||||
use anyhow::{Error, anyhow};
|
||||
use hkdf::Hkdf;
|
||||
use nostr::nips::nip60::TokenEvent;
|
||||
use nostr_sdk::prelude::*;
|
||||
use sha2::Sha256;
|
||||
|
||||
const SEED_SALT: &[u8] = b"coop nip60 seed salt";
|
||||
const SEED_INFO: &[u8] = b"coop cashu seed";
|
||||
|
||||
pub(crate) struct WalletData {
|
||||
pub(crate) event_id: EventId,
|
||||
pub(crate) created_at: Timestamp,
|
||||
pub(crate) privkey: SecretKey,
|
||||
pub(crate) mints: Vec<Url>,
|
||||
}
|
||||
|
||||
impl Clone for WalletData {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
event_id: self.event_id,
|
||||
created_at: self.created_at,
|
||||
privkey: self.privkey.clone(),
|
||||
mints: self.mints.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn generate_privkey() -> SecretKey {
|
||||
SecretKey::generate()
|
||||
}
|
||||
|
||||
/// Derive the cdk seed from the wallet key.
|
||||
pub(crate) fn derive_seed(privkey: &SecretKey) -> Result<[u8; 64], Error> {
|
||||
let ikm = privkey.to_secret_bytes();
|
||||
let hk = Hkdf::<Sha256>::new(Some(SEED_SALT), &ikm);
|
||||
let mut seed = [0u8; 64];
|
||||
hk.expand(SEED_INFO, &mut seed)
|
||||
.map_err(|error| anyhow!("seed derivation failed: {error}"))?;
|
||||
Ok(seed)
|
||||
}
|
||||
|
||||
pub(crate) fn parse_wallet_content(content: &str) -> Result<(SecretKey, Vec<Url>), Error> {
|
||||
let rows: Vec<Vec<String>> =
|
||||
serde_json::from_str(content).map_err(|error| anyhow!("invalid wallet event: {error}"))?;
|
||||
|
||||
let mut privkey = None;
|
||||
let mut mints = Vec::new();
|
||||
for row in rows {
|
||||
let (Some(key), Some(value)) = (row.first(), row.get(1)) else {
|
||||
continue;
|
||||
};
|
||||
match key.as_str() {
|
||||
"privkey" if privkey.is_none() => privkey = Some(SecretKey::from_hex(value)?),
|
||||
"mint" => {
|
||||
if let Ok(mint) = Url::parse(value) {
|
||||
mints.push(mint);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let Some(privkey) = privkey else {
|
||||
return Err(anyhow!("wallet event is missing the private key"));
|
||||
};
|
||||
if mints.is_empty() {
|
||||
return Err(anyhow!("wallet event is missing mints"));
|
||||
}
|
||||
|
||||
Ok((privkey, mints))
|
||||
}
|
||||
|
||||
pub(crate) async fn decrypt_wallet_event<S>(
|
||||
signer: &S,
|
||||
me: &PublicKey,
|
||||
event: &Event,
|
||||
) -> Result<WalletData, Error>
|
||||
where
|
||||
S: AsyncNip44 + ?Sized,
|
||||
{
|
||||
if event.pubkey != *me {
|
||||
return Err(anyhow!("wallet event was not published by this account"));
|
||||
}
|
||||
|
||||
let content = signer.nip44_decrypt_async(me, &event.content).await?;
|
||||
let (privkey, mints) = parse_wallet_content(&content)?;
|
||||
|
||||
Ok(WalletData {
|
||||
event_id: event.id,
|
||||
created_at: event.created_at,
|
||||
privkey,
|
||||
mints,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn decrypt_token_event<S>(
|
||||
signer: &S,
|
||||
me: &PublicKey,
|
||||
event: &Event,
|
||||
) -> Result<TokenEvent, Error>
|
||||
where
|
||||
S: AsyncNip44 + ?Sized,
|
||||
{
|
||||
if event.pubkey != *me {
|
||||
return Err(anyhow!("token event was not published by this account"));
|
||||
}
|
||||
|
||||
let content = signer.nip44_decrypt_async(me, &event.content).await?;
|
||||
|
||||
let token =
|
||||
serde_json::from_str(&content).map_err(|error| anyhow!("invalid token event: {error}"))?;
|
||||
|
||||
Ok(token)
|
||||
}
|
||||
|
||||
pub(crate) async fn build_wallet_event<S>(
|
||||
signer: &S,
|
||||
me: &PublicKey,
|
||||
privkey: &SecretKey,
|
||||
mints: &[Url],
|
||||
) -> Result<Event, Error>
|
||||
where
|
||||
S: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + ?Sized,
|
||||
{
|
||||
let mut rows = vec![vec!["privkey".to_string(), privkey.to_secret_hex()]];
|
||||
for mint in mints {
|
||||
rows.push(vec!["mint".to_string(), mint.to_string()]);
|
||||
}
|
||||
|
||||
let content = signer
|
||||
.nip44_encrypt_async(me, &serde_json::to_string(&rows)?)
|
||||
.await?;
|
||||
|
||||
Ok(EventBuilder::new(Kind::CashuWallet, content)
|
||||
.finalize_async(signer)
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub(crate) async fn build_token_event<S>(
|
||||
signer: &S,
|
||||
me: &PublicKey,
|
||||
token: &TokenEvent,
|
||||
) -> Result<Event, Error>
|
||||
where
|
||||
S: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + ?Sized,
|
||||
{
|
||||
let content = signer
|
||||
.nip44_encrypt_async(me, &serde_json::to_string(token)?)
|
||||
.await?;
|
||||
|
||||
Ok(EventBuilder::new(Kind::CashuWalletUnspentProof, content)
|
||||
.finalize_async(signer)
|
||||
.await?)
|
||||
}
|
||||
|
||||
/// NIP-09 deletion carrying the `k: 7375` tag required by NIP-60.
|
||||
pub(crate) async fn build_token_deletion<S>(signer: &S, ids: &[EventId]) -> Result<Event, Error>
|
||||
where
|
||||
S: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + ?Sized,
|
||||
{
|
||||
let mut tags: Vec<Tag> = ids.iter().map(|id| Tag::event(*id)).collect();
|
||||
tags.push(Tag::custom("k", ["7375".to_string()]));
|
||||
|
||||
Ok(EventBuilder::new(Kind::EventDeletion, "")
|
||||
.tags(tags)
|
||||
.finalize_async(signer)
|
||||
.await?)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) async fn build_history_event<S>(
|
||||
signer: &S,
|
||||
me: &PublicKey,
|
||||
direction: TransactionDirection,
|
||||
amount: u64,
|
||||
created: EventId,
|
||||
destroyed: &[EventId],
|
||||
redeemed: &[EventId],
|
||||
sender: Option<PublicKey>,
|
||||
) -> Result<Event, Error>
|
||||
where
|
||||
S: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + ?Sized,
|
||||
{
|
||||
let mut rows = vec![
|
||||
vec!["direction".to_string(), direction.to_string()],
|
||||
vec!["amount".to_string(), amount.to_string()],
|
||||
];
|
||||
|
||||
for id in destroyed {
|
||||
rows.push(vec![
|
||||
"e".to_string(),
|
||||
id.to_hex(),
|
||||
String::new(),
|
||||
"destroyed".to_string(),
|
||||
]);
|
||||
}
|
||||
|
||||
rows.push(vec![
|
||||
"e".to_string(),
|
||||
created.to_hex(),
|
||||
String::new(),
|
||||
"created".to_string(),
|
||||
]);
|
||||
|
||||
let mut tags: Vec<Tag> = redeemed
|
||||
.iter()
|
||||
.map(|id| Tag::custom("e", [id.to_hex(), String::new(), "redeemed".to_string()]))
|
||||
.collect();
|
||||
|
||||
if let Some(sender) = sender {
|
||||
tags.push(Tag::custom("p", [sender.to_hex()]));
|
||||
}
|
||||
|
||||
let content = signer
|
||||
.nip44_encrypt_async(me, &serde_json::to_string(&rows)?)
|
||||
.await?;
|
||||
|
||||
Ok(EventBuilder::new(Kind::CashuWalletSpendingHistory, content)
|
||||
.tags(tags)
|
||||
.finalize_async(signer)
|
||||
.await?)
|
||||
}
|
||||
|
||||
pub(crate) async fn build_nutzap_info_event<S>(
|
||||
signer: &S,
|
||||
mints: &[Url],
|
||||
relays: &[&str],
|
||||
wallet_pubkey: PublicKey,
|
||||
) -> Result<Event, Error>
|
||||
where
|
||||
S: AsyncGetPublicKey + AsyncSignEvent + ?Sized,
|
||||
{
|
||||
let mut tags: Vec<Tag> = relays
|
||||
.iter()
|
||||
.map(|relay| Tag::custom("relay", [relay.to_string()]))
|
||||
.collect();
|
||||
|
||||
for mint in mints {
|
||||
tags.push(Tag::custom("mint", [mint.to_string(), "sat".to_string()]));
|
||||
}
|
||||
|
||||
tags.push(Tag::custom(
|
||||
"pubkey",
|
||||
[format!("02{}", wallet_pubkey.to_hex())],
|
||||
));
|
||||
|
||||
Ok(EventBuilder::new(Kind::Custom(10019), "")
|
||||
.tags(tags)
|
||||
.finalize_async(signer)
|
||||
.await?)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_wallet_content() {
|
||||
let privkey = SecretKey::generate();
|
||||
let mint = Url::parse("https://mint.example.com").expect("valid mint URL");
|
||||
|
||||
let content = serde_json::to_string(&vec![
|
||||
vec!["privkey".to_string(), privkey.to_secret_hex()],
|
||||
vec!["mint".to_string(), mint.to_string()],
|
||||
])
|
||||
.expect("serialization cannot fail");
|
||||
|
||||
let (parsed_key, mints) = parse_wallet_content(&content).expect("valid content");
|
||||
assert_eq!(parsed_key.to_secret_hex(), privkey.to_secret_hex());
|
||||
assert_eq!(mints, vec![mint]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wallet_content_rejects_missing_privkey() {
|
||||
let mint = Url::parse("https://mint.example.com").expect("valid mint URL");
|
||||
let content = serde_json::to_string(&vec![vec!["mint".to_string(), mint.to_string()]])
|
||||
.expect("serialization cannot fail");
|
||||
|
||||
assert!(parse_wallet_content(&content).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seed_is_deterministic_per_key() {
|
||||
let key = SecretKey::generate();
|
||||
let first = derive_seed(&key).expect("seed derivation cannot fail");
|
||||
let second = derive_seed(&key).expect("seed derivation cannot fail");
|
||||
assert_eq!(first, second);
|
||||
|
||||
let other = derive_seed(&SecretKey::generate()).expect("seed derivation cannot fail");
|
||||
assert_ne!(first, other);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,440 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::str::FromStr;
|
||||
|
||||
use anyhow::{Error, anyhow};
|
||||
use cdk::Amount;
|
||||
use cdk::amount::SplitTarget;
|
||||
use cdk::mint_url::MintUrl;
|
||||
use cdk::nuts::nut00::KnownMethod;
|
||||
use cdk::nuts::{
|
||||
CurrencyUnit, Id, MeltQuoteState, MintQuoteState, PaymentMethod, Proof, Proofs, SecretKey,
|
||||
State,
|
||||
};
|
||||
use cdk::secret::Secret;
|
||||
use cdk::wallet::types::ProofInfo;
|
||||
use cdk::wallet::{ReceiveOptions, SendOptions, Wallet};
|
||||
use nostr::nips::nip60::{CashuProof, TokenEvent, TransactionDirection};
|
||||
use nostr_sdk::prelude::*;
|
||||
|
||||
use crate::keys;
|
||||
|
||||
/// A job mutating the wallet store or reconciling it with relays.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) enum Job {
|
||||
Reconcile,
|
||||
ClaimQuote {
|
||||
mint: MintUrl,
|
||||
quote_id: String,
|
||||
},
|
||||
Melt {
|
||||
mint: MintUrl,
|
||||
invoice: String,
|
||||
},
|
||||
SendToken {
|
||||
mint: MintUrl,
|
||||
amount: u64,
|
||||
},
|
||||
Receive {
|
||||
mint: MintUrl,
|
||||
token: String,
|
||||
},
|
||||
RedeemNutzap {
|
||||
mint: MintUrl,
|
||||
proofs: Proofs,
|
||||
nutzap_id: EventId,
|
||||
sender: PublicKey,
|
||||
},
|
||||
}
|
||||
|
||||
/// History event payload for a token state change
|
||||
pub(crate) struct History {
|
||||
pub(crate) direction: TransactionDirection,
|
||||
pub(crate) amount: u64,
|
||||
/// NIP-61 nutzap events redeemed by this state change
|
||||
pub(crate) redeemed: Vec<EventId>,
|
||||
/// Author of the redeemed nutzap, for the unencrypted `p` tag
|
||||
pub(crate) sender: Option<PublicKey>,
|
||||
}
|
||||
|
||||
pub(crate) struct TokenUpdate {
|
||||
pub(crate) event_id: EventId,
|
||||
pub(crate) token: TokenEvent,
|
||||
pub(crate) destroyed: Vec<EventId>,
|
||||
}
|
||||
|
||||
pub(crate) enum Outcome {
|
||||
/// Nothing changed (e.g. an unpaid quote)
|
||||
Idle,
|
||||
/// Token events published by a reconcile pass
|
||||
Reconciled {
|
||||
updates: Vec<TokenUpdate>,
|
||||
},
|
||||
QuoteMinted {
|
||||
quote_id: String,
|
||||
update: TokenUpdate,
|
||||
amount: u64,
|
||||
},
|
||||
Melted {
|
||||
update: TokenUpdate,
|
||||
amount: u64,
|
||||
},
|
||||
Sent {
|
||||
update: TokenUpdate,
|
||||
token: String,
|
||||
},
|
||||
Received {
|
||||
update: TokenUpdate,
|
||||
amount: u64,
|
||||
},
|
||||
NutzapRedeemed {
|
||||
update: TokenUpdate,
|
||||
nutzap_id: EventId,
|
||||
amount: u64,
|
||||
},
|
||||
}
|
||||
|
||||
pub(crate) struct JobCtx<S> {
|
||||
pub(crate) wallets: HashMap<MintUrl, Wallet>,
|
||||
/// Wallet signing key, unlocking P2PK-locked nutzap proofs
|
||||
pub(crate) wallet_key: SecretKey,
|
||||
pub(crate) signer: S,
|
||||
pub(crate) client: Client,
|
||||
/// Relay token events at schedule time.
|
||||
pub(crate) tokens: HashMap<EventId, TokenEvent>,
|
||||
}
|
||||
|
||||
pub(crate) async fn run_job<S>(job: Job, ctx: JobCtx<S>) -> Result<Outcome, Error>
|
||||
where
|
||||
S: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + Send + Sync + 'static,
|
||||
{
|
||||
match job {
|
||||
Job::Reconcile => reconcile(ctx).await,
|
||||
Job::ClaimQuote { mint, quote_id } => {
|
||||
let wallet = wallet_for(&ctx, &mint)?;
|
||||
let quote = wallet.check_mint_quote("e_id).await?;
|
||||
|
||||
if quote.state != MintQuoteState::Paid {
|
||||
return Ok(Outcome::Idle);
|
||||
}
|
||||
|
||||
let proofs = wallet.mint("e_id, SplitTarget::default(), None).await?;
|
||||
let amount: u64 = proofs.iter().map(|proof| u64::from(proof.amount)).sum();
|
||||
|
||||
let update = sync_token_events(
|
||||
&ctx.signer,
|
||||
&ctx.client,
|
||||
wallet,
|
||||
nostr_mint(&mint)?,
|
||||
&previous_ids(&ctx.tokens, &mint),
|
||||
Some(History {
|
||||
direction: TransactionDirection::In,
|
||||
amount: u64::from(quote.amount.unwrap_or_default()),
|
||||
redeemed: Vec::new(),
|
||||
sender: None,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(Outcome::QuoteMinted {
|
||||
quote_id,
|
||||
update,
|
||||
amount,
|
||||
})
|
||||
}
|
||||
Job::Melt { mint, invoice } => {
|
||||
let wallet = wallet_for(&ctx, &mint)?;
|
||||
let quote = wallet
|
||||
.melt_quote(
|
||||
PaymentMethod::Known(KnownMethod::Bolt11),
|
||||
invoice,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let finalized = wallet
|
||||
.prepare_melt("e.id, HashMap::new())
|
||||
.await?
|
||||
.confirm()
|
||||
.await?;
|
||||
|
||||
if finalized.state() != MeltQuoteState::Paid {
|
||||
return Err(anyhow!("melt did not settle: {:?}", finalized.state()));
|
||||
}
|
||||
|
||||
let amount = u64::from(finalized.total_amount());
|
||||
let update = sync_token_events(
|
||||
&ctx.signer,
|
||||
&ctx.client,
|
||||
wallet,
|
||||
nostr_mint(&mint)?,
|
||||
&previous_ids(&ctx.tokens, &mint),
|
||||
Some(History {
|
||||
direction: TransactionDirection::Out,
|
||||
amount,
|
||||
redeemed: Vec::new(),
|
||||
sender: None,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(Outcome::Melted { update, amount })
|
||||
}
|
||||
Job::SendToken { mint, amount } => {
|
||||
let wallet = wallet_for(&ctx, &mint)?;
|
||||
let prepared = wallet
|
||||
.prepare_send(Amount::from(amount), SendOptions::default())
|
||||
.await?;
|
||||
let token = prepared.confirm(None).await?.to_string();
|
||||
|
||||
let update = sync_token_events(
|
||||
&ctx.signer,
|
||||
&ctx.client,
|
||||
wallet,
|
||||
nostr_mint(&mint)?,
|
||||
&previous_ids(&ctx.tokens, &mint),
|
||||
Some(History {
|
||||
direction: TransactionDirection::Out,
|
||||
amount,
|
||||
redeemed: Vec::new(),
|
||||
sender: None,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(Outcome::Sent { update, token })
|
||||
}
|
||||
Job::Receive { mint, token } => {
|
||||
let wallet = wallet_for(&ctx, &mint)?;
|
||||
let received = wallet.receive(&token, ReceiveOptions::default()).await?;
|
||||
|
||||
let update = sync_token_events(
|
||||
&ctx.signer,
|
||||
&ctx.client,
|
||||
wallet,
|
||||
nostr_mint(&mint)?,
|
||||
&previous_ids(&ctx.tokens, &mint),
|
||||
Some(History {
|
||||
direction: TransactionDirection::In,
|
||||
amount: u64::from(received),
|
||||
redeemed: Vec::new(),
|
||||
sender: None,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(Outcome::Received {
|
||||
update,
|
||||
amount: u64::from(received),
|
||||
})
|
||||
}
|
||||
Job::RedeemNutzap {
|
||||
mint,
|
||||
proofs,
|
||||
nutzap_id,
|
||||
sender,
|
||||
} => {
|
||||
let wallet = wallet_for(&ctx, &mint)?;
|
||||
let options = ReceiveOptions {
|
||||
p2pk_signing_keys: vec![ctx.wallet_key.clone()],
|
||||
..Default::default()
|
||||
};
|
||||
let received = wallet.receive_proofs(proofs, options, None, None).await?;
|
||||
|
||||
let update = sync_token_events(
|
||||
&ctx.signer,
|
||||
&ctx.client,
|
||||
wallet,
|
||||
nostr_mint(&mint)?,
|
||||
&previous_ids(&ctx.tokens, &mint),
|
||||
Some(History {
|
||||
direction: TransactionDirection::In,
|
||||
amount: u64::from(received),
|
||||
redeemed: vec![nutzap_id],
|
||||
sender: Some(sender),
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(Outcome::NutzapRedeemed {
|
||||
update,
|
||||
nutzap_id,
|
||||
amount: u64::from(received),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Claim paid quotes, then converge each mint.
|
||||
async fn reconcile<S>(ctx: JobCtx<S>) -> Result<Outcome, Error>
|
||||
where
|
||||
S: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + Sync,
|
||||
{
|
||||
let mut tokens = ctx.tokens.clone();
|
||||
let mut updates = Vec::new();
|
||||
|
||||
for (mint_url, wallet) in &ctx.wallets {
|
||||
let minted = wallet.mint_unissued_quotes().await?;
|
||||
if minted == Amount::ZERO {
|
||||
continue;
|
||||
}
|
||||
|
||||
let update = sync_token_events(
|
||||
&ctx.signer,
|
||||
&ctx.client,
|
||||
wallet,
|
||||
nostr_mint(mint_url)?,
|
||||
&previous_ids(&tokens, mint_url),
|
||||
Some(History {
|
||||
direction: TransactionDirection::In,
|
||||
amount: u64::from(minted),
|
||||
redeemed: Vec::new(),
|
||||
sender: None,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
apply_update(&mut tokens, &update);
|
||||
updates.push(update);
|
||||
}
|
||||
|
||||
for (mint_url, wallet) in &ctx.wallets {
|
||||
let mut relay_ys = HashSet::new();
|
||||
let mut added = Vec::new();
|
||||
|
||||
for token in tokens
|
||||
.values()
|
||||
.filter(|token| token.mint.as_str() == mint_url.to_string())
|
||||
{
|
||||
for proof in &token.proofs {
|
||||
let info = match proof_info(proof, mint_url) {
|
||||
Ok(info) => info,
|
||||
Err(error) => {
|
||||
log::warn!("skipping proof: {error:#}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if relay_ys.insert(info.y) {
|
||||
added.push(info);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let unspent = wallet.get_unspent_proofs().await?;
|
||||
let removed = unspent
|
||||
.iter()
|
||||
.filter(|proof| match proof.y() {
|
||||
Ok(y) => !relay_ys.contains(&y),
|
||||
Err(_) => false,
|
||||
})
|
||||
.map(|proof| proof.y())
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
wallet.localstore.update_proofs(added, removed).await?;
|
||||
}
|
||||
|
||||
Ok(Outcome::Reconciled { updates })
|
||||
}
|
||||
|
||||
/// Publish the store's current unspent set as a fresh token event.
|
||||
async fn sync_token_events<S>(
|
||||
signer: &S,
|
||||
client: &Client,
|
||||
wallet: &Wallet,
|
||||
mint: Url,
|
||||
previous: &[EventId],
|
||||
history: Option<History>,
|
||||
) -> Result<TokenUpdate, Error>
|
||||
where
|
||||
S: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + Sync + ?Sized,
|
||||
{
|
||||
let me = signer.get_public_key_async().await?;
|
||||
let unspent = wallet.get_unspent_proofs().await?;
|
||||
|
||||
let mut proofs = Vec::new();
|
||||
for proof in &unspent {
|
||||
proofs.push(cashu_proof(proof)?);
|
||||
}
|
||||
|
||||
let token = TokenEvent::new(mint, proofs);
|
||||
let event = keys::build_token_event(signer, &me, &token).await?;
|
||||
client.send_event(&event).await?;
|
||||
|
||||
if !previous.is_empty() {
|
||||
let deletion = keys::build_token_deletion(signer, previous).await?;
|
||||
client.send_event(&deletion).await?;
|
||||
}
|
||||
|
||||
if let Some(history) = history {
|
||||
let history_event = keys::build_history_event(
|
||||
signer,
|
||||
&me,
|
||||
history.direction,
|
||||
history.amount,
|
||||
event.id,
|
||||
previous,
|
||||
&history.redeemed,
|
||||
history.sender,
|
||||
)
|
||||
.await?;
|
||||
client.send_event(&history_event).await?;
|
||||
}
|
||||
|
||||
Ok(TokenUpdate {
|
||||
event_id: event.id,
|
||||
token,
|
||||
destroyed: previous.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
fn apply_update(tokens: &mut HashMap<EventId, TokenEvent>, update: &TokenUpdate) {
|
||||
for id in &update.destroyed {
|
||||
tokens.remove(id);
|
||||
}
|
||||
tokens.insert(update.event_id, update.token.clone());
|
||||
}
|
||||
|
||||
fn previous_ids(tokens: &HashMap<EventId, TokenEvent>, mint: &MintUrl) -> Vec<EventId> {
|
||||
tokens
|
||||
.iter()
|
||||
.filter(|(_, token)| token.mint.as_str() == mint.to_string())
|
||||
.map(|(id, _)| *id)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn wallet_for<'a, S>(ctx: &'a JobCtx<S>, mint: &MintUrl) -> Result<&'a Wallet, Error> {
|
||||
ctx.wallets
|
||||
.get(mint)
|
||||
.ok_or_else(|| anyhow!("no open wallet for mint {mint}"))
|
||||
}
|
||||
|
||||
fn nostr_mint(mint: &MintUrl) -> Result<Url, Error> {
|
||||
Url::parse(&mint.to_string()).map_err(|error| anyhow!("invalid mint url: {error}"))
|
||||
}
|
||||
|
||||
fn cashu_proof(proof: &Proof) -> Result<CashuProof, Error> {
|
||||
Ok(CashuProof {
|
||||
id: proof.keyset_id.to_string(),
|
||||
amount: u64::from(proof.amount),
|
||||
secret: proof.secret.to_string(),
|
||||
c: proof.c.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn proof_info(proof: &CashuProof, mint: &MintUrl) -> Result<ProofInfo, Error> {
|
||||
let keyset_id = Id::from_str(&proof.id)?;
|
||||
let c = cdk::nuts::PublicKey::from_str(&proof.c)?;
|
||||
let info = ProofInfo::new(
|
||||
Proof::new(
|
||||
Amount::from(proof.amount),
|
||||
keyset_id,
|
||||
Secret::new(proof.secret.clone()),
|
||||
c,
|
||||
),
|
||||
mint.clone(),
|
||||
State::Unspent,
|
||||
CurrencyUnit::Sat,
|
||||
)?;
|
||||
|
||||
Ok(info)
|
||||
}
|
||||
@@ -37,6 +37,7 @@ workspace = { path = "../crates/workspace" }
|
||||
ui = { path = "../crates/ui" }
|
||||
state = { path = "../crates/state" }
|
||||
nip4e = { path = "../crates/nip4e" }
|
||||
nip60 = { path = "../crates/nip60" }
|
||||
chat = { path = "../crates/chat" }
|
||||
chat_ui = { path = "../crates/chat_ui" }
|
||||
nip29 = { path = "../crates/nip29" }
|
||||
|
||||
@@ -91,6 +91,11 @@ fn main() {
|
||||
// NIP-4e: https://github.com/nostr-protocol/nips/blob/per-device-keys/4e.md
|
||||
nip4e::init(cx);
|
||||
|
||||
// Initialize cashu wallet registry
|
||||
//
|
||||
// NIP-60: https://github.com/nostr-protocol/nips/blob/master/60.md
|
||||
nip60::init(cx);
|
||||
|
||||
// Initialize app registry
|
||||
chat::init(cx);
|
||||
|
||||
|
||||
+318
@@ -0,0 +1,318 @@
|
||||
# NIP-60: cashu wallet — implementation plan
|
||||
|
||||
Spec: https://github.com/nostr-protocol/nips/blob/master/60.md
|
||||
CDK: https://github.com/cashubtc/cdk (crates `cdk`, `cdk-redb`, from git main)
|
||||
NIP-61: https://github.com/nostr-protocol/nips/blob/master/61.md
|
||||
|
||||
NIP-60 stores a user's cashu wallet state on relays: the wallet config
|
||||
(kind `17375`), its unspent proofs (kind `7375`), and an optional spending
|
||||
history (kind `7376`). All content is NIP-44 encrypted to self. This plan
|
||||
implements it inside coop using the CDK for all cashu/mint operations and
|
||||
the app's existing nostr client/signer for events.
|
||||
|
||||
## Analysis
|
||||
|
||||
| Kind | Replaceable | Content (NIP-44 to self) | Purpose |
|
||||
| ------ | ----------- | ----------------------------------------------- | -------------------------------- |
|
||||
| 17375 | yes `[[privkey, hex], [mint, url], ...]` | wallet config: P2PK key + mints |
|
||||
| 7375 | no `{mint, unit, proofs[], del[]}` | unspent proofs (per mint) |
|
||||
| 7376 | no `[[direction], [amount], [unit], [e, ...]]` | spend/receive history (optional) |
|
||||
| 7374 | no `quote-id` + `mint`/`expiration` tags | pending mint quote (optional) |
|
||||
| 10019 | yes empty, `relay` tags | wallet relay list |
|
||||
|
||||
Key mechanics:
|
||||
|
||||
- Wallet state transitions are rollover: spending part of a token event
|
||||
publishes a new `7375` with the unspent proofs + `del: [old-event-id]`,
|
||||
then NIP-09 deletes the old event (the delete MUST carry `["k", "7375"]`).
|
||||
- The `privkey` in `17375` is a wallet-only key (never the nostr identity
|
||||
key). It exists to unlock P2PK-locked ecash, i.e. redeeming NIP-61
|
||||
nutzaps.
|
||||
- NIP-60 itself does not move money to/from others. Receiving ecash from
|
||||
peers is NIP-61 (nutzaps): public `kind:9321` events published by the
|
||||
sender, p-tagging the recipient's nostr identity pubkey, carrying
|
||||
P2PK-locked proofs (`proof` tags) on a trusted mint (`u` tag). Redemption
|
||||
is `receive_proofs` with the wallet signing key + a `7376` whose
|
||||
unencrypted tags mark the nutzap `redeemed` and carry the sender pubkey.
|
||||
- NIP-61 discovery runs through a `kind:10019` informational event
|
||||
(relays, mints, wallet pubkey) published alongside the wallet event.
|
||||
- History (7376) and quote events (7374) are optional; the spec recommends
|
||||
local state for quotes. We publish 7376, skip 7374 (cdk keeps quotes in
|
||||
its local DB).
|
||||
|
||||
## How it fits coop
|
||||
|
||||
Follows the existing crate patterns exactly; no new architecture.
|
||||
|
||||
- One protocol crate: `crates/nip60`, mirroring `nip4e`/`nip29` — a
|
||||
registry entity set as GPUI global by `init(cx)`, `EventEmitter` for
|
||||
UI updates, `SmallVec<Task>` + `SmallVec<Subscription>` fields, flume
|
||||
signal channel for background results, reset/reload on
|
||||
`NostrRegistry::signer_changed` (see `crates/nip29/src/lib.rs`).
|
||||
- Desktop-only: crate-level `#![cfg(not(target_arch = "wasm32"))]` like
|
||||
`crates/auto_update/src/lib.rs`. Wallet UI is only wired on desktop.
|
||||
- Tokio bridge: all cdk calls run through `gpui_tokio::Tokio::spawn(cx, ...)`
|
||||
(runtime is already initialized by `state::init`). The `cdk-nostr`
|
||||
inbox listener also runs on that runtime.
|
||||
- Signer-agnostic encryption: the signer may be a bunker/extension, so we
|
||||
never use `nostr::nips::nip60` prepare helpers (they need an owned
|
||||
`SecretKey`).
|
||||
We build payloads as plain JSON, encrypt with
|
||||
`signer.nip44_encrypt(self_pubkey, json)` and sign with
|
||||
`EventBuilder::new(kind, content).finalize_async(signer)` — the same
|
||||
pattern as `crates/nip4e/src/storage.rs`. Parsing is decrypt-then-parse:
|
||||
`TokenEvent` derives `Deserialize`; `17375` content is a trivial
|
||||
`Vec<Vec<String>>` parse.
|
||||
- Existing facts we build on:
|
||||
- rust-nostr (git, already a dependency) ships `nostr::nip60` with the
|
||||
event data types (`WalletEvent`, `TokenEvent`, `SpendingHistory`,
|
||||
`QuoteEvent`, `CashuProof`) and kinds
|
||||
(`Kind::CashuWallet` = 17375, `CashuWalletUnspentProof` = 7375,
|
||||
`CashuWalletSpendingHistory` = 7376, `CashuWalletQuote` = 7374).
|
||||
It is behind the `nip60` feature, which coop does not enable yet.
|
||||
- `state::NostrRegistry` gives the `Client` (LMDB cache + bootstrap
|
||||
relays + gossip) and the `UniversalSigner`.
|
||||
- Local file storage precedent: `NostrLmdb::open(config_dir().join("nostr"))`
|
||||
in `crates/state/src/lib.rs`; cdk's sqlite store goes to
|
||||
`config_dir().join("cashu")`.
|
||||
|
||||
## Dependencies
|
||||
|
||||
Workspace `Cargo.toml` (final state after the phase 0 spike):
|
||||
|
||||
```toml
|
||||
nostr = { git = "https://github.com/rust-nostr/nostr", features = [ "nip59", "nip49", "nip44", "nip60", "nip98" ] }
|
||||
|
||||
# Cashu (NIP-60). From git: the published 0.18.x line targets nostr 0.44 and
|
||||
# cannot unify with the git rust-nostr used here, while main targets 0.45.x
|
||||
cdk = { git = "https://github.com/cashubtc/cdk", default-features = false, features = [ "wallet" ] }
|
||||
cdk-redb = { git = "https://github.com/cashubtc/cdk", default-features = false, features = [ "wallet" ] }
|
||||
cdk-nostr = { git = "https://github.com/cashubtc/cdk", default-features = false }
|
||||
|
||||
[patch.crates-io]
|
||||
nostr = { git = "https://github.com/rust-nostr/nostr" }
|
||||
nostr-sdk = { git = "https://github.com/rust-nostr/nostr" }
|
||||
```
|
||||
|
||||
Spike findings (all resolved and verified with `cargo check`):
|
||||
|
||||
- The cdk family hard-pins `cdk-common` with `=` per release, so all crates
|
||||
must come from one release train. crates.io 0.18.3 pins nostr 0.44 and
|
||||
cannot coexist with coop's git nostr 0.45.x; the git main line pins
|
||||
nostr ^0.45.3, which the `[patch.crates-io]` block redirects onto the
|
||||
same git rust-nostr checkout. The lockfile ends with exactly one `nostr`
|
||||
and one `nostr-sdk`, proven by compile-time type-identity checks between
|
||||
`nostr` and `cdk_nostr::nostr`.
|
||||
- Storage is `cdk-redb` (`WalletRedbDatabase::new(&Path)`, pure Rust), not
|
||||
`cdk-sqlite`: published cdk-sqlite pins rusqlite ^0.31, whose
|
||||
`libsqlite3-sys` clashes at the `links` level with the `nostr-sqlite`
|
||||
wasm dependency of the `state` crate.
|
||||
- rust-nostr 0.45.x has no root re-exports: the module is
|
||||
`nostr::nips::nip60`, and cdk-nostr re-exports the SDK as
|
||||
`cdk_nostr::nostr` / `cdk_nostr::nostr_sdk`.
|
||||
- The `nip60` crate exists (`crates/nip60`) with a compile-only spike in
|
||||
`lib.rs` and a no-op `init(cx)` wired into `desktop/src/main.rs`; both
|
||||
are replaced in phase 1.
|
||||
|
||||
## Design
|
||||
|
||||
### Key material
|
||||
|
||||
- On first `setup(mint_url)` (explicit user action, no auto-creation):
|
||||
generate `SecretKey::generate()` as the wallet key, publish `17375`
|
||||
containing it + the mint list (encrypted to self, signed by the user).
|
||||
- The cdk seed is derived deterministically from the wallet key
|
||||
(`HKDF-SHA256(wallet_privkey, info = "coop cashu seed")` -> `[u8; 64]`).
|
||||
No extra local storage, and a fresh device recovers the full wallet from
|
||||
the relay state alone. Tradeoff: the derivation is coop-specific (NIP-60
|
||||
does not standardize seed derivation), so it does not restore into other
|
||||
apps — acceptable, see open questions.
|
||||
- Proof-level secrets/counters live in cdk's sqlite store; NUT-13 restore
|
||||
from mints works because the seed is deterministic.
|
||||
|
||||
### Local state
|
||||
|
||||
- cdk redb store at `config_dir().join("cashu")` (one `WalletDatabase`
|
||||
shared by all mint wallets).
|
||||
- `WalletRegistry` holds: parsed `17375` (`WalletEvent` + event id), the
|
||||
active `7375` events per mint (event id + `TokenEvent`), cdk `Wallet`
|
||||
per mint (`CurrencyUnit::Sat` only in v1), and the subscription handle.
|
||||
|
||||
### Relay sync
|
||||
|
||||
- One subscription: `authors: [me], kinds: [17375, 7375, 7376]` plus
|
||||
kind `5` with `k: 7375`, on the existing client (bootstrap relays).
|
||||
Notifications flow through the nip29-style flume channel.
|
||||
- Published relays: the same client/relays coop already uses. Publishing a
|
||||
`10019` wallet relay list with those relays is a one-liner for interop;
|
||||
reading `10019` from other clients is skipped in v1 (coop always uses
|
||||
its own relay set).
|
||||
|
||||
### Operations
|
||||
|
||||
Each op runs on tokio and ends with the same `sync` tail:
|
||||
read unspent proofs from cdk -> publish one `7375` per changed mint
|
||||
(rolling up previous event ids into `del`) -> NIP-09 delete old events with
|
||||
a `k:7375` tag -> publish `7376` history -> update registry state and emit.
|
||||
|
||||
- `setup(mint_url)`: create wallet key + seed, publish `17375`, build cdk
|
||||
`Wallet`, open subscription.
|
||||
- `create_mint_quote(amount)`: `wallet.mint_quote` -> return invoice to UI;
|
||||
poll / subscribe quote state, then `wallet.mint(quote_id)` -> sync.
|
||||
On load, `mint_unissued_quotes` claims quotes paid elsewhere.
|
||||
- `melt(invoice)`: `wallet.melt` -> sync (change proofs roll over).
|
||||
- `send_token(amount)`: `wallet.send` -> return token string for the user
|
||||
to share -> sync. (No in-chat token delivery in v1.)
|
||||
- `receive_token(token)`: `wallet.receive` -> sync.
|
||||
- Redeem nutzap (NIP-61): verify the gift-wrapped proofs are P2PK-locked to
|
||||
the wallet pubkey, then `wallet.receive_proofs(proofs, ReceiveOptions {
|
||||
p2pk_signing_keys: [wallet_key] })` -> `7376` with unencrypted
|
||||
`e <nutzap-id> "" redeemed` tag -> sync.
|
||||
- Remote `7375` from another device: import its unspent proofs into the
|
||||
cdk store as the new local truth (cdk proof insertion + state check via
|
||||
`check_proofs_spent`); superseded `7375`s reconcile through `del`/NIP-09.
|
||||
- On every load: `recover_incomplete_sagas` and `mint_unissued_quotes`
|
||||
(required by cdk to clear interrupted operations), then re-derive the
|
||||
unspent set from `7375` minus deletes.
|
||||
|
||||
### Crate layout (3 files, kept small on purpose)
|
||||
|
||||
- `lib.rs` — `init`, `WalletRegistry`, `WalletEvent` (`Updated`, `Error`),
|
||||
subscription/notification handling, `reset` on signer change.
|
||||
- `keys.rs` — wallet key/seed derivation, `17375` build/parse via signer.
|
||||
- `ops.rs` — cdk operations + the shared `sync` tail (rollover, deletes,
|
||||
history), NIP-61 redemption.
|
||||
|
||||
Wiring: `nip60::init(cx)` in `desktop/src/main.rs` after `nip4e::init(cx)`;
|
||||
`nip60 = { path = "../crates/nip60" }` added to `desktop/Cargo.toml` (and
|
||||
the UI crate when Phase 3 lands).
|
||||
|
||||
## Phases
|
||||
|
||||
### Phase 0 — dependency spike (done)
|
||||
|
||||
Outcome recorded in the Dependencies section: cdk family on git main,
|
||||
`[patch.crates-io]` unification, cdk-redb storage, `nip60` crate skeleton
|
||||
wired into desktop. `cargo check -p nip60` and the full desktop check pass.
|
||||
|
||||
The remaining spike code in `crates/nip60/src/lib.rs` is deleted in
|
||||
phase 1.
|
||||
|
||||
### Phase 1 — bootstrap + load + balance (done)
|
||||
|
||||
Implemented in `crates/nip60` (`lib.rs`, `keys.rs`):
|
||||
|
||||
- `WalletRegistry` follows the nip29/nip4e pattern: global entity, signer
|
||||
reset, flume notification listener, task + subscription SmallVecs.
|
||||
- `keys.rs`: wallet key generation, HKDF seed derivation, `17375`
|
||||
encrypt/parse through the signer (works with bunkers), unit tests.
|
||||
- Load: subscribe + query cache for 17375/7375/7376 and kind 5 `k:7375`,
|
||||
decrypt via signer, prune deleted (`k:7375` deletes) and superseded
|
||||
(`del` chains) token events, expose `has_wallet()`/`balance()`.
|
||||
- cdk: redb store per wallet pubkey under `config_dir()/cashu`, one `Wallet`
|
||||
per mint (`sat`), unspent proofs imported/diffed against the store on
|
||||
every sync, `recover_incomplete_sagas` + `mint_unissued_quotes` fire on
|
||||
first store open.
|
||||
- `setup(mint)` creates the wallet (first mint) or adds a mint, publishing
|
||||
`17375` and saving it to the local cache.
|
||||
|
||||
Deferred to later phases: token rollover publishing (phase 2), remote
|
||||
proof validation at the mint (phase 2 reconciliation), replacing proofs
|
||||
reserved by local in-flight operations (phase 2 guard).
|
||||
|
||||
### Phase 2 — moving money (done)
|
||||
|
||||
Implemented in `crates/nip60/src/ops.rs` plus registry wiring:
|
||||
|
||||
- All store mutations go through a serialized job queue
|
||||
(`schedule_job`): one job at a time on the background executor,
|
||||
snapshots taken at schedule time, one queued job slot. This keeps ops
|
||||
and relay-driven imports from interleaving on the store, which a loose
|
||||
sync tail would not guarantee.
|
||||
- Jobs: `Reconcile` (claim paid quotes via `mint_unissued_quotes`, then
|
||||
converge each mint — publish the store's unspent set when it diverges
|
||||
from the relay view, and import relay-only proofs into the store),
|
||||
`ClaimQuote`, `Melt`, `SendToken`, `Receive`.
|
||||
- The sync tail (`sync_token_events`) publishes a fresh `7375` with the
|
||||
store's unspent proofs, NIP-09-deletes the previous token events with
|
||||
the required `k: 7375` tag, and publishes a `7376` history event with
|
||||
`created`/`destroyed` markers.
|
||||
- Registry API: `create_mint_quote(amount)` (invoice stored in
|
||||
`mint_quotes()`, UI polls `claim_mint_quote(id)`), `melt(invoice)`,
|
||||
`send_token(amount)` (token delivered via `WalletEvent::TokenCreated`),
|
||||
`receive_token(token)` (mint resolved from the token).
|
||||
- Claim-on-load moved from a fire-and-forget task into `Reconcile`:
|
||||
the fire-and-forget variant raced the import pass, which could wipe
|
||||
freshly claimed proofs from the store before they were published.
|
||||
- History amounts: mint/receive record what was received; melt records
|
||||
invoice amount + fee (`FinalizedMelt::total_amount`); send records the
|
||||
sent amount.
|
||||
|
||||
Deferred: NUT-20/quote events (`7374`, per spec local state is fine),
|
||||
sending tokens in-chat (v1 copies the token string).
|
||||
|
||||
### Phase 3 — NIP-61 redemption (done)
|
||||
|
||||
Spec note: NIP-61 changed since this plan was first written — nutzaps are
|
||||
now public `kind:9321` events p-tagging the recipient's nostr identity
|
||||
pubkey (the old draft's `kind:938` + gift-wrap shape is gone). So
|
||||
`cdk_nostr::NostrInbox` (a NIP-17 gift-wrap listener) is not the right
|
||||
tool; the dependency was dropped and reception rides the app's existing
|
||||
nostr client.
|
||||
|
||||
Implemented:
|
||||
|
||||
- `setup` also publishes a `kind:10019` nutzap info event (bootstrap
|
||||
relays, wallet mints, wallet pubkey) so other clients can nutzap us.
|
||||
- A second subscription (`kinds: [9321], #p: me`) feeds nutzaps through
|
||||
the same notification listener; the cache load scans stored `9321`s
|
||||
too, so unredeemed nutzaps survive restarts.
|
||||
- `absorb_nutzap` parses `proof`/`u` tags, resolves the mint against the
|
||||
open wallets, verifies every proof is P2PK-locked to the wallet pubkey
|
||||
(NUT-10 spending conditions), and enqueues `Job::RedeemNutzap` through
|
||||
the serialized job queue.
|
||||
- The job redeems via `wallet.receive_proofs` with the wallet key in
|
||||
`p2pk_signing_keys`, then syncs with a `7376` history event whose
|
||||
unencrypted tags mark the nutzap `redeemed` and tag the sender.
|
||||
- Already-redeemed nutzaps (from cached `7376` tags) and ones with a job
|
||||
in flight are skipped; failed redemptions are retried on relay echo.
|
||||
|
||||
### Phase 4 — UI
|
||||
|
||||
- Settings entry for the mint URL (`settings` crate pattern).
|
||||
- Minimal wallet surface in the workspace (balance, receive invoice,
|
||||
paste-token receive, send-token, history list) subscribing to
|
||||
`WalletEvent`. Follows `nip29_ui`'s split if it grows beyond a panel.
|
||||
|
||||
## Tests
|
||||
|
||||
- `keys.rs` round-trips: encrypt/decrypt `17375` payloads against the
|
||||
rust-nostr reference types (mirrors `nostr::nip60` unit tests).
|
||||
- Rollover logic: given prior token events + a new unspent set, assert the
|
||||
produced `7375`/delete/`7376` trio (pure functions, no network).
|
||||
- Integration (optional, behind `#[ignore]`): testnut mint mint -> melt
|
||||
cycle against cdk's memory store.
|
||||
|
||||
## Open questions / tradeoffs
|
||||
|
||||
- Seed derivation is coop-specific; cross-app portability of proof
|
||||
restores is unsolved by NIP-60 generally. Revisit if a derivation
|
||||
convention lands in the NIP or cdk.
|
||||
- v1 is single-unit (`sat`) and effectively single-mint in the UI, even
|
||||
though the event format and registry support many mints.
|
||||
- Concurrent spends from two devices double-spend; recovery is the spec's
|
||||
Appendix-1 validation (check proofs at the mint, roll over survivors) —
|
||||
implemented as reconciliation on sync, not real-time locking.
|
||||
- Import replaces the unspent proof set wholesale; the serialized job
|
||||
queue closes the in-flight-operation window, and mint-side double-spend
|
||||
rejection remains the backstop.
|
||||
- Tracking cdk via git main is a moving target; the lockfile pins a rev
|
||||
and must be bumped deliberately (same policy as the rust-nostr git dep).
|
||||
Watch for the next cdk release line built against nostr 0.45.x — moving
|
||||
back to crates.io then removes the moving-target concern.
|
||||
- Web target gets no wallet in v1: cdk store backends (redb, sqlite) need
|
||||
a real filesystem and do not build on wasm32; the crate compiles to
|
||||
nothing there (auto_update pattern). A wasm store would need a cdk
|
||||
`WalletDatabase` over IndexedDB — explicitly out of scope.
|
||||
- `7374` quote events are skipped (local cdk state per the spec); pending
|
||||
quotes are not visible to other devices until claimed.
|
||||
Reference in New Issue
Block a user