Skip to content

nostr events fix 2 #104

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
140 changes: 35 additions & 105 deletions client/src/bin/space-cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,7 @@ use spaces_client::{
};
use spaces_protocol::bitcoin::{Amount, FeeRate, OutPoint, Txid};
use spaces_wallet::{
bitcoin::secp256k1::schnorr::Signature,
export::WalletExport,
nostr::{NostrEvent, NostrTag},
Listing,
bitcoin::secp256k1::schnorr::Signature, export::WalletExport, nostr::NostrEvent, Listing,
};

#[derive(Parser, Debug)]
Expand Down Expand Up @@ -264,21 +261,18 @@ enum Commands {
SignEvent {
/// Space name (e.g., @example)
space: String,

/// Path to a Nostr event json file (omit for stdin)
#[arg(short, long)]
input: Option<PathBuf>,

/// Include a space-tag and trust path data
#[arg(short, long)]
anchor: bool,
/// Prefer the most recent trust path (not recommended)
#[arg(long)]
prefer_recent: bool,
},
/// Verify a signed Nostr event against the space's public key
#[command(name = "verifyevent")]
VerifyEvent {
/// Space name (e.g., @example)
space: String,

/// Path to a signed Nostr event json file (omit for stdin)
#[arg(short, long)]
input: Option<PathBuf>,
Expand All @@ -290,9 +284,9 @@ enum Commands {
space: String,
/// The DNS zone file path (omit for stdin)
input: Option<PathBuf>,
/// Skip including bundled Merkle proof in the event.
/// Prefer the most recent trust path (not recommended)
#[arg(long)]
skip_anchor: bool,
prefer_recent: bool,
},
/// Updates the Merkle trust path for space-anchored Nostr events
#[command(name = "refreshanchor")]
Expand Down Expand Up @@ -439,62 +433,15 @@ impl SpaceCli {
&self,
space: String,
event: NostrEvent,
anchor: bool,
most_recent: bool,
) -> Result<NostrEvent, ClientError> {
let mut result = self
let result = self
.client
.wallet_sign_event(&self.wallet, &space, event)
.wallet_sign_event(&self.wallet, &space, event, Some(most_recent))
.await?;

if anchor {
result = self.add_anchor(result, most_recent).await?
}

Ok(result)
}
async fn add_anchor(
&self,
mut event: NostrEvent,
most_recent: bool,
) -> Result<NostrEvent, ClientError> {
let space = match event.space() {
None => {
return Err(ClientError::Custom(
"A space tag is required to add an anchor".to_string(),
))
}
Some(space) => space,
};

let spaceout = self
.client
.get_space(&space)
.await
.map_err(|e| ClientError::Custom(e.to_string()))?
.ok_or(ClientError::Custom(format!(
"Space not found \"{}\"",
space
)))?;

event.proof = Some(
base64::prelude::BASE64_STANDARD.encode(
self.client
.prove_spaceout(
OutPoint {
txid: spaceout.txid,
vout: spaceout.spaceout.n as _,
},
Some(most_recent),
)
.await
.map_err(|e| ClientError::Custom(e.to_string()))?
.proof,
),
);

Ok(event)
}
async fn send_request(
&self,
req: Option<RpcWalletRequest>,
Expand Down Expand Up @@ -894,41 +841,27 @@ async fn handle_commands(cli: &SpaceCli, command: Commands) -> Result<(), Client
println!("{} Listing verified", "✓".color(Color::Green));
}
Commands::SignEvent {
mut space,
space,
input,
anchor,
prefer_recent,
} => {
let mut event = read_event(input)
let space = normalize_space(&space);
let event = read_event(input)
.map_err(|e| ClientError::Custom(format!("input error: {}", e.to_string())))?;

space = normalize_space(&space);
match event.space() {
None if anchor => event
.tags
.insert(0, NostrTag(vec!["space".to_string(), space.clone()])),
Some(tag) => {
if tag != space {
return Err(ClientError::Custom(format!(
"Expected a space tag with value '{}', got '{}'",
space, tag
)));
}
}
_ => {}
};

let result = cli.sign_event(space, event, anchor, false).await?;
let result = cli.sign_event(space, event, prefer_recent).await?;
println!("{}", serde_json::to_string(&result).expect("result"));
}
Commands::SignZone {
space,
input,
skip_anchor,
prefer_recent,
} => {
let update = encode_dns_update(&space, input)
let space = normalize_space(&space);
let event = encode_dns_update(input)
.map_err(|e| ClientError::Custom(format!("Parse error: {}", e)))?;
let result = cli.sign_event(space, update, !skip_anchor, false).await?;

let result = cli.sign_event(space, event, prefer_recent).await?;
println!("{}", serde_json::to_string(&result).expect("result"));
}
Commands::RefreshAnchor {
Expand All @@ -937,34 +870,31 @@ async fn handle_commands(cli: &SpaceCli, command: Commands) -> Result<(), Client
} => {
let event = read_event(input)
.map_err(|e| ClientError::Custom(format!("input error: {}", e.to_string())))?;
let space = match event.space() {
None => {
return Err(ClientError::Custom(
"Not a space-anchored event (no space tag)".to_string(),
))
}
Some(space) => space,
};

let mut event = cli
.client
.verify_event(&space, event)
cli.client
.verify_event(event.clone())
.await
.map_err(|e| ClientError::Custom(e.to_string()))?;
event.proof = None;
event = cli.add_anchor(event, prefer_recent).await?;

println!("{}", serde_json::to_string(&event).expect("result"));
let e = event.clone();
let space = e.get_space_tag().expect("space tag").0;
let result = cli
.client
.wallet_sign_event(&cli.wallet, space, event, Some(prefer_recent))
.await?;
println!("{}", serde_json::to_string(&result).expect("result"));
}
Commands::VerifyEvent { space, input } => {
let event = read_event(input)
.map_err(|e| ClientError::Custom(format!("input error: {}", e.to_string())))?;
let event = cli
.client
.verify_event(&space, event)
cli.client
.verify_event(event.clone())
.await
.map_err(|e| ClientError::Custom(e.to_string()))?;

if event.get_space_tag().expect("space tag").0 != &space {
return Err(ClientError::Custom(
"Space tag does not match specified space".to_string(),
));
}
println!("{}", serde_json::to_string(&event).expect("result"));
}
}
Expand All @@ -976,7 +906,7 @@ fn default_rpc_url(chain: &ExtendedNetwork) -> String {
format!("http://127.0.0.1:{}", default_spaces_rpc_port(chain))
}

fn encode_dns_update(space: &str, zone_file: Option<PathBuf>) -> anyhow::Result<NostrEvent> {
fn encode_dns_update(zone_file: Option<PathBuf>) -> anyhow::Result<NostrEvent> {
// domain crate panics if zone doesn't end in a new line
let zone = get_input(zone_file)? + "\n";

Expand All @@ -1000,7 +930,7 @@ fn encode_dns_update(space: &str, zone_file: Option<PathBuf>) -> anyhow::Result<
Ok(NostrEvent::new(
871_222,
&base64::prelude::BASE64_STANDARD.encode(msg.as_slice()),
vec![NostrTag(vec!["space".to_string(), space.to_string()])],
vec![],
))
}

Expand Down
74 changes: 43 additions & 31 deletions client/src/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::{
};

use anyhow::{anyhow, Context};
use base64::Engine;
use bdk::{
bitcoin::{Amount, BlockHash, FeeRate, Network, Txid},
chain::BlockId,
Expand Down Expand Up @@ -49,19 +50,18 @@ use tokio::{
};

use crate::auth::BasicAuthLayer;
use crate::wallets::WalletInfoWithProgress;
use crate::{
calc_progress,
checker::TxChecker,
client::{BlockMeta, TxEntry, BlockchainInfo},
client::{BlockMeta, BlockchainInfo, TxEntry},
config::ExtendedNetwork,
deserialize_base64, serialize_base64,
source::BitcoinRpc,
spaces::{COMMIT_BLOCK_INTERVAL, ROOT_ANCHORS_COUNT},
store::{ChainState, LiveSnapshot, RolloutEntry, Sha256},
wallets::{
AddressKind, ListSpacesResponse, RpcWallet, TxInfo, TxResponse, WalletCommand,
WalletResponse,
WalletInfoWithProgress, WalletResponse,
},
};

Expand Down Expand Up @@ -147,9 +147,8 @@ pub enum ChainStateCommand {
resp: Responder<anyhow::Result<()>>,
},
VerifyEvent {
space: String,
event: NostrEvent,
resp: Responder<anyhow::Result<NostrEvent>>,
resp: Responder<anyhow::Result<()>>,
},
ProveSpaceout {
outpoint: OutPoint,
Expand Down Expand Up @@ -221,18 +220,15 @@ pub trait Rpc {
async fn wallet_import(&self, wallet: WalletExport) -> Result<(), ErrorObjectOwned>;

#[method(name = "verifyevent")]
async fn verify_event(
&self,
space: &str,
event: NostrEvent,
) -> Result<NostrEvent, ErrorObjectOwned>;
async fn verify_event(&self, event: NostrEvent) -> Result<(), ErrorObjectOwned>;

#[method(name = "walletsignevent")]
async fn wallet_sign_event(
&self,
wallet: &str,
space: &str,
event: NostrEvent,
most_recent: Option<bool>,
) -> Result<NostrEvent, ErrorObjectOwned>;

#[method(name = "walletgetinfo")]
Expand Down Expand Up @@ -507,7 +503,11 @@ impl WalletManager {
Ok(export)
}

pub async fn create_wallet(&self, client: &reqwest::Client, name: &str) -> anyhow::Result<String> {
pub async fn create_wallet(
&self,
client: &reqwest::Client,
name: &str,
) -> anyhow::Result<String> {
let mnemonic: GeneratedKey<_, Tap> =
Mnemonic::generate((WordCount::Words12, Language::English))
.map_err(|_| anyhow!("Mnemonic generation error"))?;
Expand All @@ -518,7 +518,12 @@ impl WalletManager {
Ok(mnemonic.to_string())
}

pub async fn recover_wallet(&self, client: &reqwest::Client, name: &str, mnemonic: &str) -> anyhow::Result<()> {
pub async fn recover_wallet(
&self,
client: &reqwest::Client,
name: &str,
mnemonic: &str,
) -> anyhow::Result<()> {
let start_block = self.get_wallet_start_block(client).await?;
self.setup_new_wallet(name.to_string(), mnemonic.to_string(), start_block)?;
self.load_wallet(name).await?;
Expand Down Expand Up @@ -892,13 +897,9 @@ impl RpcServer for RpcServerImpl {
})
}

async fn verify_event(
&self,
space: &str,
event: NostrEvent,
) -> Result<NostrEvent, ErrorObjectOwned> {
async fn verify_event(&self, event: NostrEvent) -> Result<(), ErrorObjectOwned> {
self.store
.verify_event(space, event)
.verify_event(event)
.await
.map_err(|error| ErrorObjectOwned::owned(-1, error.to_string(), None::<String>))
}
Expand All @@ -907,8 +908,27 @@ impl RpcServer for RpcServerImpl {
&self,
wallet: &str,
space: &str,
event: NostrEvent,
mut event: NostrEvent,
most_recent: Option<bool>,
) -> Result<NostrEvent, ErrorObjectOwned> {
let most_recent = most_recent.unwrap_or(false);
let spaceout = self.get_space(space).await?.ok_or(ErrorObjectOwned::owned(
-1,
format!("Space not found \"{}\"", space),
None::<String>,
))?;
let proof = base64::prelude::BASE64_STANDARD.encode(
self.prove_spaceout(
OutPoint {
txid: spaceout.txid,
vout: spaceout.spaceout.n as _,
},
Some(most_recent),
)
.await?
.proof,
);
event.set_space_tag(space, &proof);
self.wallet(&wallet)
.await?
.send_sign_event(space, event)
Expand Down Expand Up @@ -1281,12 +1301,8 @@ impl AsyncChainState {
SpacesWallet::verify_listing::<Sha256>(chain_state, &listing).map(|_| ()),
);
}
ChainStateCommand::VerifyEvent { space, event, resp } => {
_ = resp.send(SpacesWallet::verify_event::<Sha256>(
chain_state,
&space,
event,
));
ChainStateCommand::VerifyEvent { event, resp } => {
_ = resp.send(SpacesWallet::verify_event::<Sha256>(chain_state, event));
}
ChainStateCommand::ProveSpaceout {
prefer_recent,
Expand Down Expand Up @@ -1474,14 +1490,10 @@ impl AsyncChainState {
resp_rx.await?
}

pub async fn verify_event(&self, space: &str, event: NostrEvent) -> anyhow::Result<NostrEvent> {
pub async fn verify_event(&self, event: NostrEvent) -> anyhow::Result<()> {
let (resp, resp_rx) = oneshot::channel();
self.sender
.send(ChainStateCommand::VerifyEvent {
space: space.to_string(),
event,
resp,
})
.send(ChainStateCommand::VerifyEvent { event, resp })
.await?;
resp_rx.await?
}
Expand Down
Loading
Loading