Skip to content

Commit

Permalink
sdk: adapt to use NostrSigner trait
Browse files Browse the repository at this point in the history
Signed-off-by: Yuki Kishimoto <[email protected]>
  • Loading branch information
yukibtc committed Oct 17, 2024
1 parent 20dee5b commit 924b722
Show file tree
Hide file tree
Showing 17 changed files with 144 additions and 272 deletions.
24 changes: 13 additions & 11 deletions crates/nostr-database/examples/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,27 +24,29 @@ async fn main() {
.unwrap();
let keys_b = Keys::new(secret_key);

let index = DatabaseHelper::unbounded();
let helper = DatabaseHelper::unbounded();

for i in 0..100_000 {
let event = EventBuilder::text_note(format!("Event #{i}"), [])
.to_event(&keys_a)
.sign_with_keys(&keys_a)
.unwrap();
index.index_event(&event).await;
helper.index_event(&event).await;

let event = EventBuilder::text_note(
format!("Reply to event #{i}"),
[Tag::event(event.id), Tag::public_key(event.pubkey)],
)
.to_event(&keys_b)
.sign_with_keys(&keys_b)
.unwrap();
index.index_event(&event).await;
helper.index_event(&event).await;
}

for i in 0..1000 {
let metadata = Metadata::new().name(format!("Name #{i}"));
let event = EventBuilder::metadata(&metadata).to_event(&keys_a).unwrap();
index.index_event(&event).await;
let event = EventBuilder::metadata(&metadata)
.sign_with_keys(&keys_a)
.unwrap();
helper.index_event(&event).await;
}

for i in 0..500_000 {
Expand All @@ -53,20 +55,20 @@ async fn main() {
"Custom with d tag",
[Tag::identifier(format!("myid{i}"))],
)
.to_event(&keys_a)
.sign_with_keys(&keys_a)
.unwrap();
index.index_event(&event).await;
helper.index_event(&event).await;
}

let ids = index
let events = helper
.query(vec![Filter::new()
.kinds(vec![Kind::Metadata, Kind::Custom(123), Kind::TextNote])
.limit(20)
//.kind(Kind::Custom(123))
//.identifier("myid5000")
.author(keys_a.public_key())])
.await;
println!("Got {} ids", ids.len());
println!("Got {} events", events.len());

loop {
tokio::time::sleep(Duration::from_secs(60)).await;
Expand Down
10 changes: 6 additions & 4 deletions crates/nostr-database/examples/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,22 +34,24 @@ async fn main() {

for i in 0..100_000 {
let event = EventBuilder::text_note(format!("Event #{i}"), [])
.to_event(&keys_a)
.sign_with_keys(&keys_a)
.unwrap();
database.save_event(&event).await.unwrap();

let event = EventBuilder::text_note(
format!("Reply to event #{i}"),
[Tag::event(event.id), Tag::public_key(event.pubkey)],
)
.to_event(&keys_b)
.sign_with_keys(&keys_b)
.unwrap();
database.save_event(&event).await.unwrap();
}

for i in 0..10 {
let metadata = Metadata::new().name(format!("Name #{i}"));
let event = EventBuilder::metadata(&metadata).to_event(&keys_a).unwrap();
let event = EventBuilder::metadata(&metadata)
.sign_with_keys(&keys_a)
.unwrap();
database.save_event(&event).await.unwrap();
}

Expand All @@ -59,7 +61,7 @@ async fn main() {
"Custom with d tag",
[Tag::identifier(format!("myid{i}"))],
)
.to_event(&keys_a)
.sign_with_keys(&keys_a)
.unwrap();
database.save_event(&event).await.unwrap();
}
Expand Down
16 changes: 8 additions & 8 deletions crates/nostr-lmdb/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,12 +212,12 @@ mod tests {
// Add some text notes
events.push(
EventBuilder::text_note("Text Note A", [])
.to_event(&keys_a)
.sign_with_keys(&keys_a)
.unwrap(),
);
events.push(
EventBuilder::text_note("Text Note B", [])
.to_event(&keys_b)
.sign_with_keys(&keys_b)
.unwrap(),
);

Expand All @@ -226,14 +226,14 @@ mod tests {
EventBuilder::metadata(
&Metadata::new().name("account-a").display_name("Account A"),
)
.to_event(&keys_a)
.sign_with_keys(&keys_a)
.unwrap(),
);
events.push(
EventBuilder::metadata(
&Metadata::new().name("account-b").display_name("Account B"),
)
.to_event(&keys_b)
.sign_with_keys(&keys_b)
.unwrap(),
);

Expand All @@ -244,7 +244,7 @@ mod tests {
"",
[Tag::identifier("my-id-a")],
)
.to_event(&keys_a)
.sign_with_keys(&keys_a)
.unwrap(),
);
events.push(
Expand All @@ -253,7 +253,7 @@ mod tests {
"",
[Tag::identifier("my-id-b")],
)
.to_event(&keys_b)
.sign_with_keys(&keys_b)
.unwrap(),
);

Expand All @@ -267,13 +267,13 @@ mod tests {

async fn add_event(&self, builder: EventBuilder) -> (Keys, Event) {
let keys = Keys::generate();
let event = builder.to_event(&keys).unwrap();
let event = builder.sign_with_keys(&keys).unwrap();
self.db.save_event(&event).await.unwrap();
(keys, event)
}

async fn add_event_with_keys(&self, builder: EventBuilder, keys: &Keys) -> (Event, bool) {
let event = builder.to_event(&keys).unwrap();
let event = builder.sign_with_keys(&keys).unwrap();
let stored = self.db.save_event(&event).await.unwrap();
(event, stored)
}
Expand Down
11 changes: 5 additions & 6 deletions crates/nostr-sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,13 @@ use nostr_sdk::prelude::*;
#[tokio::main]
async fn main() -> Result<()> {
// Generate new random keys
let my_keys = Keys::generate();
let keys = Keys::generate();
// Or use your already existing (from hex or bech32)
let my_keys = Keys::parse("hex-or-bech32-secret-key")?;
let keys = Keys::parse("hex-or-bech32-secret-key")?;
// Show bech32 public key
let bech32_pubkey: String = my_keys.public_key().to_bech32()?;
let bech32_pubkey: String = keys.public_key().to_bech32()?;
println!("Bech32 PubKey: {}", bech32_pubkey);
// Configure client to use proxy for `.onion` relays
Expand All @@ -45,7 +45,7 @@ async fn main() -> Result<()> {
// Create new client with custom options.
// Use `Client::new(signer)` to construct the client with a custom signer and default options
// or `Client::default()` to create one without signer and with default options.
let client = Client::with_opts(&my_keys, opts);
let client = Client::with_opts(keys.clone(), opts);
// Add relays
client.add_relay("wss://relay.damus.io").await?;
Expand Down Expand Up @@ -74,7 +74,7 @@ async fn main() -> Result<()> {
client.publish_text_note("My first text note from rust-nostr!", []).await?;
// Create a POW text note
let event: Event = EventBuilder::text_note("POW text note from nostr-sdk", []).pow(20).to_event(&my_keys)?;
let event: Event = EventBuilder::text_note("POW text note from nostr-sdk", []).pow(20).sign(&keys).await?;
client.send_event(event).await?; // Send to all relays
// client.send_event_to(["wss://relay.damus.io"], event).await?; // Send to specific relay
Expand Down Expand Up @@ -141,7 +141,6 @@ The following crate feature flags are available:
| `nip07` | Yes | Enable NIP-07: `window.nostr` capability for web browsers (**available only for `wasm32`!**) |
| `nip11` | Yes | Enable NIP-11: Relay Information Document |
| `nip44` | Yes | Enable NIP-44: Encrypted Payloads (Versioned) |
| `nip46` | Yes | Enable NIP-46: Nostr Connect |
| `nip47` | Yes | Enable NIP-47: Nostr Wallet Connect |
| `nip49` | Yes | Enable NIP-49: Private Key Encryption |
| `nip57` | Yes | Enable NIP-57: Zaps |
Expand Down
7 changes: 2 additions & 5 deletions crates/nostr-sdk/examples/bot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,16 @@ use std::time::Duration;

use nostr_sdk::prelude::*;

const BECH32_SK: &str = "nsec12kcgs78l06p30jz7z7h3n2x2cy99nw2z6zspjdp7qc206887mwvs95lnkx";

#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();

let secret_key = SecretKey::from_bech32(BECH32_SK)?;
let keys = Keys::new(secret_key);
let keys = Keys::parse("nsec12kcgs78l06p30jz7z7h3n2x2cy99nw2z6zspjdp7qc206887mwvs95lnkx")?;
let opts = Options::new()
.skip_disconnected_relays(true)
.connection_timeout(Some(Duration::from_secs(10)))
.send_timeout(Some(Duration::from_secs(5)));
let client = Client::with_opts(&keys, opts);
let client = Client::with_opts(keys.clone(), opts);

println!("Bot public key: {}", keys.public_key().to_bech32()?);

Expand Down
8 changes: 3 additions & 5 deletions crates/nostr-sdk/examples/client-with-opts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,22 +6,20 @@ use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};

use nostr_sdk::prelude::*;

const BECH32_SK: &str = "nsec1ufnus6pju578ste3v90xd5m2decpuzpql2295m3sknqcjzyys9ls0qlc85";

#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();

// Parse keys
let my_keys = Keys::parse(BECH32_SK)?;
let keys = Keys::parse("nsec1ufnus6pju578ste3v90xd5m2decpuzpql2295m3sknqcjzyys9ls0qlc85")?;

// Configure client to use proxy for `.onion` relays
let addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 9050));
let connection = Connection::new()
.proxy(addr)
.target(ConnectionTarget::Onion);
let opts = Options::new().connection(connection);
let client = Client::with_opts(&my_keys, opts);
let client = Client::with_opts(keys.clone(), opts);

// Add relays
client.add_relay("wss://relay.damus.io").await?;
Expand All @@ -37,7 +35,7 @@ async fn main() -> Result<()> {

client.connect().await;

let subscription = Filter::new().pubkey(my_keys.public_key()).limit(0);
let subscription = Filter::new().pubkey(keys.public_key()).limit(0);

client.subscribe(vec![subscription], None).await?;

Expand Down
29 changes: 7 additions & 22 deletions crates/nostr-sdk/examples/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,13 @@

use nostr_sdk::prelude::*;

const BECH32_SK: &str = "nsec1ufnus6pju578ste3v90xd5m2decpuzpql2295m3sknqcjzyys9ls0qlc85";

#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();

let secret_key = SecretKey::from_bech32(BECH32_SK)?;
let my_keys = Keys::new(secret_key);
let keys = Keys::parse("nsec1ufnus6pju578ste3v90xd5m2decpuzpql2295m3sknqcjzyys9ls0qlc85")?;
let client = Client::new(keys);

let client = Client::new(&my_keys);
client.add_relay("wss://relay.damus.io").await?;
client.add_relay("wss://nostr.wine").await?;
client.add_relay("wss://relay.rip").await?;
Expand All @@ -26,26 +23,14 @@ async fn main() -> Result<()> {
println!("Sent to: {:?}", output.success);
println!("Not sent to: {:?}", output.failed);

// Create a text note POW event and broadcast to all connected relays
let event: Event = EventBuilder::text_note("POW text note from rust-nostr", [])
.pow(20)
.to_event(&my_keys)?;
client.send_event(event).await?;

// Send multiple events at once (to all relays)
let mut events: Vec<Event> = Vec::new();
for i in 0..10 {
events.push(EventBuilder::text_note(format!("Event #{i}"), []).to_event(&my_keys)?);
}
let opts = RelaySendOptions::default();
client.batch_event(events, opts).await?;
// Create a text note POW event and broadcast to relays
let builder = EventBuilder::text_note("POW text note from rust-nostr", []).pow(20);
client.send_event_builder(builder).await?;

// Send event to specific relays
let event: Event = EventBuilder::text_note("POW text note from rust-nostr 16", [])
.pow(16)
.to_event(&my_keys)?;
let builder = EventBuilder::text_note("POW text note from rust-nostr 16", []).pow(16);
client
.send_event_to(["wss://relay.damus.io", "wss://relay.rip"], event)
.send_event_builder_to(["wss://relay.damus.io", "wss://relay.rip"], builder)
.await?;

Ok(())
Expand Down
2 changes: 1 addition & 1 deletion crates/nostr-sdk/examples/gossip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ async fn main() -> Result<()> {
let my_keys = Keys::parse(BECH32_SK)?;

let opts = Options::new().gossip(true);
let client = Client::with_opts(&my_keys, opts);
let client = Client::with_opts(my_keys, opts);

client.add_discovery_relay("wss://relay.damus.io").await?;
client.add_discovery_relay("wss://purplepag.es").await?;
Expand Down
8 changes: 4 additions & 4 deletions crates/nostr-sdk/examples/lmdb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ use nostr_sdk::prelude::*;
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();

let my_keys = Keys::parse("nsec1ufnus6pju578ste3v90xd5m2decpuzpql2295m3sknqcjzyys9ls0qlc85")?;
let keys = Keys::parse("nsec1ufnus6pju578ste3v90xd5m2decpuzpql2295m3sknqcjzyys9ls0qlc85")?;

let database = NostrLMDB::open("./db/nostr-lmdb")?;
let client: Client = ClientBuilder::default()
.signer(&my_keys)
.signer(keys.clone())
.database(database)
.build();

Expand All @@ -26,7 +26,7 @@ async fn main() -> Result<()> {
client.publish_text_note("Hello world", []).await?;

// Negentropy reconcile
let filter = Filter::new().author(my_keys.public_key());
let filter = Filter::new().author(keys.public_key());
let output = client
.reconcile(
filter,
Expand All @@ -47,7 +47,7 @@ async fn main() -> Result<()> {
}

// Query events from database
let filter = Filter::new().author(my_keys.public_key()).limit(10);
let filter = Filter::new().author(keys.public_key()).limit(10);
let events = client.database().query(vec![filter]).await?;
println!("Events: {events:?}");

Expand Down
8 changes: 4 additions & 4 deletions crates/nostr-sdk/examples/nostrdb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ const BECH32_SK: &str = "nsec1ufnus6pju578ste3v90xd5m2decpuzpql2295m3sknqcjzyys9
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();

let my_keys = Keys::parse(BECH32_SK)?;
let keys = Keys::parse(BECH32_SK)?;

let database = NdbDatabase::open("./db/ndb")?;
let client: Client = Client::builder()
.signer(&my_keys)
.signer(keys.clone())
.database(database)
.build();

Expand All @@ -26,13 +26,13 @@ async fn main() -> Result<()> {
client.publish_text_note("Hello world", []).await?;

// Negentropy reconcile
let filter = Filter::new().author(my_keys.public_key());
let filter = Filter::new().author(keys.public_key());
client
.reconcile(filter, NegentropyOptions::default())
.await?;

// Query events from database
let filter = Filter::new().author(my_keys.public_key()).limit(10);
let filter = Filter::new().author(keys.public_key()).limit(10);
let events = client.database().query(vec![filter]).await?;
println!("Events: {events:?}");

Expand Down
Loading

0 comments on commit 924b722

Please sign in to comment.