Compare commits
7
Commits
master
..
feat/nip60
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53aa54a034 | ||
|
|
2d85c563fa | ||
|
|
8c5b816ebf | ||
|
|
4b9e229532 | ||
|
|
d466cac99e | ||
|
|
c5dc0ca242 | ||
|
|
73962d351f |
Generated
+1002
-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"
|
||||
|
||||
@@ -23,3 +23,6 @@ smallvec.workspace = true
|
||||
serde.workspace = true
|
||||
|
||||
regex = "1"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
nip60_ui = { path = "../nip60_ui" }
|
||||
|
||||
@@ -681,6 +681,41 @@ impl ChatPanel {
|
||||
});
|
||||
}
|
||||
|
||||
/// Open the nutzap dialog for the room's peer; direct chats only
|
||||
fn open_nutzap(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = (window, cx);
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let Some(room) = self.room.upgrade() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let nostr = NostrRegistry::global(cx);
|
||||
let Some(me) = nostr.read(cx).current_user() else {
|
||||
return;
|
||||
};
|
||||
|
||||
let peers: Vec<PublicKey> = room
|
||||
.read(cx)
|
||||
.members()
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|key| *key != me)
|
||||
.collect();
|
||||
|
||||
if let [recipient] = peers[..] {
|
||||
nip60_ui::open_nutzap(window, cx, recipient, None);
|
||||
} else {
|
||||
window.push_notification(
|
||||
Notification::warning("Nutzaps can only be sent in direct chats"),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn upload(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
// Get the user's configured blossom server
|
||||
let server = AppSettings::get_file_server(cx);
|
||||
@@ -2012,6 +2047,18 @@ impl Render for ChatPanel {
|
||||
this.upload(window, cx);
|
||||
})),
|
||||
)
|
||||
.when(cfg!(not(target_arch = "wasm32")), |this| {
|
||||
this.child(
|
||||
Button::new("nutzap")
|
||||
.icon(gpui_kit::assets::IconName::Coins)
|
||||
.tooltip("Send eCash")
|
||||
.disabled(dictating)
|
||||
.ghost()
|
||||
.on_click(cx.listener(move |this, _ev, window, cx| {
|
||||
this.open_nutzap(window, cx);
|
||||
})),
|
||||
)
|
||||
})
|
||||
.when(dictating, |this| {
|
||||
this.child(
|
||||
h_flex()
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
[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
|
||||
futures.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,369 @@
|
||||
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";
|
||||
|
||||
/// Parsed 17375 wallet event: the wallet key and its mint list.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct WalletData {
|
||||
pub(crate) event_id: EventId,
|
||||
pub(crate) created_at: Timestamp,
|
||||
pub(crate) privkey: SecretKey,
|
||||
pub(crate) mints: Vec<Url>,
|
||||
}
|
||||
|
||||
impl WalletData {
|
||||
/// A new wallet with a fresh key.
|
||||
pub(crate) fn generate(first_mint: Url) -> Self {
|
||||
Self {
|
||||
event_id: EventId::from_byte_array([0; 32]),
|
||||
created_at: Timestamp::from_secs(0),
|
||||
privkey: SecretKey::generate(),
|
||||
mints: vec![first_mint],
|
||||
}
|
||||
}
|
||||
|
||||
/// The cdk seed, derived deterministically 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)
|
||||
}
|
||||
|
||||
/// Decrypt and parse a 17375 event published by this account.
|
||||
pub(crate) async fn decrypt<S>(signer: &S, me: &PublicKey, event: &Event) -> Result<Self, 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(Self {
|
||||
event_id: event.id,
|
||||
created_at: event.created_at,
|
||||
privkey,
|
||||
mints,
|
||||
})
|
||||
}
|
||||
|
||||
/// Build the encrypted 17375 event for this wallet data.
|
||||
pub(crate) async fn to_event<S>(&self, signer: &S, me: &PublicKey) -> Result<Event, Error>
|
||||
where
|
||||
S: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + ?Sized,
|
||||
{
|
||||
let mut rows = vec![vec!["privkey".to_string(), self.privkey.to_secret_hex()]];
|
||||
for mint in &self.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?)
|
||||
}
|
||||
}
|
||||
|
||||
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_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_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?)
|
||||
}
|
||||
|
||||
/// Decrypted 7376 payload, enough for the wallet panel's history list.
|
||||
pub(crate) struct HistoryPayload {
|
||||
pub(crate) direction: TransactionDirection,
|
||||
pub(crate) amount: u64,
|
||||
}
|
||||
|
||||
pub(crate) async fn decrypt_history_event<S>(
|
||||
signer: &S,
|
||||
me: &PublicKey,
|
||||
event: &Event,
|
||||
) -> Result<HistoryPayload, Error>
|
||||
where
|
||||
S: AsyncNip44 + ?Sized,
|
||||
{
|
||||
if event.pubkey != *me {
|
||||
return Err(anyhow!("history event was not published by this account"));
|
||||
}
|
||||
|
||||
let content = signer.nip44_decrypt_async(me, &event.content).await?;
|
||||
let rows: Vec<Vec<String>> = serde_json::from_str(&content)
|
||||
.map_err(|error| anyhow!("invalid history event: {error}"))?;
|
||||
|
||||
let mut direction = None;
|
||||
let mut amount = None;
|
||||
for row in rows {
|
||||
let (Some(key), Some(value)) = (row.first(), row.get(1)) else {
|
||||
continue;
|
||||
};
|
||||
match key.as_str() {
|
||||
"direction" if direction.is_none() => direction = value.parse().ok(),
|
||||
"amount" if amount.is_none() => amount = value.parse().ok(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let Some(direction) = direction else {
|
||||
return Err(anyhow!("history event is missing the direction"));
|
||||
};
|
||||
let Some(amount) = amount else {
|
||||
return Err(anyhow!("history event is missing the amount"));
|
||||
};
|
||||
|
||||
Ok(HistoryPayload { direction, amount })
|
||||
}
|
||||
|
||||
/// Build the public kind 9321 nutzap event carrying P2PK-locked proofs.
|
||||
pub(crate) async fn build_nutzap_event<S>(
|
||||
signer: &S,
|
||||
recipient: PublicKey,
|
||||
mint: &str,
|
||||
proofs: &[String],
|
||||
target: Option<EventId>,
|
||||
comment: &str,
|
||||
) -> Result<Event, Error>
|
||||
where
|
||||
S: AsyncGetPublicKey + AsyncSignEvent + ?Sized,
|
||||
{
|
||||
let mut tags: Vec<Tag> = vec![
|
||||
Tag::custom("p", [recipient.to_hex()]),
|
||||
Tag::custom("u", [mint.to_string()]),
|
||||
Tag::custom("unit", ["sat".to_string()]),
|
||||
];
|
||||
|
||||
for proof in proofs {
|
||||
tags.push(Tag::custom("proof", [proof.clone()]));
|
||||
}
|
||||
|
||||
if let Some(target) = target {
|
||||
tags.push(Tag::custom("e", [target.to_hex()]));
|
||||
}
|
||||
|
||||
Ok(EventBuilder::new(Kind::Custom(9321), comment)
|
||||
.tags(tags)
|
||||
.finalize_async(signer)
|
||||
.await?)
|
||||
}
|
||||
|
||||
/// Encrypted 7376 history payload for one 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) async fn build_history_event<S>(
|
||||
signer: &S,
|
||||
me: &PublicKey,
|
||||
history: &History,
|
||||
created: EventId,
|
||||
destroyed: &[EventId],
|
||||
) -> Result<Event, Error>
|
||||
where
|
||||
S: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + ?Sized,
|
||||
{
|
||||
let mut rows = vec![
|
||||
vec!["direction".to_string(), history.direction.to_string()],
|
||||
vec!["amount".to_string(), history.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> = history
|
||||
.redeemed
|
||||
.iter()
|
||||
.map(|id| Tag::custom("e", [id.to_hex(), String::new(), "redeemed".to_string()]))
|
||||
.collect();
|
||||
|
||||
if let Some(sender) = history.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: &[RelayUrl],
|
||||
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 = WalletData::derive_seed(&key).expect("seed derivation cannot fail");
|
||||
let second = WalletData::derive_seed(&key).expect("seed derivation cannot fail");
|
||||
assert_eq!(first, second);
|
||||
|
||||
let other =
|
||||
WalletData::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,617 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::str::FromStr;
|
||||
use std::time::Duration;
|
||||
|
||||
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, KeySetInfo, MeltQuoteState, MintQuoteState, PaymentMethod, Proof, Proofs,
|
||||
SecretKey, SpendingConditions, State,
|
||||
};
|
||||
use cdk::secret::Secret;
|
||||
use cdk::wallet::types::ProofInfo;
|
||||
use cdk::wallet::{ReceiveOptions, SendOptions, Wallet};
|
||||
use futures::StreamExt;
|
||||
use nostr::nips::nip60::{CashuProof, TokenEvent, TransactionDirection};
|
||||
use nostr_sdk::prelude::*;
|
||||
|
||||
use crate::keys;
|
||||
|
||||
/// How long to wait for relays when fetching a recipient's wallet info
|
||||
const FETCH_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// A job mutating the wallet store or reconciling it with relays.
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) enum Job {
|
||||
Reconcile,
|
||||
CreateQuote {
|
||||
mint: MintUrl,
|
||||
amount: u64,
|
||||
},
|
||||
ClaimQuote {
|
||||
mint: MintUrl,
|
||||
quote_id: String,
|
||||
},
|
||||
Melt {
|
||||
mint: MintUrl,
|
||||
invoice: String,
|
||||
},
|
||||
SendToken {
|
||||
mint: MintUrl,
|
||||
amount: u64,
|
||||
},
|
||||
SendNutzap {
|
||||
recipient: PublicKey,
|
||||
amount: u64,
|
||||
target: Option<EventId>,
|
||||
comment: Option<String>,
|
||||
},
|
||||
Receive {
|
||||
mint: MintUrl,
|
||||
token: String,
|
||||
},
|
||||
RedeemNutzap {
|
||||
mint: MintUrl,
|
||||
proofs: Proofs,
|
||||
nutzap_id: EventId,
|
||||
sender: PublicKey,
|
||||
},
|
||||
}
|
||||
|
||||
impl Job {
|
||||
pub(crate) async fn run<S>(self, ctx: JobCtx<S>) -> Result<Outcome, Error>
|
||||
where
|
||||
S: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + Send + Sync + 'static,
|
||||
{
|
||||
match self {
|
||||
Job::Reconcile => ctx.reconcile().await,
|
||||
Job::CreateQuote { mint, amount } => {
|
||||
let wallet = ctx.wallet(&mint)?;
|
||||
let quote = wallet
|
||||
.mint_quote(
|
||||
PaymentMethod::Known(KnownMethod::Bolt11),
|
||||
Some(Amount::from(amount)),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(Outcome::QuoteCreated {
|
||||
mint,
|
||||
quote_id: quote.id,
|
||||
request: quote.request,
|
||||
amount,
|
||||
})
|
||||
}
|
||||
Job::ClaimQuote { mint, quote_id } => {
|
||||
let wallet = ctx.wallet(&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 = ctx
|
||||
.sync_token_events(
|
||||
wallet,
|
||||
nostr_mint(&mint)?,
|
||||
&ctx.previous_ids(&mint),
|
||||
Some(keys::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 = ctx.wallet(&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 = ctx
|
||||
.sync_token_events(
|
||||
wallet,
|
||||
nostr_mint(&mint)?,
|
||||
&ctx.previous_ids(&mint),
|
||||
Some(keys::History {
|
||||
direction: TransactionDirection::Out,
|
||||
amount,
|
||||
redeemed: Vec::new(),
|
||||
sender: None,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(Outcome::Melted { update, amount })
|
||||
}
|
||||
Job::SendToken { mint, amount } => {
|
||||
let wallet = ctx.wallet(&mint)?;
|
||||
let prepared = wallet
|
||||
.prepare_send(Amount::from(amount), SendOptions::default())
|
||||
.await?;
|
||||
let token = prepared.confirm(None).await?.to_string();
|
||||
|
||||
let update = ctx
|
||||
.sync_token_events(
|
||||
wallet,
|
||||
nostr_mint(&mint)?,
|
||||
&ctx.previous_ids(&mint),
|
||||
Some(keys::History {
|
||||
direction: TransactionDirection::Out,
|
||||
amount,
|
||||
redeemed: Vec::new(),
|
||||
sender: None,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(Outcome::Sent { update, token })
|
||||
}
|
||||
Job::SendNutzap {
|
||||
recipient,
|
||||
amount,
|
||||
target,
|
||||
comment,
|
||||
} => {
|
||||
let (mint_url, mint_tag, p2pk) = recipient_wallet_info(&ctx, recipient).await?;
|
||||
let wallet = ctx.wallet(&mint_url)?;
|
||||
|
||||
let keysets = wallet
|
||||
.keysets(cdk::wallet::types::KeysetLoadPolicy::CacheOnly)
|
||||
.await?;
|
||||
|
||||
let infos: Vec<KeySetInfo> = keysets
|
||||
.iter()
|
||||
.map(|keyset| KeySetInfo {
|
||||
id: keyset.id,
|
||||
unit: keyset.unit.clone(),
|
||||
active: keyset.active.unwrap_or(true),
|
||||
input_fee_ppk: keyset.input_fee_ppk,
|
||||
final_expiry: keyset.final_expiry,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let options = SendOptions {
|
||||
conditions: Some(SpendingConditions::new_p2pk(p2pk, None)),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let token = wallet
|
||||
.prepare_send(Amount::from(amount), options)
|
||||
.await?
|
||||
.confirm(None)
|
||||
.await?;
|
||||
let proofs = token.proofs(&infos)?;
|
||||
|
||||
let mut tags = Vec::new();
|
||||
for proof in &proofs {
|
||||
tags.push(serde_json::to_string(proof)?);
|
||||
}
|
||||
|
||||
let event = keys::build_nutzap_event(
|
||||
&ctx.signer,
|
||||
recipient,
|
||||
&mint_tag,
|
||||
&tags,
|
||||
target,
|
||||
comment.as_deref().unwrap_or(""),
|
||||
)
|
||||
.await?;
|
||||
ctx.client.send_event(&event).await?;
|
||||
|
||||
let update = ctx
|
||||
.sync_token_events(
|
||||
wallet,
|
||||
nostr_mint(&mint_url)?,
|
||||
&ctx.previous_ids(&mint_url),
|
||||
Some(keys::History {
|
||||
direction: TransactionDirection::Out,
|
||||
amount,
|
||||
redeemed: Vec::new(),
|
||||
sender: None,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(Outcome::NutzapSent { update, amount })
|
||||
}
|
||||
Job::Receive { mint, token } => {
|
||||
let wallet = ctx.wallet(&mint)?;
|
||||
let received = wallet.receive(&token, ReceiveOptions::default()).await?;
|
||||
|
||||
let update = ctx
|
||||
.sync_token_events(
|
||||
wallet,
|
||||
nostr_mint(&mint)?,
|
||||
&ctx.previous_ids(&mint),
|
||||
Some(keys::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 = ctx.wallet(&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 = ctx
|
||||
.sync_token_events(
|
||||
wallet,
|
||||
nostr_mint(&mint)?,
|
||||
&ctx.previous_ids(&mint),
|
||||
Some(keys::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),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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>,
|
||||
},
|
||||
QuoteCreated {
|
||||
mint: MintUrl,
|
||||
quote_id: String,
|
||||
request: String,
|
||||
amount: u64,
|
||||
},
|
||||
QuoteMinted {
|
||||
quote_id: String,
|
||||
update: TokenUpdate,
|
||||
amount: u64,
|
||||
},
|
||||
Melted {
|
||||
update: TokenUpdate,
|
||||
amount: u64,
|
||||
},
|
||||
Sent {
|
||||
update: TokenUpdate,
|
||||
token: String,
|
||||
},
|
||||
NutzapSent {
|
||||
update: TokenUpdate,
|
||||
amount: u64,
|
||||
},
|
||||
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>,
|
||||
}
|
||||
|
||||
impl<S> JobCtx<S>
|
||||
where
|
||||
S: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + Sync,
|
||||
{
|
||||
fn wallet(&self, mint: &MintUrl) -> Result<&Wallet, Error> {
|
||||
self.wallets
|
||||
.get(mint)
|
||||
.ok_or_else(|| anyhow!("no open wallet for mint {mint}"))
|
||||
}
|
||||
|
||||
fn previous_ids(&self, mint: &MintUrl) -> Vec<EventId> {
|
||||
previous_ids(&self.tokens, mint)
|
||||
}
|
||||
|
||||
/// Publish the store's current unspent set as a fresh token event.
|
||||
async fn sync_token_events(
|
||||
&self,
|
||||
wallet: &Wallet,
|
||||
mint: Url,
|
||||
previous: &[EventId],
|
||||
history: Option<keys::History>,
|
||||
) -> Result<TokenUpdate, Error> {
|
||||
let me = self.signer.get_public_key_async().await?;
|
||||
let unspent = wallet.get_unspent_proofs().await?;
|
||||
|
||||
let proofs = unspent
|
||||
.iter()
|
||||
.map(cashu_proof)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
let mut token = TokenEvent::new(mint, proofs);
|
||||
token.del = previous.iter().map(|id| id.to_hex()).collect();
|
||||
let event = keys::build_token_event(&self.signer, &me, &token).await?;
|
||||
self.client.send_event(&event).await?;
|
||||
|
||||
if !previous.is_empty() {
|
||||
let deletion = keys::build_token_deletion(&self.signer, previous).await?;
|
||||
self.client.send_event(&deletion).await?;
|
||||
}
|
||||
|
||||
if let Some(history) = history {
|
||||
let history_event =
|
||||
keys::build_history_event(&self.signer, &me, &history, event.id, previous).await?;
|
||||
self.client.send_event(&history_event).await?;
|
||||
}
|
||||
|
||||
Ok(TokenUpdate {
|
||||
event_id: event.id,
|
||||
token,
|
||||
destroyed: previous.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Claim paid quotes, then converge each mint.
|
||||
async fn reconcile(self) -> Result<Outcome, Error> {
|
||||
let mut tokens = self.tokens.clone();
|
||||
let mut updates = Vec::new();
|
||||
|
||||
for (mint_url, wallet) in &self.wallets {
|
||||
if let Err(error) = wallet.recover_incomplete_sagas().await {
|
||||
log::warn!("saga recovery failed for {mint_url}: {error:#}");
|
||||
}
|
||||
|
||||
let minted = wallet.mint_unissued_quotes().await?;
|
||||
if minted == Amount::ZERO {
|
||||
continue;
|
||||
}
|
||||
|
||||
let update = self
|
||||
.sync_token_events(
|
||||
wallet,
|
||||
nostr_mint(mint_url)?,
|
||||
&previous_ids(&tokens, mint_url),
|
||||
Some(keys::History {
|
||||
direction: TransactionDirection::In,
|
||||
amount: u64::from(minted),
|
||||
redeemed: Vec::new(),
|
||||
sender: None,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
|
||||
for id in &update.destroyed {
|
||||
tokens.remove(id);
|
||||
}
|
||||
tokens.insert(update.event_id, update.token.clone());
|
||||
updates.push(update);
|
||||
}
|
||||
|
||||
for (mint_url, wallet) in &self.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 })
|
||||
}
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
/// Resolve a recipient's 10019 wallet info and pick a mint we share with them.
|
||||
async fn recipient_wallet_info<S>(
|
||||
ctx: &JobCtx<S>,
|
||||
recipient: PublicKey,
|
||||
) -> Result<(MintUrl, String, cdk::nuts::PublicKey), Error>
|
||||
where
|
||||
S: AsyncGetPublicKey + AsyncSignEvent + AsyncNip44 + Sync,
|
||||
{
|
||||
let filter = Filter::new()
|
||||
.author(recipient)
|
||||
.kind(Kind::Custom(10019))
|
||||
.limit(1);
|
||||
|
||||
let info = match ctx
|
||||
.client
|
||||
.database()
|
||||
.query(filter.clone())
|
||||
.await?
|
||||
.into_iter()
|
||||
.next()
|
||||
{
|
||||
Some(event) => event,
|
||||
None => {
|
||||
let mut stream = ctx
|
||||
.client
|
||||
.stream_events(filter)
|
||||
.timeout(FETCH_TIMEOUT)
|
||||
.await?;
|
||||
let mut found: Option<Event> = None;
|
||||
|
||||
while let Some((_url, result)) = stream.next().await {
|
||||
if let Ok(event) = result {
|
||||
let newer = found
|
||||
.as_ref()
|
||||
.is_none_or(|current| event.created_at > current.created_at);
|
||||
|
||||
if newer {
|
||||
found = Some(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
found.ok_or_else(|| anyhow!("recipient has no wallet info"))?
|
||||
}
|
||||
};
|
||||
|
||||
let (p2pk, mints) = parse_nutzap_info(&info)?;
|
||||
|
||||
for mint in mints {
|
||||
let Ok(mint_url) = MintUrl::from_str(&mint) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if ctx.wallets.contains_key(&mint_url) {
|
||||
return Ok((mint_url, mint, p2pk));
|
||||
}
|
||||
}
|
||||
|
||||
Err(anyhow!("no shared mint with the recipient"))
|
||||
}
|
||||
|
||||
fn parse_nutzap_info(event: &Event) -> Result<(cdk::nuts::PublicKey, Vec<String>), Error> {
|
||||
let mut p2pk = None;
|
||||
let mut mints = Vec::new();
|
||||
|
||||
for tag in event.tags.iter() {
|
||||
let Some(value) = tag.content() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
match tag.kind() {
|
||||
"pubkey" if p2pk.is_none() => {
|
||||
p2pk = Some(cdk::nuts::PublicKey::from_str(value)?);
|
||||
}
|
||||
"mint" => mints.push(value.to_string()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let Some(p2pk) = p2pk else {
|
||||
return Err(anyhow!("recipient has no wallet pubkey"));
|
||||
};
|
||||
|
||||
Ok((p2pk, mints))
|
||||
}
|
||||
|
||||
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 nostr_mint(mint: &MintUrl) -> Result<Url, Error> {
|
||||
Url::parse(&mint.to_string()).map_err(|error| anyhow!("invalid mint url: {error}"))
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "nip60_ui"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
common = { path = "../common" }
|
||||
nip60 = { path = "../nip60" }
|
||||
|
||||
gpui.workspace = true
|
||||
gpui-kit.workspace = true
|
||||
nostr-sdk.workspace = true
|
||||
anyhow.workspace = true
|
||||
smallvec.workspace = true
|
||||
@@ -0,0 +1,79 @@
|
||||
#![cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use gpui::{App, AppContext, ClickEvent, ParentElement, Styled, Window, px};
|
||||
use gpui_kit::component::button::{Button, ButtonVariants};
|
||||
use gpui_kit::component::input::{Input, InputState};
|
||||
use gpui_kit::component::notification::Notification;
|
||||
use gpui_kit::component::{WindowExt, h_flex, v_flex};
|
||||
use nip60::WalletRegistry;
|
||||
use nostr_sdk::prelude::{EventId, PublicKey};
|
||||
|
||||
pub mod wallet;
|
||||
|
||||
type SubmitFn = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) -> bool>;
|
||||
|
||||
/// Ask for an amount and send a nutzap to `recipient`, optionally
|
||||
/// nutzapping the event with `target`.
|
||||
pub fn open_nutzap(
|
||||
window: &mut Window,
|
||||
cx: &mut App,
|
||||
recipient: PublicKey,
|
||||
target: Option<EventId>,
|
||||
) {
|
||||
let input = cx.new(|cx| InputState::new(window, cx).placeholder("Amount (sats)"));
|
||||
|
||||
let send: SubmitFn = {
|
||||
let input = input.clone();
|
||||
Rc::new(move |_, window, cx| {
|
||||
let amount = match input.read(cx).value().trim().parse::<u64>() {
|
||||
Ok(amount) if amount > 0 => amount,
|
||||
_ => {
|
||||
window.push_notification(Notification::error("Enter an amount in sats"), cx);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
let wallet = WalletRegistry::global(cx);
|
||||
wallet.update(cx, |registry, cx| {
|
||||
registry.send_nutzap(recipient, amount, target, None, cx);
|
||||
});
|
||||
|
||||
true
|
||||
})
|
||||
};
|
||||
|
||||
window.open_dialog(cx, move |this, _window, _cx| {
|
||||
this.width(px(380.))
|
||||
.title("Send Nutzap")
|
||||
.on_ok({
|
||||
let send = send.clone();
|
||||
move |event, window, cx| send(event, window, cx)
|
||||
})
|
||||
.child(
|
||||
v_flex()
|
||||
.gap_3()
|
||||
.child(Input::new(&input).cleanable(true))
|
||||
.child(
|
||||
h_flex()
|
||||
.gap_1()
|
||||
.justify_end()
|
||||
.child(
|
||||
Button::new("cancel")
|
||||
.label("Cancel")
|
||||
.ghost()
|
||||
.on_click(|_, window, cx| window.close_dialog(cx)),
|
||||
)
|
||||
.child(Button::new("send").label("Send").primary().on_click({
|
||||
let send = send.clone();
|
||||
move |event, window, cx| {
|
||||
if send(event, window, cx) {
|
||||
window.close_dialog(cx);
|
||||
}
|
||||
}
|
||||
})),
|
||||
),
|
||||
)
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,422 @@
|
||||
use ::nip60::{HistoryEntry, MintQuoteEntry, WalletEvent, WalletRegistry};
|
||||
use common::TimestampExt;
|
||||
use gpui::prelude::FluentBuilder;
|
||||
use gpui::{
|
||||
App, AppContext, Context, Entity, EventEmitter, FocusHandle, Focusable, IntoElement,
|
||||
ParentElement, Render, SharedString, Styled, Subscription, Window, div,
|
||||
};
|
||||
use gpui_kit::assets::IconName;
|
||||
use gpui_kit::base::StyledExt as _;
|
||||
use gpui_kit::component::button::{Button, ButtonVariants as _};
|
||||
use gpui_kit::component::clipboard::Clipboard;
|
||||
use gpui_kit::component::dock::{Panel, PanelEvent};
|
||||
use gpui_kit::component::input::{Input, InputState};
|
||||
use gpui_kit::component::notification::Notification;
|
||||
use gpui_kit::component::scroll::ScrollableElement as _;
|
||||
use gpui_kit::component::separator::Separator;
|
||||
use gpui_kit::component::{ActiveTheme, Icon, Sizable, WindowExt, h_flex, v_flex};
|
||||
use nostr_sdk::prelude::*;
|
||||
use smallvec::SmallVec;
|
||||
pub fn init(window: &mut Window, cx: &mut App) -> Entity<WalletPanel> {
|
||||
cx.new(|cx| WalletPanel::new(window, cx))
|
||||
}
|
||||
|
||||
pub struct WalletPanel {
|
||||
name: SharedString,
|
||||
focus_handle: FocusHandle,
|
||||
|
||||
/// Mint URL input for the setup flow
|
||||
mint_input: Entity<InputState>,
|
||||
/// Amount input for sending a cashu token
|
||||
send_input: Entity<InputState>,
|
||||
/// Amount input for the funding invoice
|
||||
invoice_input: Entity<InputState>,
|
||||
/// Pasted token input for receiving ecash
|
||||
token_input: Entity<InputState>,
|
||||
/// The token produced by the last send, shown for copying
|
||||
sent_token: Option<SharedString>,
|
||||
|
||||
_subscriptions: SmallVec<[Subscription; 1]>,
|
||||
}
|
||||
|
||||
impl WalletPanel {
|
||||
fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let mint_input = cx.new(|cx| InputState::new(window, cx).placeholder("https://mint…"));
|
||||
let send_input = cx.new(|cx| InputState::new(window, cx).placeholder("Amount (sats)"));
|
||||
let invoice_input = cx.new(|cx| InputState::new(window, cx).placeholder("Amount (sats)"));
|
||||
let token_input = cx.new(|cx| InputState::new(window, cx).placeholder("cashu…"));
|
||||
|
||||
let wallet = WalletRegistry::global(cx);
|
||||
let mut subscriptions = SmallVec::new();
|
||||
subscriptions.push(
|
||||
cx.subscribe_in(
|
||||
&wallet,
|
||||
window,
|
||||
|this, _wallet, event, window, cx| match event {
|
||||
WalletEvent::Updated => cx.notify(),
|
||||
WalletEvent::Error(error) => {
|
||||
window.push_notification(Notification::error(error.clone()), cx);
|
||||
}
|
||||
WalletEvent::TokenCreated(token) => {
|
||||
this.sent_token = Some(token.clone().into());
|
||||
cx.notify();
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
Self {
|
||||
name: "Wallet".into(),
|
||||
focus_handle: cx.focus_handle(),
|
||||
mint_input,
|
||||
send_input,
|
||||
invoice_input,
|
||||
token_input,
|
||||
sent_token: None,
|
||||
_subscriptions: subscriptions,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_amount(&self, input: &Entity<InputState>, cx: &Context<Self>) -> Option<u64> {
|
||||
match input.read(cx).value().trim().parse::<u64>() {
|
||||
Ok(amount) if amount > 0 => Some(amount),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn setup(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let mint = self.mint_input.read(cx).value().trim().to_string();
|
||||
if mint.is_empty() {
|
||||
window.push_notification(Notification::error("Enter a mint URL"), cx);
|
||||
return;
|
||||
}
|
||||
|
||||
WalletRegistry::global(cx).update(cx, |registry, cx| {
|
||||
registry.setup(mint, cx);
|
||||
});
|
||||
}
|
||||
|
||||
fn send_token(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let Some(amount) = self.parse_amount(&self.send_input, cx) else {
|
||||
window.push_notification(Notification::error("Enter an amount in sats"), cx);
|
||||
return;
|
||||
};
|
||||
|
||||
WalletRegistry::global(cx).update(cx, |registry, cx| {
|
||||
registry.send_token(amount, cx);
|
||||
});
|
||||
}
|
||||
|
||||
fn create_invoice(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let Some(amount) = self.parse_amount(&self.invoice_input, cx) else {
|
||||
window.push_notification(Notification::error("Enter an amount in sats"), cx);
|
||||
return;
|
||||
};
|
||||
|
||||
WalletRegistry::global(cx).update(cx, |registry, cx| {
|
||||
registry.create_mint_quote(amount, cx);
|
||||
});
|
||||
}
|
||||
|
||||
fn claim_quote(&mut self, quote_id: String, cx: &mut Context<Self>) {
|
||||
WalletRegistry::global(cx).update(cx, |registry, cx| {
|
||||
registry.claim_mint_quote(quote_id, cx);
|
||||
});
|
||||
}
|
||||
|
||||
fn receive_token(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
let token = self.token_input.read(cx).value().trim().to_string();
|
||||
if token.is_empty() {
|
||||
window.push_notification(Notification::error("Paste a cashu token"), cx);
|
||||
return;
|
||||
}
|
||||
|
||||
WalletRegistry::global(cx).update(cx, |registry, cx| {
|
||||
registry.receive_token(token, cx);
|
||||
});
|
||||
}
|
||||
|
||||
fn render_balance(&self, cx: &Context<Self>) -> impl IntoElement {
|
||||
let balance = WalletRegistry::global(cx).read(cx).balance();
|
||||
|
||||
h_flex()
|
||||
.gap_2()
|
||||
.items_end()
|
||||
.child(
|
||||
div()
|
||||
.text_2xl()
|
||||
.child(SharedString::from(balance.to_string())),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.text_xs()
|
||||
.text_color(cx.theme().muted_foreground)
|
||||
.child("sats"),
|
||||
)
|
||||
}
|
||||
|
||||
fn render_setup(&self, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let has_wallet = WalletRegistry::global(cx).read(cx).has_wallet();
|
||||
|
||||
v_flex()
|
||||
.gap_1p5()
|
||||
.w_full()
|
||||
.child(
|
||||
div()
|
||||
.text_xs()
|
||||
.font_semibold()
|
||||
.text_color(cx.theme().muted_foreground)
|
||||
.child(SharedString::from(if has_wallet {
|
||||
"Add a mint:"
|
||||
} else {
|
||||
"Set up your wallet with a mint:"
|
||||
})),
|
||||
)
|
||||
.child(
|
||||
h_flex()
|
||||
.gap_1()
|
||||
.w_full()
|
||||
.child(Input::new(&self.mint_input).cleanable(true))
|
||||
.child(
|
||||
Button::new("setup")
|
||||
.label(if has_wallet { "Add" } else { "Set up" })
|
||||
.primary()
|
||||
.small()
|
||||
.on_click(cx.listener(move |this, _ev, window, cx| {
|
||||
this.setup(window, cx);
|
||||
})),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fn render_send(&self, cx: &Context<Self>) -> impl IntoElement {
|
||||
v_flex()
|
||||
.gap_1p5()
|
||||
.w_full()
|
||||
.child(
|
||||
div()
|
||||
.text_xs()
|
||||
.font_semibold()
|
||||
.text_color(cx.theme().muted_foreground)
|
||||
.child("Send ecash:"),
|
||||
)
|
||||
.child(
|
||||
h_flex()
|
||||
.gap_1()
|
||||
.w_full()
|
||||
.child(Input::new(&self.send_input).cleanable(true))
|
||||
.child(
|
||||
Button::new("send")
|
||||
.label("Send")
|
||||
.small()
|
||||
.on_click(cx.listener(move |this, _ev, window, cx| {
|
||||
this.send_token(window, cx);
|
||||
})),
|
||||
),
|
||||
)
|
||||
.when_some(self.sent_token.as_ref(), |this, token| {
|
||||
this.child(
|
||||
h_flex()
|
||||
.gap_1()
|
||||
.w_full()
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.truncate()
|
||||
.text_color(cx.theme().muted_foreground)
|
||||
.child(token.clone()),
|
||||
)
|
||||
.child(
|
||||
Clipboard::new("copy-token")
|
||||
.accessibility_label("Copy cashu token")
|
||||
.value_fn({
|
||||
let token = token.clone();
|
||||
move |_, _| SharedString::from(token.to_string())
|
||||
}),
|
||||
),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn render_receive(&self, cx: &Context<Self>) -> impl IntoElement {
|
||||
let quotes = WalletRegistry::global(cx).read(cx).mint_quotes().to_vec();
|
||||
|
||||
let mut section =
|
||||
v_flex()
|
||||
.gap_1p5()
|
||||
.w_full()
|
||||
.child(
|
||||
div()
|
||||
.text_xs()
|
||||
.font_semibold()
|
||||
.text_color(cx.theme().muted_foreground)
|
||||
.child("Receive:"),
|
||||
)
|
||||
.child(
|
||||
h_flex()
|
||||
.gap_1()
|
||||
.w_full()
|
||||
.child(Input::new(&self.invoice_input).cleanable(true))
|
||||
.child(Button::new("invoice").label("Invoice").small().on_click(
|
||||
cx.listener(move |this, _ev, window, cx| {
|
||||
this.create_invoice(window, cx);
|
||||
}),
|
||||
)),
|
||||
);
|
||||
|
||||
for quote in quotes {
|
||||
section = section.child(self.render_quote("e, cx));
|
||||
}
|
||||
|
||||
section.child(
|
||||
h_flex()
|
||||
.gap_1()
|
||||
.w_full()
|
||||
.child(Input::new(&self.token_input).cleanable(true))
|
||||
.child(
|
||||
Button::new("receive")
|
||||
.label("Redeem")
|
||||
.small()
|
||||
.on_click(cx.listener(move |this, _ev, window, cx| {
|
||||
this.receive_token(window, cx);
|
||||
})),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
fn render_quote(&self, quote: &MintQuoteEntry, cx: &Context<Self>) -> impl IntoElement {
|
||||
h_flex()
|
||||
.gap_1()
|
||||
.w_full()
|
||||
.child(
|
||||
div()
|
||||
.flex_1()
|
||||
.min_w_0()
|
||||
.truncate()
|
||||
.text_color(cx.theme().muted_foreground)
|
||||
.child(SharedString::from(quote.request.clone())),
|
||||
)
|
||||
.child(
|
||||
Clipboard::new(SharedString::from(format!("copy_{}", quote.quote_id)))
|
||||
.accessibility_label("Copy lightning invoice")
|
||||
.value_fn({
|
||||
let request = SharedString::from(quote.request.clone());
|
||||
move |_, _| request.clone()
|
||||
}),
|
||||
)
|
||||
.child(
|
||||
Button::new(SharedString::from(format!("claim_{}", quote.quote_id)))
|
||||
.label("Claim")
|
||||
.small()
|
||||
.on_click({
|
||||
let quote_id = quote.quote_id.clone();
|
||||
cx.listener(move |this, _ev, _window, cx| {
|
||||
this.claim_quote(quote_id.clone(), cx);
|
||||
})
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
fn render_history(&self, cx: &Context<Self>) -> impl IntoElement {
|
||||
let history = WalletRegistry::global(cx).read(cx).history().to_vec();
|
||||
|
||||
let mut section = v_flex().gap_1().w_full().child(
|
||||
div()
|
||||
.text_xs()
|
||||
.font_semibold()
|
||||
.text_color(cx.theme().muted_foreground)
|
||||
.child("History:"),
|
||||
);
|
||||
|
||||
if history.is_empty() {
|
||||
section = section.child(
|
||||
div()
|
||||
.text_xs()
|
||||
.text_color(cx.theme().muted_foreground)
|
||||
.child("No transactions yet."),
|
||||
);
|
||||
}
|
||||
|
||||
for entry in history {
|
||||
section = section.child(self.render_history_entry(&entry, cx));
|
||||
}
|
||||
|
||||
section
|
||||
}
|
||||
|
||||
fn render_history_entry(&self, entry: &HistoryEntry, cx: &Context<Self>) -> impl IntoElement {
|
||||
let (label, color) = match entry.direction {
|
||||
TransactionDirection::In => ("Received", cx.theme().success),
|
||||
TransactionDirection::Out => ("Sent", cx.theme().danger),
|
||||
};
|
||||
|
||||
h_flex()
|
||||
.justify_between()
|
||||
.w_full()
|
||||
.py_0p5()
|
||||
.text_xs()
|
||||
.child(
|
||||
h_flex()
|
||||
.gap_2()
|
||||
.child(div().text_color(color).child(label))
|
||||
.child(SharedString::from(format!("{} sats", entry.amount))),
|
||||
)
|
||||
.child(
|
||||
div()
|
||||
.text_color(cx.theme().muted_foreground)
|
||||
.child(entry.created_at.to_human_time()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl gpui_kit::component::dock::BasePanel for WalletPanel {
|
||||
fn panel_name(&self) -> &'static str {
|
||||
"Wallet"
|
||||
}
|
||||
}
|
||||
|
||||
impl Panel for WalletPanel {
|
||||
fn title(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
h_flex()
|
||||
.gap_1p5()
|
||||
.child(
|
||||
Icon::new(IconName::Wallet)
|
||||
.small()
|
||||
.text_color(cx.theme().muted_foreground),
|
||||
)
|
||||
.child(self.name.clone())
|
||||
.into_any_element()
|
||||
}
|
||||
}
|
||||
|
||||
impl EventEmitter<PanelEvent> for WalletPanel {}
|
||||
|
||||
impl Focusable for WalletPanel {
|
||||
fn focus_handle(&self, _: &App) -> FocusHandle {
|
||||
self.focus_handle.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for WalletPanel {
|
||||
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let has_wallet = WalletRegistry::global(cx).read(cx).has_wallet();
|
||||
|
||||
v_flex()
|
||||
.p_3()
|
||||
.gap_3()
|
||||
.w_full()
|
||||
.overflow_y_scrollbar()
|
||||
.text_xs()
|
||||
.when(!has_wallet, |this| this.child(self.render_setup(cx)))
|
||||
.when(has_wallet, |this| {
|
||||
this.child(self.render_balance(cx))
|
||||
.child(Separator::horizontal())
|
||||
.child(self.render_send(cx))
|
||||
.child(self.render_receive(cx))
|
||||
.child(Separator::horizontal())
|
||||
.child(self.render_history(cx))
|
||||
.child(self.render_setup(cx))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -9,11 +9,11 @@ ui = { path = "../ui" }
|
||||
gpui-kit.workspace = true
|
||||
common = { path = "../common" }
|
||||
state = { path = "../state" }
|
||||
nip29 = { path = "../nip29" }
|
||||
nip29_ui = { path = "../nip29_ui" }
|
||||
nip4e = { path = "../nip4e" }
|
||||
chat = { path = "../chat" }
|
||||
chat_ui = { path = "../chat_ui" }
|
||||
nip29 = { path = "../nip29" }
|
||||
nip29_ui = { path = "../nip29_ui" }
|
||||
settings = { path = "../settings" }
|
||||
speech = { path = "../speech" }
|
||||
person = { path = "../person" }
|
||||
@@ -30,3 +30,7 @@ serde.workspace = true
|
||||
log.workspace = true
|
||||
rand.workspace = true
|
||||
smallvec.workspace = true
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
nip60 = { path = "../nip60" }
|
||||
nip60_ui = { path = "../nip60_ui" }
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
use std::rc::Rc;
|
||||
|
||||
use gpui::{App, AppContext, ClickEvent, ParentElement, Styled, Window, px};
|
||||
use gpui_kit::assets::IconName;
|
||||
use gpui_kit::component::button::{Button, ButtonVariants};
|
||||
use gpui_kit::component::input::{Input, InputState};
|
||||
use gpui_kit::component::notification::Notification;
|
||||
use gpui_kit::component::{WindowExt, h_flex, v_flex};
|
||||
use std::rc::Rc;
|
||||
|
||||
use gpui::{App, AppContext, ClickEvent, ParentElement, Styled, Window, px};
|
||||
use nip29::{GroupReference, GroupsRegistry};
|
||||
|
||||
type SubmitFn = Rc<dyn Fn(&ClickEvent, &mut Window, &mut App) -> bool>;
|
||||
|
||||
@@ -61,6 +61,8 @@ enum Command {
|
||||
ShowContactList,
|
||||
ShowInbox,
|
||||
ShowBrowse,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
ShowWallet,
|
||||
NewChat,
|
||||
NewGroup,
|
||||
JoinGroup,
|
||||
@@ -196,6 +198,30 @@ impl Workspace {
|
||||
}),
|
||||
);
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let wallet = ::nip60::WalletRegistry::global(cx);
|
||||
|
||||
subscriptions.push(cx.subscribe_in(
|
||||
&wallet,
|
||||
window,
|
||||
|_this, _wallet, event, window, cx| match event {
|
||||
::nip60::WalletEvent::Error(error) => {
|
||||
window.push_notification(Notification::error(error.clone()), cx);
|
||||
}
|
||||
::nip60::WalletEvent::TokenCreated(_) => {
|
||||
window.push_notification(
|
||||
Notification::new()
|
||||
.message("Cashu token created, copy it from the wallet panel")
|
||||
.with_type(NotificationType::Success),
|
||||
cx,
|
||||
);
|
||||
}
|
||||
::nip60::WalletEvent::Updated => {}
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
App::on_action(cx, {
|
||||
let workspace = workspace.clone();
|
||||
move |action, cx| {
|
||||
@@ -307,6 +333,11 @@ impl Workspace {
|
||||
let panel = browse::init(self.dock.downgrade(), window, cx);
|
||||
self.add_panel_to_dock(panel, DockPlacement::Center, window, cx);
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Command::ShowWallet => {
|
||||
let panel = nip60_ui::wallet::init(window, cx);
|
||||
self.add_panel_to_dock(panel, DockPlacement::Center, window, cx);
|
||||
}
|
||||
Command::NewChat => {
|
||||
new_chat::open(self.dock.downgrade(), window, cx);
|
||||
}
|
||||
|
||||
@@ -43,6 +43,19 @@ impl Sidebar {
|
||||
// Whether to show the create button for the contact picker
|
||||
let create_button = contacts_open && !self.selected_contacts.is_empty();
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let wallet_row = Some(
|
||||
Nav::new("wallet")
|
||||
.prefix(Icon::new(gpui_kit::assets::IconName::Wallet).small())
|
||||
.label("Wallet")
|
||||
.text_sm()
|
||||
.on_click(|_, window, cx| {
|
||||
window.dispatch_action(Box::new(crate::Command::ShowWallet), cx)
|
||||
}),
|
||||
);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let wallet_row: Option<Nav> = None;
|
||||
|
||||
let (list_id, title) = if contacts_open {
|
||||
("sidebar-contacts", Some("Contacts"))
|
||||
} else if requests_open {
|
||||
@@ -75,6 +88,7 @@ impl Sidebar {
|
||||
window.dispatch_action(Box::new(Command::ShowBrowse), cx)
|
||||
}),
|
||||
)
|
||||
.when_some(wallet_row, |this, row| this.child(row))
|
||||
.child(
|
||||
Nav::new("reqs")
|
||||
.prefix(Icon::new(IconName::Invite).small())
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
+387
@@ -0,0 +1,387 @@
|
||||
# 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 `10019` nutzap info event advertises the user's
|
||||
NIP-65 relay list (queried from the local database), never the bootstrap
|
||||
relays; subscriptions and publishes ride the SDK's NIP-65 handling.
|
||||
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
|
||||
(with `del` set to the previous event ids) -> 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)`: a job in the queue — `wallet.mint_quote` ->
|
||||
invoice recorded in `mint_quotes()` for the UI; poll /
|
||||
`claim_mint_quote(id)`, 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 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 reconcile: `recover_incomplete_sagas` and
|
||||
`mint_unissued_quotes` (required by cdk to clear interrupted operations),
|
||||
then converge 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,
|
||||
`7375`/deletion/`7376` event builders, the `History` payload.
|
||||
- `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.
|
||||
|
||||
### Audit (post phase 3) — done
|
||||
|
||||
Backend review before Phase 4: keep it simple, no premature edge-case
|
||||
handling, struct/impl blocks over standalone functions. Applied:
|
||||
|
||||
- Code shape: `keys::WalletData` carries generate/derive_seed/decrypt/
|
||||
to_event as an impl block; `ops::Job::run` and the `JobCtx` helpers
|
||||
(`wallet`, `previous_ids`, `sync_token_events`, `reconcile`) are impl
|
||||
methods; `LoadedState::load`, `WalletRegistry::open_store` and the
|
||||
filters are associated functions; nutzap tag parsing moved into a
|
||||
`Nutzap` struct (dropped the speculative `mint` tag fallback for the
|
||||
current `u` tag). `History` moved to `keys.rs` so `build_history_event`
|
||||
takes one struct instead of eight arguments.
|
||||
- Spec gap: the sync tail never set `TokenEvent.del` — new `7375`s now
|
||||
carry the previous event ids, so superseded tokens stay pruned even if
|
||||
a NIP-09 delete is dropped by a relay.
|
||||
- Bug: `start_job` errored "Wallet is not ready" for the auto `Reconcile`
|
||||
scheduled before the redb store finished opening. Jobs scheduled while
|
||||
the store is opening now queue and run once `ensure_wallets` completes;
|
||||
`apply_loaded` no longer schedules a redundant `Reconcile`.
|
||||
- Bug: a late-landing stale wallet decrypt could overwrite a newer
|
||||
`17375`; `absorb_wallet` now re-checks `created_at` when applying.
|
||||
- Consistency: an unreadable live token event logs a warning instead of
|
||||
surfacing an error event (same as the load path); nutzaps arriving with
|
||||
no wallet set up are dropped (a fresh setup would generate a different
|
||||
key, so they were unredeemable anyway).
|
||||
- Invariant: quote creation moved into the serialized job queue
|
||||
(`Job::CreateQuote` / `Outcome::QuoteCreated`) — `mint_quote` writes to
|
||||
the cdk store, so it must not interleave with running jobs. This also
|
||||
collapsed the mint-resolution boilerplate shared by quote/melt/send
|
||||
into `primary_mint`, and `MintQuoteEntry.mint` is now a `cdk::MintUrl`.
|
||||
- Reconcile now calls `recover_incomplete_sagas` (the plan promised it;
|
||||
it was missing), before `mint_unissued_quotes`. It is best-effort: the
|
||||
cdk-redb fresh-store init does not create the `wallet_sagas` table
|
||||
(upstream bug), so the first recovery attempts fail with "table does
|
||||
not exist" until a saga is written — logged, never fatal.
|
||||
|
||||
Not changed, deliberately: per-outcome `Outcome` variants, the bounded
|
||||
notification dedup set, the single queued Reconcile collapse, and the
|
||||
remaining small conversion helpers in `ops.rs` (`cashu_proof`,
|
||||
`proof_info`, `nostr_mint`) — they are simple, and further abstraction
|
||||
would be over-engineering.
|
||||
|
||||
### Phase 4 — UI (done)
|
||||
|
||||
Implemented in a new `crates/nip60_ui` (crate-level wasm gate, so it
|
||||
compiles to nothing on web; consumers list it under
|
||||
`[target.'cfg(not(target_arch = "wasm32"))'.dependencies]`):
|
||||
|
||||
- Backend additions: `WalletRegistry::history()` (`HistoryEntry` list,
|
||||
newest first, from live + cached `7376`s), and `send_nutzap(recipient,
|
||||
amount, target, comment)` — `Job::SendNutzap` fetches the recipient's
|
||||
`10019` from the local database (falling back to `stream_events`),
|
||||
picks the first shared mint, P2PK-locks a `prepare_send` to their
|
||||
wallet pubkey, publishes a public `9321` (`p`/`u`/`unit`/`proof` tags,
|
||||
optional `e`), then runs the usual sync tail with an out-history.
|
||||
- `wallet.rs` — `WalletPanel` in the left dock: balance, setup/add-mint,
|
||||
send-token (token shown for copy), receive (invoice per quote with
|
||||
copy + claim, paste-token redeem), history list. Subscribes to
|
||||
`WalletEvent`; errors surface as notifications here and, via a
|
||||
workspace-level subscription, even when the panel is closed.
|
||||
- `lib.rs` — `open_nutzap` dialog (amount prompt) reused by chat.
|
||||
- Sidebar: "Wallet" row under Browse (gated off on wasm), dispatching
|
||||
`Command::ShowWallet` -> dock the panel.
|
||||
- `chat_ui`: a coins button in the composer opens the nutzap dialog for
|
||||
the room's peer; group rooms are declined with a warning (v1 is
|
||||
direct-chat only).
|
||||
- `nip29_ui`: "Send Nutzap" context-menu item on messages, nutzapping
|
||||
the author with an `e` tag on the message.
|
||||
|
||||
Not rendered yet: nutzaps/tokens do not appear in the chat timeline; the
|
||||
wallet panel history is the only transaction view.
|
||||
|
||||
## 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