From ee655f31231ecf97f05aee9c9f5ae9abfbf1f2a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Szil=C3=A1rd=20Parrag?= Date: Thu, 23 Mar 2023 13:30:42 +0000 Subject: [PATCH 01/77] nostr: add std feature --- crates/nostr/Cargo.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml index e6ca33221..ef6edb53b 100644 --- a/crates/nostr/Cargo.toml +++ b/crates/nostr/Cargo.toml @@ -12,7 +12,8 @@ rust-version.workspace = true keywords = ["nostr", "protocol", "sdk"] [features] -default = ["all-nips"] +default = ["all-nips", "std"] +std = [] blocking = ["reqwest?/blocking"] vanity = ["nip19"] all-nips = ["nip04", "nip05", "nip06", "nip11", "nip19", "nip21", "nip46"] From 598f99b36a817dd4bab63823d4eb85b4152b09bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Szil=C3=A1rd=20Parrag?= Date: Thu, 23 Mar 2023 14:01:12 +0000 Subject: [PATCH 02/77] nostr: use thiserror-core with alloc feature --- crates/nostr/Cargo.toml | 3 ++- crates/nostr/src/lib.rs | 9 ++++++++- crates/nostr/src/types/metadata.rs | 2 ++ crates/nostr/src/types/profile.rs | 2 ++ 4 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml index ef6edb53b..d3d0ae78e 100644 --- a/crates/nostr/Cargo.toml +++ b/crates/nostr/Cargo.toml @@ -13,7 +13,8 @@ keywords = ["nostr", "protocol", "sdk"] [features] default = ["all-nips", "std"] -std = [] +std = ["dep:thiserror"] +alloc = ["dep:thiserror-core"] blocking = ["reqwest?/blocking"] vanity = ["nip19"] all-nips = ["nip04", "nip05", "nip06", "nip11", "nip19", "nip21", "nip46"] diff --git a/crates/nostr/src/lib.rs b/crates/nostr/src/lib.rs index c48e752c9..c9e581bf9 100644 --- a/crates/nostr/src/lib.rs +++ b/crates/nostr/src/lib.rs @@ -1,6 +1,13 @@ // Copyright (c) 2022-2023 Yuki Kishimoto // Distributed under the MIT software license +#![cfg_attr(not(feature = "std"), no_std)] + +#[cfg(not(feature = "debug"))] +extern crate alloc; + + + #![warn(missing_docs)] #![warn(rustdoc::bare_urls)] @@ -35,4 +42,4 @@ pub use self::message::{ClientMessage, Filter, RelayMessage, SubscriptionId}; pub use self::types::{ChannelId, Contact, Entity, Metadata, Profile, Timestamp, UncheckedUrl}; /// Result -pub type Result> = std::result::Result; +pub type Result> = std::result::Result; diff --git a/crates/nostr/src/types/metadata.rs b/crates/nostr/src/types/metadata.rs index 0fc0d404d..f25f368c1 100644 --- a/crates/nostr/src/types/metadata.rs +++ b/crates/nostr/src/types/metadata.rs @@ -8,6 +8,8 @@ use core::fmt; use serde::{Deserialize, Serialize}; use url::Url; +use alloc::string::String; + /// [`Metadata`] error #[derive(Debug)] pub enum Error { diff --git a/crates/nostr/src/types/profile.rs b/crates/nostr/src/types/profile.rs index f1bc171d8..ccfc17b4b 100644 --- a/crates/nostr/src/types/profile.rs +++ b/crates/nostr/src/types/profile.rs @@ -10,6 +10,8 @@ use serde::{Deserialize, Serialize}; #[cfg(feature = "nip19")] use crate::nips::nip19::{Error, FromBech32, ToBech32, PREFIX_BECH32_PROFILE, RELAY, SPECIAL}; +use alloc::vec::Vec; +use alloc::string::String; /// Profile #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] From 23ce7a0ba2ab0139da2843f67de1460b508bf511 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Szil=C3=A1rd=20Parrag?= Date: Thu, 23 Mar 2023 15:20:44 +0000 Subject: [PATCH 03/77] nostr: make time module `no_std` compatible --- crates/nostr/src/lib.rs | 3 +++ crates/nostr/src/message/subscription.rs | 1 + crates/nostr/src/types/time.rs | 21 +++++++++++++-------- 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/crates/nostr/src/lib.rs b/crates/nostr/src/lib.rs index c9e581bf9..35cb071fb 100644 --- a/crates/nostr/src/lib.rs +++ b/crates/nostr/src/lib.rs @@ -18,6 +18,9 @@ extern crate alloc; doc = include_str!("../README.md") )] +#[macro_use] +pub extern crate serde; + #[cfg(feature = "nip19")] pub use bech32; #[cfg(feature = "nip06")] diff --git a/crates/nostr/src/message/subscription.rs b/crates/nostr/src/message/subscription.rs index f86c6e12b..1e61fa5f9 100644 --- a/crates/nostr/src/message/subscription.rs +++ b/crates/nostr/src/message/subscription.rs @@ -4,6 +4,7 @@ //! Subscription filters +#![allow(missing_docs)] use core::fmt; use bitcoin_hashes::sha256::Hash as Sha256Hash; diff --git a/crates/nostr/src/types/time.rs b/crates/nostr/src/types/time.rs index 008160008..83218292b 100644 --- a/crates/nostr/src/types/time.rs +++ b/crates/nostr/src/types/time.rs @@ -3,15 +3,15 @@ //! Time -use std::fmt; +use core::time::Duration; +use core::ops::{Add, Sub}; +use core::str::FromStr; -use std::time::Duration; -#[cfg(not(target_arch = "wasm32"))] -use std::time::{SystemTime, UNIX_EPOCH}; -use std::{ - ops::{Add, Sub}, - str::FromStr, -}; +#[cfg(feature = "std")] +use std::{fmt, time::{SystemTime, UNIX_EPOCH}}; + +#[cfg(feature = "alloc")] +use alloc::{fmt, vec::Vec, string::String}; #[cfg(target_arch = "wasm32")] use instant::SystemTime; @@ -25,6 +25,7 @@ const UNIX_EPOCH: SystemTime = SystemTime::UNIX_EPOCH; pub struct Timestamp(i64); impl Timestamp { + #[cfg(not(feature = "alloc"))] /// Get UNIX timestamp pub fn now() -> Self { let ts: u64 = SystemTime::now() @@ -33,6 +34,10 @@ impl Timestamp { .as_secs(); Self(ts as i64) } + #[cfg(feature = "alloc")] + pub fn from_secs(external_time_stamp: u64) -> Self { + Self(external_time_stamp) + } /// Get timestamp as [`u64`] pub fn as_u64(&self) -> u64 { From c0182137c6bd4186dd9d5087e84730cba1886305 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Szil=C3=A1rd=20Parrag?= Date: Thu, 23 Mar 2023 15:24:47 +0000 Subject: [PATCH 04/77] nostr: make nostr crate no_std compatible This reverts commit 77ef1c8432b1c67971d88ccbb2fbc2799cc160ed. --- crates/nostr/src/event/tag.rs | 2 ++ crates/nostr/src/lib.rs | 14 +++++++++----- crates/nostr/src/message/client.rs | 3 +++ crates/nostr/src/message/relay.rs | 3 +++ crates/nostr/src/message/subscription.rs | 3 +++ crates/nostr/src/types/channel_id.rs | 2 ++ crates/nostr/src/types/contact.rs | 3 +++ crates/nostr/src/types/metadata.rs | 1 + crates/nostr/src/types/profile.rs | 5 +++-- 9 files changed, 29 insertions(+), 7 deletions(-) diff --git a/crates/nostr/src/event/tag.rs b/crates/nostr/src/event/tag.rs index 15a94324e..c3223f8aa 100644 --- a/crates/nostr/src/event/tag.rs +++ b/crates/nostr/src/event/tag.rs @@ -6,6 +6,8 @@ use core::fmt; use core::num::ParseIntError; use core::str::FromStr; +#[cfg(feature = "alloc")] +use alloc::{vec::Vec, string::String}; use secp256k1::schnorr::Signature; use secp256k1::XOnlyPublicKey; diff --git a/crates/nostr/src/lib.rs b/crates/nostr/src/lib.rs index 35cb071fb..2873af811 100644 --- a/crates/nostr/src/lib.rs +++ b/crates/nostr/src/lib.rs @@ -1,10 +1,6 @@ // Copyright (c) 2022-2023 Yuki Kishimoto // Distributed under the MIT software license -#![cfg_attr(not(feature = "std"), no_std)] - -#[cfg(not(feature = "debug"))] -extern crate alloc; @@ -18,6 +14,14 @@ extern crate alloc; doc = include_str!("../README.md") )] +#![cfg_attr(not(feature = "std"), no_std)] + +#[cfg(feature = "alloc")] +extern crate alloc; + +#[cfg(feature = "alloc")] +use alloc::boxed::Box; + #[macro_use] pub extern crate serde; @@ -45,4 +49,4 @@ pub use self::message::{ClientMessage, Filter, RelayMessage, SubscriptionId}; pub use self::types::{ChannelId, Contact, Entity, Metadata, Profile, Timestamp, UncheckedUrl}; /// Result -pub type Result> = std::result::Result; +pub type Result> = std::result::Result; diff --git a/crates/nostr/src/message/client.rs b/crates/nostr/src/message/client.rs index 06d32e4ff..f8597af22 100644 --- a/crates/nostr/src/message/client.rs +++ b/crates/nostr/src/message/client.rs @@ -4,6 +4,9 @@ //! Client messages +#[cfg(feature = "alloc")] +use alloc::{string::String, vec, vec::Vec}; + use serde::de::Error; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_json::{json, Value}; diff --git a/crates/nostr/src/message/relay.rs b/crates/nostr/src/message/relay.rs index 903ec8292..8b5ff4d14 100644 --- a/crates/nostr/src/message/relay.rs +++ b/crates/nostr/src/message/relay.rs @@ -4,6 +4,9 @@ //! Relay messages +#[cfg(feature = "alloc")] +use alloc::string::String; + use serde::de::Error; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde_json::{json, Value}; diff --git a/crates/nostr/src/message/subscription.rs b/crates/nostr/src/message/subscription.rs index 1e61fa5f9..8c1915da7 100644 --- a/crates/nostr/src/message/subscription.rs +++ b/crates/nostr/src/message/subscription.rs @@ -7,6 +7,9 @@ #![allow(missing_docs)] use core::fmt; +#[cfg(feature = "alloc")] +use alloc::{fmt, string::String, vec::Vec}; + use bitcoin_hashes::sha256::Hash as Sha256Hash; use bitcoin_hashes::Hash; use secp256k1::rand::rngs::OsRng; diff --git a/crates/nostr/src/types/channel_id.rs b/crates/nostr/src/types/channel_id.rs index a3cf1036a..33ea4573c 100644 --- a/crates/nostr/src/types/channel_id.rs +++ b/crates/nostr/src/types/channel_id.rs @@ -5,6 +5,8 @@ use core::fmt; use core::str::FromStr; +#[cfg(feature = "alloc")] +use alloc::{vec::Vec, string::String}; #[cfg(feature = "nip19")] use bech32::{self, FromBase32, ToBase32, Variant}; diff --git a/crates/nostr/src/types/contact.rs b/crates/nostr/src/types/contact.rs index ea3432698..151a2ab4a 100644 --- a/crates/nostr/src/types/contact.rs +++ b/crates/nostr/src/types/contact.rs @@ -3,6 +3,9 @@ //! Contact +#[cfg(feature = "alloc")] +use alloc::string::String; + use secp256k1::XOnlyPublicKey; use serde::{Deserialize, Serialize}; diff --git a/crates/nostr/src/types/metadata.rs b/crates/nostr/src/types/metadata.rs index f25f368c1..32ee64c56 100644 --- a/crates/nostr/src/types/metadata.rs +++ b/crates/nostr/src/types/metadata.rs @@ -8,6 +8,7 @@ use core::fmt; use serde::{Deserialize, Serialize}; use url::Url; +#[cfg(feature = "alloc")] use alloc::string::String; /// [`Metadata`] error diff --git a/crates/nostr/src/types/profile.rs b/crates/nostr/src/types/profile.rs index ccfc17b4b..79188e651 100644 --- a/crates/nostr/src/types/profile.rs +++ b/crates/nostr/src/types/profile.rs @@ -10,8 +10,9 @@ use serde::{Deserialize, Serialize}; #[cfg(feature = "nip19")] use crate::nips::nip19::{Error, FromBech32, ToBech32, PREFIX_BECH32_PROFILE, RELAY, SPECIAL}; -use alloc::vec::Vec; -use alloc::string::String; + +#[cfg(feature = "alloc")] +use alloc::{string::String, vec::Vec}; /// Profile #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] From 20cffbf9a5fac87bcb715039c634c69c3ca34a44 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 24 Mar 2023 12:56:08 +0100 Subject: [PATCH 05/77] nostr: no_std support --- crates/nostr/src/event/builder.rs | 14 ++++++++++---- crates/nostr/src/event/id.rs | 6 ++++++ crates/nostr/src/event/mod.rs | 5 +++++ crates/nostr/src/event/tag.rs | 6 +++++- crates/nostr/src/event/unsigned.rs | 2 ++ crates/nostr/src/lib.rs | 8 +++++++- crates/nostr/src/message/client.rs | 2 +- crates/nostr/src/message/relay.rs | 2 +- crates/nostr/src/message/subscription.rs | 7 ++++++- crates/nostr/src/types/channel_id.rs | 5 ++++- crates/nostr/src/types/metadata.rs | 2 +- crates/nostr/src/types/time.rs | 8 +++++--- 12 files changed, 53 insertions(+), 14 deletions(-) diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index 80d396f5b..075ba8e4b 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -2,6 +2,8 @@ // Distributed under the MIT software license //! Event builder +#[cfg(feature = "alloc")] +use alloc::{string::{String, ToString}, vec::Vec}; use core::fmt; #[cfg(not(target_arch = "wasm32"))] @@ -129,9 +131,13 @@ impl EventBuilder { /// Build POW [`Event`] pub fn to_pow_event(self, keys: &Keys, difficulty: u8) -> Result { - let pubkey: XOnlyPublicKey = keys.public_key(); - Ok(self.to_unsigned_pow_event(pubkey, difficulty).sign(keys)?) - } + #[cfg(target_arch = "wasm32")] + use instant::Instant; + #[cfg(all(not(target_arch = "wasm32"), feature = "std"))] + use std::{cmp, time::Instant}; + + #[cfg(feature = "alloc")] + use core::cmp; /// Build unsigned POW [`Event`] pub fn to_unsigned_pow_event(self, pubkey: XOnlyPublicKey, difficulty: u8) -> UnsignedEvent { @@ -153,7 +159,7 @@ impl EventBuilder { "{} iterations in {} ms. Avg rate {} hashes/second", nonce, now.elapsed().as_millis(), - nonce * 1000 / std::cmp::max(1, now.elapsed().as_millis()) + nonce * 1000 / cmp::max(1, now.elapsed().as_millis()) ); return UnsignedEvent { diff --git a/crates/nostr/src/event/id.rs b/crates/nostr/src/event/id.rs index 1af00562c..793e828a6 100644 --- a/crates/nostr/src/event/id.rs +++ b/crates/nostr/src/event/id.rs @@ -6,6 +6,12 @@ use core::fmt; use core::str::FromStr; +#[cfg(feature = "alloc")] +use alloc::string::{String, ToString}; +#[cfg(feature = "alloc")] +use alloc::vec; + + use bitcoin_hashes::sha256::Hash as Sha256Hash; use bitcoin_hashes::Hash; use secp256k1::XOnlyPublicKey; diff --git a/crates/nostr/src/event/mod.rs b/crates/nostr/src/event/mod.rs index 119d0616d..d889d313f 100644 --- a/crates/nostr/src/event/mod.rs +++ b/crates/nostr/src/event/mod.rs @@ -7,6 +7,11 @@ use core::fmt; use core::str::FromStr; +#[cfg(feature = "alloc")] +use alloc::{string::{String, ToString}; +#[cfg(feature = "alloc")] +use alloc::vec::Vec; + use secp256k1::schnorr::Signature; use secp256k1::{Message, XOnlyPublicKey}; use serde::{Deserialize, Serialize}; diff --git a/crates/nostr/src/event/tag.rs b/crates/nostr/src/event/tag.rs index c3223f8aa..220c0a66b 100644 --- a/crates/nostr/src/event/tag.rs +++ b/crates/nostr/src/event/tag.rs @@ -7,7 +7,11 @@ use core::fmt; use core::num::ParseIntError; use core::str::FromStr; #[cfg(feature = "alloc")] -use alloc::{vec::Vec, string::String}; +use alloc::string::{String, ToString}; +#[cfg(feature = "alloc")] +use alloc::{vec, vec::Vec}; +#[cfg(feature = "alloc")] +use alloc::format; use secp256k1::schnorr::Signature; use secp256k1::XOnlyPublicKey; diff --git a/crates/nostr/src/event/unsigned.rs b/crates/nostr/src/event/unsigned.rs index fb3996292..e3e3b532a 100644 --- a/crates/nostr/src/event/unsigned.rs +++ b/crates/nostr/src/event/unsigned.rs @@ -4,6 +4,8 @@ //! Unsigned Event use core::fmt; +#[cfg(feature = "alloc")] +use alloc::{string::{String, ToString}, vec::Vec}; use secp256k1::schnorr::Signature; use secp256k1::{Message, XOnlyPublicKey}; diff --git a/crates/nostr/src/lib.rs b/crates/nostr/src/lib.rs index 2873af811..d6922f163 100644 --- a/crates/nostr/src/lib.rs +++ b/crates/nostr/src/lib.rs @@ -3,6 +3,7 @@ +#![cfg_attr(not(feature = "std"), feature(error_in_core))] #![warn(missing_docs)] #![warn(rustdoc::bare_urls)] @@ -15,10 +16,12 @@ )] #![cfg_attr(not(feature = "std"), no_std)] - #[cfg(feature = "alloc")] extern crate alloc; +#[cfg(feature = "alloc")] +extern crate thiserror_core as thiserror; + #[cfg(feature = "alloc")] use alloc::boxed::Box; @@ -49,4 +52,7 @@ pub use self::message::{ClientMessage, Filter, RelayMessage, SubscriptionId}; pub use self::types::{ChannelId, Contact, Entity, Metadata, Profile, Timestamp, UncheckedUrl}; /// Result +#[cfg(feature = "std")] pub type Result> = std::result::Result; +#[cfg(feature = "alloc")] +pub type Result> = core::result::Result; diff --git a/crates/nostr/src/message/client.rs b/crates/nostr/src/message/client.rs index f8597af22..2f58650b1 100644 --- a/crates/nostr/src/message/client.rs +++ b/crates/nostr/src/message/client.rs @@ -5,7 +5,7 @@ //! Client messages #[cfg(feature = "alloc")] -use alloc::{string::String, vec, vec::Vec}; +use alloc::{boxed::Box, string::{String, ToString}, vec, vec::Vec}; use serde::de::Error; use serde::{Deserialize, Deserializer, Serialize, Serializer}; diff --git a/crates/nostr/src/message/relay.rs b/crates/nostr/src/message/relay.rs index 8b5ff4d14..d822c568f 100644 --- a/crates/nostr/src/message/relay.rs +++ b/crates/nostr/src/message/relay.rs @@ -5,7 +5,7 @@ //! Relay messages #[cfg(feature = "alloc")] -use alloc::string::String; +use alloc::{boxed::Box, string::{String, ToString}, vec}; use serde::de::Error; use serde::{Deserialize, Deserializer, Serialize, Serializer}; diff --git a/crates/nostr/src/message/subscription.rs b/crates/nostr/src/message/subscription.rs index 8c1915da7..7f86bbc1c 100644 --- a/crates/nostr/src/message/subscription.rs +++ b/crates/nostr/src/message/subscription.rs @@ -8,7 +8,12 @@ use core::fmt; #[cfg(feature = "alloc")] -use alloc::{fmt, string::String, vec::Vec}; +use alloc::{ + fmt, + string::{String, ToString}, + vec, + vec::Vec, +}; use bitcoin_hashes::sha256::Hash as Sha256Hash; use bitcoin_hashes::Hash; diff --git a/crates/nostr/src/types/channel_id.rs b/crates/nostr/src/types/channel_id.rs index 33ea4573c..d4dcc87f7 100644 --- a/crates/nostr/src/types/channel_id.rs +++ b/crates/nostr/src/types/channel_id.rs @@ -5,8 +5,11 @@ use core::fmt; use core::str::FromStr; + +#[cfg(feature = "alloc")] +use alloc::string::{String, ToString}; #[cfg(feature = "alloc")] -use alloc::{vec::Vec, string::String}; +use alloc::{vec::Vec}; #[cfg(feature = "nip19")] use bech32::{self, FromBase32, ToBase32, Variant}; diff --git a/crates/nostr/src/types/metadata.rs b/crates/nostr/src/types/metadata.rs index 32ee64c56..266886290 100644 --- a/crates/nostr/src/types/metadata.rs +++ b/crates/nostr/src/types/metadata.rs @@ -9,7 +9,7 @@ use serde::{Deserialize, Serialize}; use url::Url; #[cfg(feature = "alloc")] -use alloc::string::String; +use alloc::string::{String, ToString}; /// [`Metadata`] error #[derive(Debug)] diff --git a/crates/nostr/src/types/time.rs b/crates/nostr/src/types/time.rs index 83218292b..aefda6d37 100644 --- a/crates/nostr/src/types/time.rs +++ b/crates/nostr/src/types/time.rs @@ -8,10 +8,12 @@ use core::ops::{Add, Sub}; use core::str::FromStr; #[cfg(feature = "std")] -use std::{fmt, time::{SystemTime, UNIX_EPOCH}}; +use std::{fmt, num, time::{SystemTime, UNIX_EPOCH}}; #[cfg(feature = "alloc")] -use alloc::{fmt, vec::Vec, string::String}; +use alloc::fmt; +#[cfg(feature = "alloc")] +use core::num; #[cfg(target_arch = "wasm32")] use instant::SystemTime; @@ -144,7 +146,7 @@ impl From for Timestamp { } impl FromStr for Timestamp { - type Err = std::num::ParseIntError; + type Err = num::ParseIntError; fn from_str(s: &str) -> Result { Ok(Self(s.parse::()?)) } From 1380fe918c13970a10f911530ac5a951b5b407a4 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 24 Mar 2023 13:31:04 +0100 Subject: [PATCH 06/77] nostr: port nip26 --- crates/nostr/src/nips/nip26.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/nostr/src/nips/nip26.rs b/crates/nostr/src/nips/nip26.rs index 192a046b0..5f669f232 100644 --- a/crates/nostr/src/nips/nip26.rs +++ b/crates/nostr/src/nips/nip26.rs @@ -9,6 +9,14 @@ use core::fmt; use core::num::ParseIntError; use core::str::FromStr; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::string::{String, ToString}; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::format; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::{vec, vec::Vec}; + + use bitcoin_hashes::sha256::Hash as Sha256Hash; use bitcoin_hashes::Hash; use secp256k1::schnorr::Signature; From 2d4d69006508563f8729adb282264a5ff4b6bfaf Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 24 Mar 2023 13:38:15 +0100 Subject: [PATCH 07/77] nostr: port nip13 --- crates/nostr/src/nips/nip13.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/nostr/src/nips/nip13.rs b/crates/nostr/src/nips/nip13.rs index a4760ac25..b67da095b 100644 --- a/crates/nostr/src/nips/nip13.rs +++ b/crates/nostr/src/nips/nip13.rs @@ -6,6 +6,13 @@ //! //! +#[cfg(feature = "alloc")] +use alloc::format; +#[cfg(feature = "alloc")] +use alloc::string::String; +#[cfg(feature = "alloc")] +use alloc::{vec, vec::Vec}; + /// Gets the number of leading zero bits. Result is between 0 and 255. pub fn get_leading_zero_bits(h: T) -> u8 where From d7c64695a100baca2b1851843ea449760de0fbd4 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 24 Mar 2023 13:40:32 +0100 Subject: [PATCH 08/77] nostr: port nip65 --- crates/nostr/src/nips/nip65.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/nostr/src/nips/nip65.rs b/crates/nostr/src/nips/nip65.rs index 8fb2082df..dd6ac76d5 100644 --- a/crates/nostr/src/nips/nip65.rs +++ b/crates/nostr/src/nips/nip65.rs @@ -2,6 +2,11 @@ //! //! +#[cfg(feature = "alloc")] +use alloc::string::String; +#[cfg(feature = "alloc")] +use alloc::vec::Vec; + use crate::Event; /// Extracts the relay info (url, optional read/write flag) from the event From 98374cd34fb717663ef353d11fb704ad666d227c Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 24 Mar 2023 16:22:46 +0100 Subject: [PATCH 09/77] nostr: outsourcing time for no_std --- crates/nostr/src/event/builder.rs | 51 +++++++++++++++++++++++++++---- crates/nostr/src/types/time.rs | 21 ++++++++++--- 2 files changed, 62 insertions(+), 10 deletions(-) diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index 075ba8e4b..c3fbe21d4 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -110,14 +110,21 @@ impl EventBuilder { } /// Build [`Event`] + #[cfg(feature = "std")] pub fn to_event(self, keys: &Keys) -> Result { - let pubkey: XOnlyPublicKey = keys.public_key(); - Ok(self.to_unsigned_event(pubkey).sign(keys)?) + let created_at: Timestamp = Timestamp::now(); + + Self::to_event_internal(self, keys, created_at) } - /// Build [`UnsignedEvent`] - pub fn to_unsigned_event(self, pubkey: XOnlyPublicKey) -> UnsignedEvent { - let created_at: Timestamp = Timestamp::now(); + #[cfg(not(feature = "std"))] + pub fn to_event_with_timestamp(self, keys: &Keys, created_at: Timestamp) -> Result { + Self::to_event_internal(self, keys, created_at) + } + + fn to_event_internal(self, keys: &Keys, created_at: Timestamp) -> Result { + let pubkey: XOnlyPublicKey = keys.public_key(); + let id = EventId::new(&pubkey, created_at, &self.kind, &self.tags, &self.content); UnsignedEvent { id, @@ -130,7 +137,16 @@ impl EventBuilder { } /// Build POW [`Event`] + #[cfg(feature = "std")] pub fn to_pow_event(self, keys: &Keys, difficulty: u8) -> Result { + + } + #[cfg(feature = "std")] + pub fn to_pow_event_with_time_supplier(self, keys: &Keys, difficulty: u8, time_supplier: &impl TimeSupplier) -> Result { + + } + + fn to_pow_event_internal(self, keys: &Keys, difficulty: u8, time_supplier: &impl TimeSupplier) -> Result { #[cfg(target_arch = "wasm32")] use instant::Instant; #[cfg(all(not(target_arch = "wasm32"), feature = "std"))] @@ -175,6 +191,30 @@ impl EventBuilder { tags.pop(); } } + + /// Build [`UnsignedEvent`] + #[cfg(feature = "std")] + pub fn to_unsigned_event(self, pubkey: XOnlyPublicKey) -> UnsignedEvent { + let created_at: Timestamp = Timestamp::now(); + + Self::to_unsigned_event_internal(self, pubkey, created_at) + + pub fn to_unsigned_event_with_timestamp(self, pubkey: XOnlyPublicKey, created_at: Timestamp) -> UnsignedEvent { + Self::to_unsigned_event_internal(self, pubkey, created_at) + } + + fn to_unsigned_event_internal(self, pubkey: XOnlyPublicKey, created_at: Timestamp) -> UnsignedEvent { + let id = EventId::new(&pubkey, created_at, &self.kind, &self.tags, &self.content); + UnsignedEvent { + id, + pubkey, + created_at, + kind: self.kind, + tags: self.tags, + content: self.content, + } + + } } impl EventBuilder { @@ -184,7 +224,6 @@ impl EventBuilder { /// /// # Example /// ```rust,no_run - /// use nostr::url::Url; /// use nostr::{EventBuilder, Metadata}; /// /// let metadata = Metadata::new() diff --git a/crates/nostr/src/types/time.rs b/crates/nostr/src/types/time.rs index aefda6d37..b1dc09707 100644 --- a/crates/nostr/src/types/time.rs +++ b/crates/nostr/src/types/time.rs @@ -22,13 +22,25 @@ use serde::{Deserialize, Serialize}; #[cfg(target_arch = "wasm32")] const UNIX_EPOCH: SystemTime = SystemTime::UNIX_EPOCH; + +/// Helper trait for acquiring time in `no_std` environments. +#[cfg(not(feature = "std"))] +pub trait TimeSupplier { + type Now; + + fn now(&self) -> Self::Now; + fn elapsed_since(&self, since: Self::Now) -> Duration; + + fn as_i64(&self) -> i64; +} + /// Unix timestamp in seconds #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub struct Timestamp(i64); impl Timestamp { - #[cfg(not(feature = "alloc"))] /// Get UNIX timestamp + #[cfg(feature = "std")] pub fn now() -> Self { let ts: u64 = SystemTime::now() .duration_since(UNIX_EPOCH) @@ -36,9 +48,10 @@ impl Timestamp { .as_secs(); Self(ts as i64) } - #[cfg(feature = "alloc")] - pub fn from_secs(external_time_stamp: u64) -> Self { - Self(external_time_stamp) + + #[cfg(not(feature = "std"))] + pub fn now_no_std(time_supplier: &impl TimeSupplier) -> Self { + Self(time_supplier.as_i64()) } /// Get timestamp as [`u64`] From 67cc842574809c3d9049903065d589a54e350348 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Mon, 27 Mar 2023 22:33:55 +0200 Subject: [PATCH 10/77] nostr: implement TimeSupplier trait for std environments --- crates/nostr/Cargo.toml | 5 +- crates/nostr/src/event/builder.rs | 56 +++++++++++++++------ crates/nostr/src/types/time.rs | 81 +++++++++++++++++++++++++++---- 3 files changed, 116 insertions(+), 26 deletions(-) diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml index d3d0ae78e..a7c7c9b85 100644 --- a/crates/nostr/Cargo.toml +++ b/crates/nostr/Cargo.toml @@ -39,13 +39,14 @@ log = "0.4" nostr-ots = { version = "0.2", optional = true } reqwest = { version = "0.11", default-features = false, features = ["json", "rustls-tls-webpki-roots", "socks"], optional = true } secp256k1 = { version = "0.27", features = ["global-context", "rand-std", "serde"] } + serde = { version = "1.0", features = ["derive"] } serde_json = { version = "1.0" } url = { version = "2", features = ["serde"] } -[target.'cfg(target_arch = "wasm32")'.dependencies] +#[target.'cfg(target_arch = "wasm32")'.dependencies] getrandom = { version = "0.2", features = ["js"] } -instant = { version = "0.1", features = [ "wasm-bindgen", "inaccurate" ] } +instant = { version = "0.1", features = ["wasm-bindgen", "inaccurate"] } [dev-dependencies] csv = "1.1.5" diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index c3fbe21d4..9f890a260 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -3,7 +3,10 @@ //! Event builder #[cfg(feature = "alloc")] -use alloc::{string::{String, ToString}, vec::Vec}; +use alloc::{ + string::{String, ToString}, + vec::Vec, +}; use core::fmt; #[cfg(not(target_arch = "wasm32"))] @@ -24,6 +27,7 @@ use crate::nips::nip04; use crate::nips::nip13; #[cfg(feature = "nip46")] use crate::nips::nip46::Message as NostrConnectMessage; +use crate::types::time::TimeSupplier; use crate::types::{ChannelId, Contact, Metadata, Timestamp}; /// [`EventBuilder`] error @@ -118,7 +122,11 @@ impl EventBuilder { } #[cfg(not(feature = "std"))] - pub fn to_event_with_timestamp(self, keys: &Keys, created_at: Timestamp) -> Result { + pub fn to_event_with_timestamp( + self, + keys: &Keys, + created_at: Timestamp, + ) -> Result { Self::to_event_internal(self, keys, created_at) } @@ -138,15 +146,22 @@ impl EventBuilder { /// Build POW [`Event`] #[cfg(feature = "std")] - pub fn to_pow_event(self, keys: &Keys, difficulty: u8) -> Result { - - } + pub fn to_pow_event(self, keys: &Keys, difficulty: u8) -> Result {} #[cfg(feature = "std")] - pub fn to_pow_event_with_time_supplier(self, keys: &Keys, difficulty: u8, time_supplier: &impl TimeSupplier) -> Result { - - } - - fn to_pow_event_internal(self, keys: &Keys, difficulty: u8, time_supplier: &impl TimeSupplier) -> Result { + pub fn to_pow_event_with_time_supplier( + self, + keys: &Keys, + difficulty: u8, + time_supplier: &impl TimeSupplier, + ) -> Result { + } + + fn to_pow_event_internal( + self, + keys: &Keys, + difficulty: u8, + time_supplier: &impl TimeSupplier, + ) -> Result { #[cfg(target_arch = "wasm32")] use instant::Instant; #[cfg(all(not(target_arch = "wasm32"), feature = "std"))] @@ -160,7 +175,10 @@ impl EventBuilder { let mut nonce: u128 = 0; let mut tags: Vec = self.tags; - let now = Instant::now(); + let pubkey = keys.public_key(); + + //let now = Instant::now(); + let now = time_supplier.now(); loop { nonce += 1; @@ -198,12 +216,21 @@ impl EventBuilder { let created_at: Timestamp = Timestamp::now(); Self::to_unsigned_event_internal(self, pubkey, created_at) - - pub fn to_unsigned_event_with_timestamp(self, pubkey: XOnlyPublicKey, created_at: Timestamp) -> UnsignedEvent { + } + #[cfg(not(feature = "std"))] + pub fn to_unsigned_event_with_timestamp( + self, + pubkey: XOnlyPublicKey, + created_at: Timestamp, + ) -> UnsignedEvent { Self::to_unsigned_event_internal(self, pubkey, created_at) } - fn to_unsigned_event_internal(self, pubkey: XOnlyPublicKey, created_at: Timestamp) -> UnsignedEvent { + fn to_unsigned_event_internal( + self, + pubkey: XOnlyPublicKey, + created_at: Timestamp, + ) -> UnsignedEvent { let id = EventId::new(&pubkey, created_at, &self.kind, &self.tags, &self.content); UnsignedEvent { id, @@ -213,7 +240,6 @@ impl EventBuilder { tags: self.tags, content: self.content, } - } } diff --git a/crates/nostr/src/types/time.rs b/crates/nostr/src/types/time.rs index b1dc09707..e4caf714e 100644 --- a/crates/nostr/src/types/time.rs +++ b/crates/nostr/src/types/time.rs @@ -3,12 +3,15 @@ //! Time -use core::time::Duration; use core::ops::{Add, Sub}; use core::str::FromStr; +use core::time::Duration; #[cfg(feature = "std")] -use std::{fmt, num, time::{SystemTime, UNIX_EPOCH}}; +use std::{ + fmt, num, + time::{SystemTime, UNIX_EPOCH}, +}; #[cfg(feature = "alloc")] use alloc::fmt; @@ -22,16 +25,69 @@ use serde::{Deserialize, Serialize}; #[cfg(target_arch = "wasm32")] const UNIX_EPOCH: SystemTime = SystemTime::UNIX_EPOCH; - /// Helper trait for acquiring time in `no_std` environments. -#[cfg(not(feature = "std"))] pub trait TimeSupplier { type Now; + type StartingPoint; fn now(&self) -> Self::Now; - fn elapsed_since(&self, since: Self::Now) -> Duration; + fn starting_point(&self) -> Self::StartingPoint; + fn elapsed_since(now: Self::Now, since: Self::Now) -> Duration; + fn elapsed_duration(now: Self::Now, since: Self::StartingPoint) -> Duration; + + fn as_i64(duration: Duration) -> i64; + fn to_timestamp(duration: Duration) -> Timestamp; +} + +#[cfg(target_arch = "wasm32")] +use instant::Instant as InstantWasm32; +#[cfg(target_arch = "wasm32")] +impl TimeSupplier for InstantWasm32 { + type Now = InstantWasm32; + type StartingPoint = std::time::SystemTime; + + fn now(&self) -> Self::Now { + InstantWasm32::now() + } + + fn starting_point(&self) -> Self::Now { + std::time::UNIX_EPOCH + } + + fn elapsed_since(now: Self::Now, since: Self::Now) -> Duration { + now - since + } - fn as_i64(&self) -> i64; + fn as_i64(duration: Duration) -> i64 { + duration.as_millis() as i64 + } + + fn to_timestamp(duration: Duration) -> Timestamp { + Timestamp(duration.as_millis() as i64) + } +} + +#[cfg(all(not(target_arch = "wasm32"), feature = "std"))] +use std::time::Instant; +#[cfg(all(not(target_arch = "wasm32"), feature = "std"))] +impl TimeSupplier for Instant { + type Now = Instant; + + fn now(&self) -> Self::Now { + Instant::now() + } + + fn elapsed_since(now: Self::Now, since: Self::Now) -> Duration { + now - since + } + + fn as_i64(duration: Duration) -> i64 { + duration.as_millis() as i64 + } + + fn to_timestamp(duration: Duration) -> Timestamp { + Timestamp(duration.as_i64()) + } } /// Unix timestamp in seconds @@ -49,9 +105,16 @@ impl Timestamp { Self(ts as i64) } - #[cfg(not(feature = "std"))] - pub fn now_no_std(time_supplier: &impl TimeSupplier) -> Self { - Self(time_supplier.as_i64()) + //#[cfg(not(feature = "std"))] + pub fn now_nostd(time_supplier: &T) -> Self + where + T: TimeSupplier, + { + let now = time_supplier.now(); + let starting_point = time_supplier.starting_point(); + let duration = ::elapsed_duration(now, starting_point); + + ::to_timestamp(duration) } /// Get timestamp as [`u64`] From 6edffb3c444d59c53757e704e9d1e72cb4ee0574 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 30 Mar 2023 11:21:37 +0200 Subject: [PATCH 11/77] nostr: compiling with --no-default-features --features=alloc --- crates/nostr/src/event/builder.rs | 28 +++++++++++++++++++++------- crates/nostr/src/event/tag.rs | 10 +++++----- crates/nostr/src/event/unsigned.rs | 5 ++++- crates/nostr/src/lib.rs | 4 ---- crates/nostr/src/message/client.rs | 6 +++++- crates/nostr/src/message/relay.rs | 6 +++++- crates/nostr/src/types/time.rs | 26 +++++++++++++------------- 7 files changed, 53 insertions(+), 32 deletions(-) diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index 9f890a260..9cbf87637 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -146,7 +146,12 @@ impl EventBuilder { /// Build POW [`Event`] #[cfg(feature = "std")] - pub fn to_pow_event(self, keys: &Keys, difficulty: u8) -> Result {} + pub fn to_pow_event(self, keys: &Keys, difficulty: u8) -> Result { + #[cfg(target_arch = "wasm32")] + use instant::Instant; + #[cfg(target_arch = "wasm32")] + self.to_pow_event_with_time_supplier(self, keys, difficulty, Instant); + } #[cfg(feature = "std")] pub fn to_pow_event_with_time_supplier( self, @@ -156,12 +161,15 @@ impl EventBuilder { ) -> Result { } - fn to_pow_event_internal( + fn to_pow_event_internal( self, keys: &Keys, difficulty: u8, - time_supplier: &impl TimeSupplier, - ) -> Result { + time_supplier: &T, + ) -> Result + where + T: TimeSupplier, + { #[cfg(target_arch = "wasm32")] use instant::Instant; #[cfg(all(not(target_arch = "wasm32"), feature = "std"))] @@ -185,15 +193,21 @@ impl EventBuilder { tags.push(Tag::POW { nonce, difficulty }); - let created_at: Timestamp = Timestamp::now(); + //let created_at: Timestamp = Timestamp::now(); + let new_now = time_supplier.now(); + let starting_point = time_supplier.starting_point(); + let created_at = time_supplier.elapsed_duration(new_now.clone(), starting_point); + let created_at = time_supplier.to_timestamp(created_at); let id = EventId::new(&pubkey, created_at, &self.kind, &tags, &self.content); if nip13::get_leading_zero_bits(id.inner()) >= difficulty { log::debug!( "{} iterations in {} ms. Avg rate {} hashes/second", nonce, - now.elapsed().as_millis(), - nonce * 1000 / cmp::max(1, now.elapsed().as_millis()) + //now.elapsed().as_millis(), + time_supplier.elapsed_since(now.clone(), new_now.clone()).as_millis(), + nonce * 1000 + / cmp::max(1, time_supplier.elapsed_since(now, new_now).as_millis()) ); return UnsignedEvent { diff --git a/crates/nostr/src/event/tag.rs b/crates/nostr/src/event/tag.rs index 220c0a66b..f217a6f98 100644 --- a/crates/nostr/src/event/tag.rs +++ b/crates/nostr/src/event/tag.rs @@ -3,15 +3,15 @@ //! Tag -use core::fmt; -use core::num::ParseIntError; -use core::str::FromStr; +#[cfg(feature = "alloc")] +use alloc::format; #[cfg(feature = "alloc")] use alloc::string::{String, ToString}; #[cfg(feature = "alloc")] use alloc::{vec, vec::Vec}; -#[cfg(feature = "alloc")] -use alloc::format; +use core::fmt; +use core::num::ParseIntError; +use core::str::FromStr; use secp256k1::schnorr::Signature; use secp256k1::XOnlyPublicKey; diff --git a/crates/nostr/src/event/unsigned.rs b/crates/nostr/src/event/unsigned.rs index e3e3b532a..051235f4f 100644 --- a/crates/nostr/src/event/unsigned.rs +++ b/crates/nostr/src/event/unsigned.rs @@ -5,7 +5,10 @@ use core::fmt; #[cfg(feature = "alloc")] -use alloc::{string::{String, ToString}, vec::Vec}; +use alloc::{ + string::{String, ToString}, + vec::Vec, +}; use secp256k1::schnorr::Signature; use secp256k1::{Message, XOnlyPublicKey}; diff --git a/crates/nostr/src/lib.rs b/crates/nostr/src/lib.rs index d6922f163..a616c3d3e 100644 --- a/crates/nostr/src/lib.rs +++ b/crates/nostr/src/lib.rs @@ -1,10 +1,7 @@ // Copyright (c) 2022-2023 Yuki Kishimoto // Distributed under the MIT software license - - #![cfg_attr(not(feature = "std"), feature(error_in_core))] - #![warn(missing_docs)] #![warn(rustdoc::bare_urls)] @@ -14,7 +11,6 @@ feature = "default", doc = include_str!("../README.md") )] - #![cfg_attr(not(feature = "std"), no_std)] #[cfg(feature = "alloc")] extern crate alloc; diff --git a/crates/nostr/src/message/client.rs b/crates/nostr/src/message/client.rs index 2f58650b1..fef725a3d 100644 --- a/crates/nostr/src/message/client.rs +++ b/crates/nostr/src/message/client.rs @@ -5,7 +5,11 @@ //! Client messages #[cfg(feature = "alloc")] -use alloc::{boxed::Box, string::{String, ToString}, vec, vec::Vec}; +use alloc::boxed::Box; +#[cfg(feature = "alloc")] +use alloc::string::{String, ToString}; +#[cfg(feature = "alloc")] +use alloc::{vec, vec::Vec}; use serde::de::Error; use serde::{Deserialize, Deserializer, Serialize, Serializer}; diff --git a/crates/nostr/src/message/relay.rs b/crates/nostr/src/message/relay.rs index d822c568f..6433f2b5e 100644 --- a/crates/nostr/src/message/relay.rs +++ b/crates/nostr/src/message/relay.rs @@ -5,7 +5,11 @@ //! Relay messages #[cfg(feature = "alloc")] -use alloc::{boxed::Box, string::{String, ToString}, vec}; +use alloc::boxed::Box; +#[cfg(feature = "alloc")] +use alloc::string::{String, ToString}; +#[cfg(feature = "alloc")] +use alloc::vec; use serde::de::Error; use serde::{Deserialize, Deserializer, Serialize, Serializer}; diff --git a/crates/nostr/src/types/time.rs b/crates/nostr/src/types/time.rs index e4caf714e..05f57aea4 100644 --- a/crates/nostr/src/types/time.rs +++ b/crates/nostr/src/types/time.rs @@ -27,16 +27,16 @@ const UNIX_EPOCH: SystemTime = SystemTime::UNIX_EPOCH; /// Helper trait for acquiring time in `no_std` environments. pub trait TimeSupplier { - type Now; + type Now: Clone; type StartingPoint; fn now(&self) -> Self::Now; fn starting_point(&self) -> Self::StartingPoint; - fn elapsed_since(now: Self::Now, since: Self::Now) -> Duration; - fn elapsed_duration(now: Self::Now, since: Self::StartingPoint) -> Duration; + fn elapsed_since(&self, now: Self::Now, since: Self::Now) -> Duration; + fn elapsed_duration(&self, now: Self::Now, since: Self::StartingPoint) -> Duration; - fn as_i64(duration: Duration) -> i64; - fn to_timestamp(duration: Duration) -> Timestamp; + fn as_i64(&self, duration: Duration) -> i64; + fn to_timestamp(&self, duration: Duration) -> Timestamp; } #[cfg(target_arch = "wasm32")] @@ -54,15 +54,15 @@ impl TimeSupplier for InstantWasm32 { std::time::UNIX_EPOCH } - fn elapsed_since(now: Self::Now, since: Self::Now) -> Duration { + fn elapsed_since(&self, now: Self::Now, since: Self::Now) -> Duration { now - since } - fn as_i64(duration: Duration) -> i64 { + fn as_i64(&self, duration: Duration) -> i64 { duration.as_millis() as i64 } - fn to_timestamp(duration: Duration) -> Timestamp { + fn to_timestamp(&self, duration: Duration) -> Timestamp { Timestamp(duration.as_millis() as i64) } } @@ -77,15 +77,15 @@ impl TimeSupplier for Instant { Instant::now() } - fn elapsed_since(now: Self::Now, since: Self::Now) -> Duration { + fn elapsed_since(&self, now: Self::Now, since: Self::Now) -> Duration { now - since } - fn as_i64(duration: Duration) -> i64 { + fn as_i64(&self, duration: Duration) -> i64 { duration.as_millis() as i64 } - fn to_timestamp(duration: Duration) -> Timestamp { + fn to_timestamp(&self, duration: Duration) -> Timestamp { Timestamp(duration.as_i64()) } } @@ -112,9 +112,9 @@ impl Timestamp { { let now = time_supplier.now(); let starting_point = time_supplier.starting_point(); - let duration = ::elapsed_duration(now, starting_point); + let duration = time_supplier.elapsed_duration(now, starting_point); - ::to_timestamp(duration) + time_supplier.to_timestamp(duration) } /// Get timestamp as [`u64`] From 33a6d0fd982aa770a4d6933cc92d944176f601bf Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 30 Mar 2023 13:12:52 +0200 Subject: [PATCH 12/77] nostr: `EventBuilder` cleanup --- crates/nostr/src/event/builder.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index 9cbf87637..eacfee250 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -152,13 +152,17 @@ impl EventBuilder { #[cfg(target_arch = "wasm32")] self.to_pow_event_with_time_supplier(self, keys, difficulty, Instant); } - #[cfg(feature = "std")] - pub fn to_pow_event_with_time_supplier( + + pub fn to_pow_event_with_time_supplier( self, keys: &Keys, difficulty: u8, time_supplier: &impl TimeSupplier, - ) -> Result { + ) -> Result + where + T: TimeSupplier, + { + self.to_pow_event_internal(keys, difficulty, time_supplier) } fn to_pow_event_internal( @@ -185,7 +189,6 @@ impl EventBuilder { let pubkey = keys.public_key(); - //let now = Instant::now(); let now = time_supplier.now(); loop { @@ -193,7 +196,6 @@ impl EventBuilder { tags.push(Tag::POW { nonce, difficulty }); - //let created_at: Timestamp = Timestamp::now(); let new_now = time_supplier.now(); let starting_point = time_supplier.starting_point(); let created_at = time_supplier.elapsed_duration(new_now.clone(), starting_point); @@ -204,8 +206,9 @@ impl EventBuilder { log::debug!( "{} iterations in {} ms. Avg rate {} hashes/second", nonce, - //now.elapsed().as_millis(), - time_supplier.elapsed_since(now.clone(), new_now.clone()).as_millis(), + time_supplier + .elapsed_since(now.clone(), new_now.clone()) + .as_millis(), nonce * 1000 / cmp::max(1, time_supplier.elapsed_since(now, new_now).as_millis()) ); From 77b08b27e5de240ddf29510a339c1de726b4001e Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 30 Mar 2023 13:31:21 +0200 Subject: [PATCH 13/77] nostr: add missing documentation comments --- crates/nostr/src/event/builder.rs | 5 +++++ crates/nostr/src/lib.rs | 1 + crates/nostr/src/types/time.rs | 13 ++++++++++++- 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index eacfee250..29240d3bd 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -121,6 +121,7 @@ impl EventBuilder { Self::to_event_internal(self, keys, created_at) } + /// Build [`Event`] with a `timestamp` #[cfg(not(feature = "std"))] pub fn to_event_with_timestamp( self, @@ -153,6 +154,7 @@ impl EventBuilder { self.to_pow_event_with_time_supplier(self, keys, difficulty, Instant); } + /// Build POW [`Event`] using the given time supplier pub fn to_pow_event_with_time_supplier( self, keys: &Keys, @@ -235,6 +237,9 @@ impl EventBuilder { Self::to_unsigned_event_internal(self, pubkey, created_at) } #[cfg(not(feature = "std"))] + /// Build [`UnsignedEvent`] with the given `Timestamp` + /// Mostly useful for cases where the time source comes from the outside, not from builtin + /// functions pub fn to_unsigned_event_with_timestamp( self, pubkey: XOnlyPublicKey, diff --git a/crates/nostr/src/lib.rs b/crates/nostr/src/lib.rs index a616c3d3e..e1d06236b 100644 --- a/crates/nostr/src/lib.rs +++ b/crates/nostr/src/lib.rs @@ -50,5 +50,6 @@ pub use self::types::{ChannelId, Contact, Entity, Metadata, Profile, Timestamp, /// Result #[cfg(feature = "std")] pub type Result> = std::result::Result; +/// Result #[cfg(feature = "alloc")] pub type Result> = core::result::Result; diff --git a/crates/nostr/src/types/time.rs b/crates/nostr/src/types/time.rs index 05f57aea4..fd72cfaf0 100644 --- a/crates/nostr/src/types/time.rs +++ b/crates/nostr/src/types/time.rs @@ -27,15 +27,25 @@ const UNIX_EPOCH: SystemTime = SystemTime::UNIX_EPOCH; /// Helper trait for acquiring time in `no_std` environments. pub trait TimeSupplier { + /// The current time from the specified `TimeSupplier` type Now: Clone; + /// The starting point for the specified `TimeSupplier` type StartingPoint; + /// Get the current time as the associated `Now` type fn now(&self) -> Self::Now; + /// Get the starting point from the specified `TimeSupplier` fn starting_point(&self) -> Self::StartingPoint; + /// Get the elapsed time as `Duration` starting from `since` to `now` fn elapsed_since(&self, now: Self::Now, since: Self::Now) -> Duration; + /// Get the elapsed time as `Duration` starting from `since` to `now` + /// This is the specialised case for handling the `StartingPoint` in case its type is different + /// than the `Now` type. fn elapsed_duration(&self, now: Self::Now, since: Self::StartingPoint) -> Duration; + /// Convert the specified `Duration` to `i64` fn as_i64(&self, duration: Duration) -> i64; + /// Convert the specified `Duration` to `Timestamp` fn to_timestamp(&self, duration: Duration) -> Timestamp; } @@ -105,7 +115,8 @@ impl Timestamp { Self(ts as i64) } - //#[cfg(not(feature = "std"))] + /// Get UNIX timestamp from the specified `TimeSupplier` + #[cfg(not(feature = "std"))] pub fn now_nostd(time_supplier: &T) -> Self where T: TimeSupplier, From 32c297505404ba6454458ddf85d84d86bddd1d30 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 31 Mar 2023 14:28:40 +0200 Subject: [PATCH 14/77] nostr: make sure dependencies are no_std compatible --- crates/nostr/Cargo.toml | 49 +++++++++--- crates/nostr/src/event/mod.rs | 20 ++++- crates/nostr/src/key/mod.rs | 95 +++++++++++++++++++++++- crates/nostr/src/lib.rs | 12 ++- crates/nostr/src/message/subscription.rs | 6 +- crates/nostr/src/nips/nip26.rs | 22 ++++++ crates/nostr/src/prelude.rs | 5 +- 7 files changed, 193 insertions(+), 16 deletions(-) diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml index a7c7c9b85..9ff170cff 100644 --- a/crates/nostr/Cargo.toml +++ b/crates/nostr/Cargo.toml @@ -13,8 +13,28 @@ keywords = ["nostr", "protocol", "sdk"] [features] default = ["all-nips", "std"] -std = ["dep:thiserror"] -alloc = ["dep:thiserror-core"] +std = [ + "dep:thiserror", + "bitcoin_hashes/serde", + "serde/derive", + "serde/std", + "serde_json/std", + "url", + "secp256k1/global-context", + "secp256k1/rand-std", + "secp256k1/serde", +] +alloc = [ + "dep:thiserror-core", + "bitcoin_hashes/alloc", + "bitcoin_hashes/serde", + "serde/derive", + "serde_json/alloc", + "url_no_std", + "secp256k1/alloc", + "rand_core", + +] blocking = ["reqwest?/blocking"] vanity = ["nip19"] all-nips = ["nip04", "nip05", "nip06", "nip11", "nip19", "nip21", "nip46"] @@ -35,18 +55,29 @@ bip39 = { version = "2.0", optional = true } bitcoin = { version = "0.30", optional = true } bitcoin_hashes = { version = "0.12", features = ["serde"] } cbc = { version = "0.1", features = ["alloc"], optional = true } -log = "0.4" +log = "0.4" # no_std compatible by-default nostr-ots = { version = "0.2", optional = true } reqwest = { version = "0.11", default-features = false, features = ["json", "rustls-tls-webpki-roots", "socks"], optional = true } -secp256k1 = { version = "0.27", features = ["global-context", "rand-std", "serde"] } +secp256k1 = { version = "0.27", default-features = false } -serde = { version = "1.0", features = ["derive"] } -serde_json = { version = "1.0" } -url = { version = "2", features = ["serde"] } +serde = { version = "1.0", features = ["derive"], default-features = false, optional = true } +serde_json = { version = "1.0", optional = true, default-features = false } + +url = { version = "2", features = ["serde"], optional = true } +url_no_std = { package = "url", features = [ + "serde", +], branch = "no_std", git = "https://github.com/OverOrion/rust-url", optional = true } + +rand_core = { version = "0.6", features = [ + "alloc", + "getrandom", +], optional = true } + +rand = { version = "0.8", features = ["alloc", "getrandom"], optional = true } #[target.'cfg(target_arch = "wasm32")'.dependencies] -getrandom = { version = "0.2", features = ["js"] } -instant = { version = "0.1", features = ["wasm-bindgen", "inaccurate"] } +#getrandom = { version = "0.2", features = ["js"] } +#instant = { version = "0.1", features = ["wasm-bindgen", "inaccurate"] } [dev-dependencies] csv = "1.1.5" diff --git a/crates/nostr/src/event/mod.rs b/crates/nostr/src/event/mod.rs index d889d313f..0fe55ed96 100644 --- a/crates/nostr/src/event/mod.rs +++ b/crates/nostr/src/event/mod.rs @@ -28,7 +28,9 @@ pub use self::id::EventId; pub use self::kind::Kind; pub use self::tag::{Marker, Tag, TagKind}; pub use self::unsigned::UnsignedEvent; -use crate::{Timestamp, SECP256K1}; +use crate::Timestamp; +#[cfg(feature = "std")] +use crate::SECP256K1; /// [`Event`] error #[derive(Debug)] @@ -111,6 +113,7 @@ pub struct Event { impl Event { /// Verify event + #[cfg(feature = "std")] pub fn verify(&self) -> Result<(), Error> { let id = EventId::new( &self.pubkey, @@ -125,6 +128,21 @@ impl Event { .map_err(|_| Error::InvalidSignature) } + #[cfg(not(feature = "std"))] + pub fn verify_with_context(&self, context: &impl secp256k1::Verification) -> Result<(), Error> { + let id = EventId::new( + &self.pubkey, + self.created_at, + &self.kind, + &self.tags, + &self.content, + ); + let message = Message::from_slice(id.as_bytes())?; + context + .verify_schnorr(&self.sig, &message, &self.pubkey) + .map_err(|_| Error::InvalidSignature) + } + /// New event from [`Value`] pub fn from_value(value: Value) -> Result { let event: Self = serde_json::from_value(value)?; diff --git a/crates/nostr/src/key/mod.rs b/crates/nostr/src/key/mod.rs index c1d70946a..e80577724 100644 --- a/crates/nostr/src/key/mod.rs +++ b/crates/nostr/src/key/mod.rs @@ -10,12 +10,25 @@ use core::fmt; #[cfg(feature = "nip19")] use core::str::FromStr; +#[cfg(feature = "alloc")] +use rand_core::OsRng; +#[cfg(feature = "std")] use secp256k1::rand::rngs::OsRng; + +#[cfg(feature = "alloc")] +use secp256k1::Secp256k1; +#[cfg(feature = "alloc")] +use secp256k1::Signing; + +#[cfg(feature = "alloc")] +use randrand::Rng; +#[cfg(feature = "std")] use secp256k1::rand::Rng; use secp256k1::schnorr::Signature; use secp256k1::Message; pub use secp256k1::{KeyPair, PublicKey, SecretKey, XOnlyPublicKey}; +#[cfg(feature = "std")] use crate::SECP256K1; #[cfg(feature = "vanity")] @@ -85,6 +98,7 @@ pub struct Keys { impl Keys { /// Initialize from secret key. + #[cfg(feature = "std")] pub fn new(secret_key: SecretKey) -> Self { let key_pair = KeyPair::from_secret_key(SECP256K1, &secret_key); let public_key = XOnlyPublicKey::from_keypair(&key_pair).0; @@ -96,6 +110,21 @@ impl Keys { } } + #[cfg(not(feature = "std"))] + pub fn new_with_secp( + secret_key: SecretKey, + secp: &Secp256k1, + ) -> Self { + let key_pair = KeyPair::from_secret_key(secp, &secret_key); + let public_key = XOnlyPublicKey::from_keypair(&key_pair).0; + + Self { + public_key, + key_pair: Some(key_pair), + secret_key: Some(secret_key), + } + } + /// Initialize with public key only (no secret key). pub fn from_public_key(public_key: XOnlyPublicKey) -> Self { Self { @@ -106,13 +135,22 @@ impl Keys { } /// Generate new random [`Keys`] + #[cfg(feature = "std")] pub fn generate() -> Self { let mut rng = OsRng::default(); let (secret_key, _) = SECP256K1.generate_keypair(&mut rng); Self::new(secret_key) } + #[cfg(not(feature = "std"))] + pub fn generate_with_secp(secp: &Secp256k1) -> Self { + let mut rng = OsRng::default(); + let (secret_key, _) = secp.generate_keypair(&mut rng); + Self::new(secret_key) + } + /// Generate random [`Keys`] with custom [`Rng`] + #[cfg(feature = "std")] pub fn generate_with_rng(rng: &mut R) -> Self where R: Rng + ?Sized, @@ -121,8 +159,18 @@ impl Keys { Self::new(secret_key) } + #[cfg(not(feature = "std"))] + pub fn generate_with_rng_with_secp(rng: &mut R, secp: &Secp256k1) -> Self + where + R: Rng + ?Sized, + { + let (secret_key, _) = secp.generate_keypair(rng); + Self::new(secret_key) + } + /// Generate random [`Keys`] with custom [`Rng`] and without [`KeyPair`] /// Useful for faster [`Keys`] generation (ex. vanity pubkey mining) + #[cfg(feature = "std")] pub fn generate_without_keypair(rng: &mut R) -> Self where R: Rng + ?Sized, @@ -136,7 +184,26 @@ impl Keys { } } - /// Get [`XOnlyPublicKey`] + /// Generate random [`Keys`] with custom [`Rng`] and without [`KeyPair`] + /// Useful for faster [`Keys`] generation (ex. vanity pubkey mining) + #[cfg(not(feature = "std"))] + pub fn generate_without_keypair_with_secp( + rng: &mut R, + secp: &Secp256k1, + ) -> Self + where + R: Rng + ?Sized, + { + let (secret_key, public_key) = secp.generate_keypair(rng); + let (public_key, _) = public_key.x_only_public_key(); + Self { + public_key, + key_pair: None, + secret_key: Some(secret_key), + } + } + + /// Get public key pub fn public_key(&self) -> XOnlyPublicKey { self.public_key } @@ -158,6 +225,7 @@ impl Keys { /// Get keypair /// /// If not exists, will be created + #[cfg(feature = "std")] pub fn key_pair(&self) -> Result { if let Some(key_pair) = self.key_pair { Ok(key_pair) @@ -167,11 +235,36 @@ impl Keys { } } + /// Get keypair + /// + /// If not exists, will be created + #[cfg(not(feature = "std"))] + pub fn key_pair_from_secp(&self, secp: &Secp256k1) -> Result { + if let Some(key_pair) = self.key_pair { + Ok(key_pair) + } else { + let sk = self.secret_key()?; + Ok(KeyPair::from_secret_key(secp, &sk)) + } + } + /// Sign schnorr [`Message`] + #[cfg(feature = "std")] pub fn sign_schnorr(&self, message: &Message) -> Result { let keypair: &KeyPair = &self.key_pair()?; Ok(SECP256K1.sign_schnorr(message, keypair)) } + + /// Sign schnorr [`Message`] + #[cfg(not(feature = "std"))] + pub fn sign_schnorr_with_secp( + &self, + message: &Message, + secp: &Secp256k1, + ) -> Result { + let keypair: &KeyPair = &self.key_pair()?; + Ok(secp.sign_schnorr(message, keypair)) + } } #[cfg(feature = "nip19")] diff --git a/crates/nostr/src/lib.rs b/crates/nostr/src/lib.rs index e1d06236b..d11434d88 100644 --- a/crates/nostr/src/lib.rs +++ b/crates/nostr/src/lib.rs @@ -31,9 +31,17 @@ pub use bip39; #[cfg(feature = "nip06")] pub use bitcoin; pub use bitcoin_hashes as hashes; -pub use secp256k1::{self, SECP256K1}; +pub use secp256k1; +#[cfg(feature = "std")] +pub use secp256k1::SECP256K1; pub use serde_json; -pub use url::{self, Url}; + +#[cfg(feature = "std")] +pub use url; +#[cfg(feature = "alloc")] +extern crate url_no_std as url; + +pub use url::Url; pub mod event; pub mod key; diff --git a/crates/nostr/src/message/subscription.rs b/crates/nostr/src/message/subscription.rs index 7f86bbc1c..f0c65fcad 100644 --- a/crates/nostr/src/message/subscription.rs +++ b/crates/nostr/src/message/subscription.rs @@ -17,8 +17,10 @@ use alloc::{ use bitcoin_hashes::sha256::Hash as Sha256Hash; use bitcoin_hashes::Hash; -use secp256k1::rand::rngs::OsRng; -use secp256k1::rand::RngCore; +#[cfg(feature = "alloc")] +use rand_core::{OsRng, RngCore}; +#[cfg(feature = "std")] +use secp256k1::rand::{rngs::OsRng, RngCore}; use secp256k1::XOnlyPublicKey; use serde::de::{self, Deserializer, MapAccess, Visitor}; use serde::ser::{SerializeMap, Serializer}; diff --git a/crates/nostr/src/nips/nip26.rs b/crates/nostr/src/nips/nip26.rs index 5f669f232..b1870dac5 100644 --- a/crates/nostr/src/nips/nip26.rs +++ b/crates/nostr/src/nips/nip26.rs @@ -27,8 +27,13 @@ use serde_json::{json, Value}; use crate::event::Event; use crate::key::{self, Keys}; + +#[cfg(feature = "std")] use crate::SECP256K1; +#[cfg(not(feature = "std"))] +use secp256k1::{Secp256k1, Signing}; + const DELEGATION_KEYWORD: &str = "delegation"; /// `NIP26` error @@ -131,6 +136,7 @@ pub fn sign_delegation( } /// Verify delegation signature +#[cfg(feature = "std")] pub fn verify_delegation_signature( delegator_public_key: XOnlyPublicKey, signature: Signature, @@ -144,6 +150,22 @@ pub fn verify_delegation_signature( Ok(()) } +/// Verify delegation signature +#[cfg(not(feature = "std"))] +pub fn verify_delegation_signature( + delegator_public_key: XOnlyPublicKey, + signature: Signature, + delegatee_public_key: XOnlyPublicKey, + conditions: Conditions, + secp: &Secp256k1, +) -> Result<(), Error> { + let unhashed_token = DelegationToken::new(delegatee_public_key, conditions); + let hashed_token = Sha256Hash::hash(unhashed_token.as_bytes()); + let message = Message::from_slice(&hashed_token)?; + secp.verify_schnorr(&signature, &message, &delegator_public_key)?; + Ok(()) +} + /// Delegation token #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub struct DelegationToken(String); diff --git a/crates/nostr/src/prelude.rs b/crates/nostr/src/prelude.rs index 6dc142291..4258c6c03 100644 --- a/crates/nostr/src/prelude.rs +++ b/crates/nostr/src/prelude.rs @@ -25,7 +25,10 @@ pub use crate::event::*; pub use crate::key::*; pub use crate::message::*; pub use crate::types::*; -pub use crate::{Result, SECP256K1}; +pub use crate::Result; + +#[cfg(feature = "std")] +pub use crate::SECP256K1; // NIPs #[cfg(feature = "nip04")] From 501b2b525d86420c79207909b2f7141153ca038a Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 31 Mar 2023 16:40:34 +0200 Subject: [PATCH 15/77] nostr: adjust secp256k1 related things in no_std --- crates/nostr/Cargo.toml | 10 ++++- crates/nostr/src/event/builder.rs | 51 +++++++++++----------- crates/nostr/src/event/mod.rs | 26 +++--------- crates/nostr/src/event/unsigned.rs | 20 ++++++++- crates/nostr/src/key/mod.rs | 15 ++++--- crates/nostr/src/nips/nip26.rs | 68 +++++++++++++++++++++++++++++- crates/nostr/src/prelude.rs | 6 +-- 7 files changed, 137 insertions(+), 59 deletions(-) diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml index 9ff170cff..8bdc95244 100644 --- a/crates/nostr/Cargo.toml +++ b/crates/nostr/Cargo.toml @@ -32,7 +32,11 @@ alloc = [ "serde_json/alloc", "url_no_std", "secp256k1/alloc", + "secp256k1/serde", + "secp256k1/rand", + "secp256k1/core-error", "rand_core", + "rand", ] blocking = ["reqwest?/blocking"] @@ -73,7 +77,11 @@ rand_core = { version = "0.6", features = [ "getrandom", ], optional = true } -rand = { version = "0.8", features = ["alloc", "getrandom"], optional = true } +rand = { version = "0.8", features = [ + "alloc", + "getrandom", + "serde1", +], optional = true } #[target.'cfg(target_arch = "wasm32")'.dependencies] #getrandom = { version = "0.2", features = ["js"] } diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index 29240d3bd..8a4982d73 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -2,19 +2,18 @@ // Distributed under the MIT software license //! Event builder +use core::fmt; + #[cfg(feature = "alloc")] use alloc::{ string::{String, ToString}, vec::Vec, }; -use core::fmt; -#[cfg(not(target_arch = "wasm32"))] -use std::time::Instant; - -#[cfg(target_arch = "wasm32")] -use instant::Instant; -use secp256k1::XOnlyPublicKey; +use secp256k1::schnorr::Signature; +use secp256k1::{Message, XOnlyPublicKey}; +#[cfg(not(feature = "std"))] +use secp256k1::{Secp256k1, Signing}; use serde_json::{json, Value}; use url::Url; @@ -116,24 +115,24 @@ impl EventBuilder { /// Build [`Event`] #[cfg(feature = "std")] pub fn to_event(self, keys: &Keys) -> Result { + let pubkey: XOnlyPublicKey = keys.public_key(); let created_at: Timestamp = Timestamp::now(); + let id = EventId::new(&pubkey, created_at, &self.kind, &self.tags, &self.content); + let message = Message::from_slice(id.as_bytes())?; + let signature = keys.sign_schnorr(&message)?; - Self::to_event_internal(self, keys, created_at) + Self::to_event_internal(self, keys, created_at, id, signature) } /// Build [`Event`] with a `timestamp` #[cfg(not(feature = "std"))] - pub fn to_event_with_timestamp( + pub fn to_event_with_timestamp_with_secp( self, keys: &Keys, created_at: Timestamp, + secp: &Secp256k1, ) -> Result { - Self::to_event_internal(self, keys, created_at) - } - - fn to_event_internal(self, keys: &Keys, created_at: Timestamp) -> Result { let pubkey: XOnlyPublicKey = keys.public_key(); - let id = EventId::new(&pubkey, created_at, &self.kind, &self.tags, &self.content); UnsignedEvent { id, @@ -151,27 +150,29 @@ impl EventBuilder { #[cfg(target_arch = "wasm32")] use instant::Instant; #[cfg(target_arch = "wasm32")] - self.to_pow_event_with_time_supplier(self, keys, difficulty, Instant); + self.to_pow_event_with_time_supplier_with_secp(self, keys, difficulty, Instant, SECP256K1); } /// Build POW [`Event`] using the given time supplier - pub fn to_pow_event_with_time_supplier( + pub fn to_pow_event_with_time_supplier_with_secp( self, keys: &Keys, difficulty: u8, time_supplier: &impl TimeSupplier, + secp: &Secp256k1, ) -> Result where T: TimeSupplier, { - self.to_pow_event_internal(keys, difficulty, time_supplier) + self.to_pow_event_internal(keys, difficulty, time_supplier, secp) } - fn to_pow_event_internal( + fn to_pow_event_internal( self, keys: &Keys, difficulty: u8, time_supplier: &T, + secp: &Secp256k1, ) -> Result where T: TimeSupplier, @@ -187,7 +188,7 @@ impl EventBuilder { /// Build unsigned POW [`Event`] pub fn to_unsigned_pow_event(self, pubkey: XOnlyPublicKey, difficulty: u8) -> UnsignedEvent { let mut nonce: u128 = 0; - let mut tags: Vec = self.tags; + let mut tags: Vec = self.tags.clone(); let pubkey = keys.public_key(); @@ -215,14 +216,10 @@ impl EventBuilder { / cmp::max(1, time_supplier.elapsed_since(now, new_now).as_millis()) ); - return UnsignedEvent { - id, - pubkey, - created_at, - kind: self.kind, - tags, - content: self.content, - }; + let message = Message::from_slice(id.as_bytes())?; + let sig = keys.sign_schnorr_with_secp(&message, &secp)?; + + return self.to_event_internal(keys, created_at, id, sig); } tags.pop(); diff --git a/crates/nostr/src/event/mod.rs b/crates/nostr/src/event/mod.rs index 0fe55ed96..c748ac300 100644 --- a/crates/nostr/src/event/mod.rs +++ b/crates/nostr/src/event/mod.rs @@ -14,6 +14,8 @@ use alloc::vec::Vec; use secp256k1::schnorr::Signature; use secp256k1::{Message, XOnlyPublicKey}; +#[cfg(feature = "alloc")] +use secp256k1::{Secp256k1, Verification}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -112,24 +114,15 @@ pub struct Event { } impl Event { - /// Verify event + /// Verify Event #[cfg(feature = "std")] pub fn verify(&self) -> Result<(), Error> { - let id = EventId::new( - &self.pubkey, - self.created_at, - &self.kind, - &self.tags, - &self.content, - ); - let message = Message::from_slice(id.as_bytes())?; - SECP256K1 - .verify_schnorr(&self.sig, &message, &self.pubkey) - .map_err(|_| Error::InvalidSignature) + self.verify_with_context(SECP256K1) } + /// Verify Event #[cfg(not(feature = "std"))] - pub fn verify_with_context(&self, context: &impl secp256k1::Verification) -> Result<(), Error> { + pub fn verify_with_context(&self, secp: &Secp256k1) -> Result<(), Error> { let id = EventId::new( &self.pubkey, self.created_at, @@ -138,15 +131,13 @@ impl Event { &self.content, ); let message = Message::from_slice(id.as_bytes())?; - context - .verify_schnorr(&self.sig, &message, &self.pubkey) + secp.verify_schnorr(&self.sig, &message, &self.pubkey) .map_err(|_| Error::InvalidSignature) } /// New event from [`Value`] pub fn from_value(value: Value) -> Result { let event: Self = serde_json::from_value(value)?; - event.verify()?; Ok(event) } @@ -156,7 +147,6 @@ impl Event { S: Into, { let event: Self = serde_json::from_str(&json.into())?; - event.verify()?; Ok(event) } @@ -215,8 +205,6 @@ impl Event { ots: None, }; - event.verify()?; - Ok(event) } } diff --git a/crates/nostr/src/event/unsigned.rs b/crates/nostr/src/event/unsigned.rs index 051235f4f..9a230be98 100644 --- a/crates/nostr/src/event/unsigned.rs +++ b/crates/nostr/src/event/unsigned.rs @@ -14,7 +14,7 @@ use secp256k1::schnorr::Signature; use secp256k1::{Message, XOnlyPublicKey}; use serde::{Deserialize, Serialize}; -use crate::{Event, EventId, Keys, Kind, Tag, Timestamp}; +use crate::{Event, EventId, Kind, Tag, Timestamp}; /// [`UnsignedEvent`] error #[derive(Debug)] @@ -85,6 +85,7 @@ pub struct UnsignedEvent { impl UnsignedEvent { /// Sign an [`UnsignedEvent`] + #[cfg(feature = "std")] pub fn sign(self, keys: &Keys) -> Result { let message = Message::from_slice(self.id.as_bytes())?; Ok(Event { @@ -100,7 +101,24 @@ impl UnsignedEvent { }) } + /// Sign an [`UnsignedEvent`] with specified signature + #[cfg(not(feature = "std"))] + pub fn sign_with_signature(self, sig: Signature) -> Result { + Ok(Event { + id: self.id, + pubkey: self.pubkey, + created_at: self.created_at, + kind: self.kind, + tags: self.tags, + content: self.content, + sig, + #[cfg(feature = "nip03")] + ots: None, + }) + } + /// Add signature to [`UnsignedEvent`] + #[cfg(feature = "std")] pub fn add_signature(self, sig: Signature) -> Result { let event = Event { id: self.id, diff --git a/crates/nostr/src/key/mod.rs b/crates/nostr/src/key/mod.rs index e80577724..9f29095d7 100644 --- a/crates/nostr/src/key/mod.rs +++ b/crates/nostr/src/key/mod.rs @@ -21,7 +21,7 @@ use secp256k1::Secp256k1; use secp256k1::Signing; #[cfg(feature = "alloc")] -use randrand::Rng; +use rand::Rng; #[cfg(feature = "std")] use secp256k1::rand::Rng; use secp256k1::schnorr::Signature; @@ -110,6 +110,7 @@ impl Keys { } } + /// Initialize from secret key. #[cfg(not(feature = "std"))] pub fn new_with_secp( secret_key: SecretKey, @@ -142,11 +143,12 @@ impl Keys { Self::new(secret_key) } + /// Generate new random [`Keys`] #[cfg(not(feature = "std"))] pub fn generate_with_secp(secp: &Secp256k1) -> Self { let mut rng = OsRng::default(); let (secret_key, _) = secp.generate_keypair(&mut rng); - Self::new(secret_key) + Self::new_with_secp(secret_key, secp) } /// Generate random [`Keys`] with custom [`Rng`] @@ -159,13 +161,14 @@ impl Keys { Self::new(secret_key) } + /// Generate random [`Keys`] with custom [`Rng`] and given [`Secp256k1`] #[cfg(not(feature = "std"))] pub fn generate_with_rng_with_secp(rng: &mut R, secp: &Secp256k1) -> Self where R: Rng + ?Sized, { let (secret_key, _) = secp.generate_keypair(rng); - Self::new(secret_key) + Self::new_with_secp(secret_key, secp) } /// Generate random [`Keys`] with custom [`Rng`] and without [`KeyPair`] @@ -257,13 +260,13 @@ impl Keys { /// Sign schnorr [`Message`] #[cfg(not(feature = "std"))] - pub fn sign_schnorr_with_secp( + pub fn sign_schnorr_with_secp( &self, message: &Message, secp: &Secp256k1, ) -> Result { - let keypair: &KeyPair = &self.key_pair()?; - Ok(secp.sign_schnorr(message, keypair)) + let keypair: &KeyPair = &self.key_pair_from_secp(&secp)?; + Ok(secp.sign_schnorr_no_aux_rand(message, keypair)) } } diff --git a/crates/nostr/src/nips/nip26.rs b/crates/nostr/src/nips/nip26.rs index b1870dac5..48525769b 100644 --- a/crates/nostr/src/nips/nip26.rs +++ b/crates/nostr/src/nips/nip26.rs @@ -32,7 +32,7 @@ use crate::key::{self, Keys}; use crate::SECP256K1; #[cfg(not(feature = "std"))] -use secp256k1::{Secp256k1, Signing}; +use secp256k1::{Secp256k1, Signing, Verification}; const DELEGATION_KEYWORD: &str = "delegation"; @@ -124,6 +124,7 @@ impl fmt::Display for ValidationError { /// Sign delegation. /// See `create_delegation_tag` for more complete functionality. +#[cfg(feature = "std")] pub fn sign_delegation( delegator_keys: &Keys, delegatee_pk: XOnlyPublicKey, @@ -135,6 +136,21 @@ pub fn sign_delegation( Ok(delegator_keys.sign_schnorr(&message)?) } +/// Sign delegation. +/// See `create_delegation_tag` for more complete functionality. +#[cfg(not(feature = "std"))] +pub fn sign_delegation_with_signer( + delegator_keys: &Keys, + delegatee_pk: XOnlyPublicKey, + conditions: Conditions, + secp: &Secp256k1, +) -> Result { + let unhashed_token = DelegationToken::new(delegatee_pk, conditions); + let hashed_token = Sha256Hash::hash(unhashed_token.as_bytes()); + let message = Message::from_slice(&hashed_token)?; + Ok(delegator_keys.sign_schnorr_with_secp(&message, secp)?) +} + /// Verify delegation signature #[cfg(feature = "std")] pub fn verify_delegation_signature( @@ -152,7 +168,7 @@ pub fn verify_delegation_signature( /// Verify delegation signature #[cfg(not(feature = "std"))] -pub fn verify_delegation_signature( +pub fn verify_delegation_signature( delegator_public_key: XOnlyPublicKey, signature: Signature, delegatee_public_key: XOnlyPublicKey, @@ -201,6 +217,7 @@ pub struct DelegationTag { impl DelegationTag { /// Create a delegation tag (including the signature). /// See also validate(). + #[cfg(feature = "std")] pub fn new( delegator_keys: &Keys, delegatee_pubkey: XOnlyPublicKey, @@ -214,6 +231,28 @@ impl DelegationTag { }) } + /// Create a delegation tag (including the signature). + /// See also validate(). + #[cfg(not(feature = "std"))] + pub fn new( + delegator_keys: &Keys, + delegatee_pubkey: XOnlyPublicKey, + conditions: Conditions, + signer: Secp256k1, + ) -> Result { + let signature = sign_delegation_with_signer( + delegator_keys, + delegatee_pubkey, + conditions.clone(), + &signer, + )?; + Ok(Self { + delegator_pubkey: delegator_keys.public_key(), + conditions, + signature, + }) + } + /// Get delegator public key pub fn delegator_pubkey(&self) -> XOnlyPublicKey { self.delegator_pubkey @@ -230,6 +269,7 @@ impl DelegationTag { } /// Validate a delegation tag, check signature and conditions. + #[cfg(feature = "std")] pub fn validate( &self, delegatee_pubkey: XOnlyPublicKey, @@ -249,6 +289,30 @@ impl DelegationTag { Ok(()) } + /// Validate a delegation tag, check signature and conditions. + #[cfg(not(feature = "std"))] + pub fn validate( + &self, + delegatee_pubkey: XOnlyPublicKey, + event_properties: &EventProperties, + secp: &Secp256k1, + ) -> Result<(), Error> { + // verify signature + + verify_delegation_signature( + self.delegator_pubkey, + self.signature, + delegatee_pubkey, + self.conditions.clone(), + secp, + ) + .map_err(|_| Error::ConditionsValidation(ValidationError::InvalidSignature))?; + + // validate conditions + self.conditions.evaluate(event_properties)?; + + Ok(()) + } /// Convert to JSON string. pub fn as_json(&self) -> String { diff --git a/crates/nostr/src/prelude.rs b/crates/nostr/src/prelude.rs index 4258c6c03..3820c8d47 100644 --- a/crates/nostr/src/prelude.rs +++ b/crates/nostr/src/prelude.rs @@ -10,10 +10,10 @@ pub use bech32::*; #[cfg(feature = "nip06")] pub use bip39::*; #[cfg(feature = "nip06")] -pub use bitcoin::*; -pub use bitcoin_hashes::*; +//pub use bitcoin::*; +//pub use bitcoin_hashes::*; pub use secp256k1::*; -pub use serde_json::*; +//pub use serde_json::*; // Internal modules pub use crate::event::builder::*; From 7c16daacdfc418ce5f9b243ffdea4afa738e76f3 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Mon, 3 Apr 2023 14:18:12 +0200 Subject: [PATCH 16/77] no_std: switch back to upstream rust-url --- crates/nostr/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml index 8bdc95244..a29eac0f8 100644 --- a/crates/nostr/Cargo.toml +++ b/crates/nostr/Cargo.toml @@ -70,7 +70,7 @@ serde_json = { version = "1.0", optional = true, default-features = false } url = { version = "2", features = ["serde"], optional = true } url_no_std = { package = "url", features = [ "serde", -], branch = "no_std", git = "https://github.com/OverOrion/rust-url", optional = true } +], rev = "6385c81d9b8aa09744359155c180c252d7c111be", git = "https://github.com/servo/rust-url", optional = true } rand_core = { version = "0.6", features = [ "alloc", From 0c80a80a717b8bbc9948ad867fa5d7770b732114 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Szil=C3=A1rd=20Parrag?= Date: Tue, 4 Apr 2023 14:53:09 +0000 Subject: [PATCH 17/77] nostr: compiling --- Cargo.toml | 7 ++++++- crates/nostr/Cargo.toml | 20 ++++++++++++++------ 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 95e2da963..b070fcbc9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,6 +7,7 @@ members = [ "crates/nostr", "crates/nostr-sdk", "crates/nostr-sdk-net", + "crates/ensure_no_std", ] default-members = ["crates/*"] resolver = "2" @@ -19,4 +20,8 @@ rust-version = "1.64.0" [profile.release] lto = true -codegen-units = 1 \ No newline at end of file +codegen-units = 1 +panic = "abort" + +[profile.dev] +panic = "abort" diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml index a29eac0f8..4e1770e76 100644 --- a/crates/nostr/Cargo.toml +++ b/crates/nostr/Cargo.toml @@ -16,6 +16,7 @@ default = ["all-nips", "std"] std = [ "dep:thiserror", "bitcoin_hashes/serde", + "bitcoin_hashes/std", "serde/derive", "serde/std", "serde_json/std", @@ -28,16 +29,20 @@ alloc = [ "dep:thiserror-core", "bitcoin_hashes/alloc", "bitcoin_hashes/serde", + "bitcoin_hashes/core-error", "serde/derive", + "serde/alloc", "serde_json/alloc", "url_no_std", "secp256k1/alloc", "secp256k1/serde", "secp256k1/rand", "secp256k1/core-error", - "rand_core", - "rand", - + "rand_core/alloc", + "rand_core/getrandom", + "rand/alloc", + "rand/getrandom", + "rand/serde1", ] blocking = ["reqwest?/blocking"] vanity = ["nip19"] @@ -70,18 +75,21 @@ serde_json = { version = "1.0", optional = true, default-features = false } url = { version = "2", features = ["serde"], optional = true } url_no_std = { package = "url", features = [ "serde", -], rev = "6385c81d9b8aa09744359155c180c252d7c111be", git = "https://github.com/servo/rust-url", optional = true } + "idna", + "alloc", + "core-error" +], path = "../../../rust-url/url", optional = true, default-features = false } rand_core = { version = "0.6", features = [ "alloc", "getrandom", -], optional = true } +], optional = true, default-features = false} rand = { version = "0.8", features = [ "alloc", "getrandom", "serde1", -], optional = true } +], default-features = false, optional = true } #[target.'cfg(target_arch = "wasm32")'.dependencies] #getrandom = { version = "0.2", features = ["js"] } From 0196a15e5515424ef4619b6896f34725e1aa6635 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Thu, 6 Apr 2023 09:53:13 +0000 Subject: [PATCH 18/77] nostr: accept that other crates don't implement error --- crates/nostr/Cargo.toml | 9 +++++---- crates/nostr/src/event/builder.rs | 7 ++++++- crates/nostr/src/event/id.rs | 3 +-- crates/nostr/src/event/mod.rs | 13 +++++++++++++ crates/nostr/src/event/tag.rs | 12 ++++++++++++ crates/nostr/src/event/unsigned.rs | 10 ++++++++-- crates/nostr/src/nips/nip26.rs | 5 ++--- crates/nostr/src/types/channel_id.rs | 2 +- 8 files changed, 48 insertions(+), 13 deletions(-) diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml index 4e1770e76..15671f8be 100644 --- a/crates/nostr/Cargo.toml +++ b/crates/nostr/Cargo.toml @@ -29,7 +29,6 @@ alloc = [ "dep:thiserror-core", "bitcoin_hashes/alloc", "bitcoin_hashes/serde", - "bitcoin_hashes/core-error", "serde/derive", "serde/alloc", "serde_json/alloc", @@ -37,7 +36,6 @@ alloc = [ "secp256k1/alloc", "secp256k1/serde", "secp256k1/rand", - "secp256k1/core-error", "rand_core/alloc", "rand_core/getrandom", "rand/alloc", @@ -74,10 +72,10 @@ serde_json = { version = "1.0", optional = true, default-features = false } url = { version = "2", features = ["serde"], optional = true } url_no_std = { package = "url", features = [ - "serde", "idna", "alloc", - "core-error" + "core-error", + "core-net", ], path = "../../../rust-url/url", optional = true, default-features = false } rand_core = { version = "0.6", features = [ @@ -91,6 +89,9 @@ rand = { version = "0.8", features = [ "serde1", ], default-features = false, optional = true } + + + #[target.'cfg(target_arch = "wasm32")'.dependencies] #getrandom = { version = "0.2", features = ["js"] } #instant = { version = "0.1", features = ["wasm-bindgen", "inaccurate"] } diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index 8a4982d73..a2d9e8310 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -12,7 +12,6 @@ use alloc::{ use secp256k1::schnorr::Signature; use secp256k1::{Message, XOnlyPublicKey}; -#[cfg(not(feature = "std"))] use secp256k1::{Secp256k1, Signing}; use serde_json::{json, Value}; use url::Url; @@ -91,6 +90,12 @@ impl From for Error { } } +impl From for Error { + fn from(error: secp256k1::Error) -> Self { + Self::Secp256k1(error) + } +} + /// [`Event`] builder #[derive(Debug, Clone, Eq, PartialEq)] pub struct EventBuilder { diff --git a/crates/nostr/src/event/id.rs b/crates/nostr/src/event/id.rs index 793e828a6..fa587155a 100644 --- a/crates/nostr/src/event/id.rs +++ b/crates/nostr/src/event/id.rs @@ -38,8 +38,7 @@ impl fmt::Display for Error { Self::Hex(e) => write!(f, "{e}"), Self::Hash(e) => write!(f, "{e}"), } - } -} + impl From for Error { fn from(e: bitcoin_hashes::hex::Error) -> Self { diff --git a/crates/nostr/src/event/mod.rs b/crates/nostr/src/event/mod.rs index c748ac300..0226961c1 100644 --- a/crates/nostr/src/event/mod.rs +++ b/crates/nostr/src/event/mod.rs @@ -90,6 +90,19 @@ impl From for Error { } } +impl From for Error { + fn from(error: secp256k1::Error) -> Self { + Self::Secp256k1(error) + } +} + +impl From for Error { + fn from(error: bitcoin_hashes::hex::Error) -> Self { + Self::Hex(error) + } +} + + /// [`Event`] struct #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub struct Event { diff --git a/crates/nostr/src/event/tag.rs b/crates/nostr/src/event/tag.rs index f217a6f98..7d4142171 100644 --- a/crates/nostr/src/event/tag.rs +++ b/crates/nostr/src/event/tag.rs @@ -115,6 +115,18 @@ impl From for Error { } } +impl From for Error { + fn from(error: secp256k1::Error) -> Self { + Self::Secp256k1(error) + } +} + +impl From for Error { + fn from(error: bitcoin_hashes::hex::Error) -> Self { + Self::Hex(error) + } +} + /// Marker #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Marker { diff --git a/crates/nostr/src/event/unsigned.rs b/crates/nostr/src/event/unsigned.rs index 9a230be98..f55ea49ce 100644 --- a/crates/nostr/src/event/unsigned.rs +++ b/crates/nostr/src/event/unsigned.rs @@ -3,18 +3,18 @@ //! Unsigned Event -use core::fmt; #[cfg(feature = "alloc")] use alloc::{ string::{String, ToString}, vec::Vec, }; +use core::fmt; use secp256k1::schnorr::Signature; use secp256k1::{Message, XOnlyPublicKey}; use serde::{Deserialize, Serialize}; -use crate::{Event, EventId, Kind, Tag, Timestamp}; +use crate::{Event, EventId, Keys, Kind, Tag, Timestamp}; /// [`UnsignedEvent`] error #[derive(Debug)] @@ -66,6 +66,12 @@ impl From for Error { } } +impl From for Error { + fn from(error: secp256k1::Error) -> Self { + Self::Secp256k1(error) + } +} + /// [`UnsignedEvent`] struct #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub struct UnsignedEvent { diff --git a/crates/nostr/src/nips/nip26.rs b/crates/nostr/src/nips/nip26.rs index 48525769b..bf0736376 100644 --- a/crates/nostr/src/nips/nip26.rs +++ b/crates/nostr/src/nips/nip26.rs @@ -9,14 +9,13 @@ use core::fmt; use core::num::ParseIntError; use core::str::FromStr; -#[cfg(all(feature = "alloc", not(feature = "std")))] -use alloc::string::{String, ToString}; #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::format; #[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::string::{String, ToString}; +#[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::{vec, vec::Vec}; - use bitcoin_hashes::sha256::Hash as Sha256Hash; use bitcoin_hashes::Hash; use secp256k1::schnorr::Signature; diff --git a/crates/nostr/src/types/channel_id.rs b/crates/nostr/src/types/channel_id.rs index d4dcc87f7..8d06991c6 100644 --- a/crates/nostr/src/types/channel_id.rs +++ b/crates/nostr/src/types/channel_id.rs @@ -9,7 +9,7 @@ use core::str::FromStr; #[cfg(feature = "alloc")] use alloc::string::{String, ToString}; #[cfg(feature = "alloc")] -use alloc::{vec::Vec}; +use alloc::vec::Vec; #[cfg(feature = "nip19")] use bech32::{self, FromBase32, ToBase32, Variant}; From 1ddbbb2910272293d041c8e039c04e2e916dd146 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Thu, 6 Apr 2023 12:37:21 +0200 Subject: [PATCH 19/77] add no std test crate --- crates/ensure_no_std/Cargo.toml | 17 ++++++ crates/ensure_no_std/src/main.rs | 99 ++++++++++++++++++++++++++++++++ 2 files changed, 116 insertions(+) create mode 100644 crates/ensure_no_std/Cargo.toml create mode 100644 crates/ensure_no_std/src/main.rs diff --git a/crates/ensure_no_std/Cargo.toml b/crates/ensure_no_std/Cargo.toml new file mode 100644 index 000000000..acdc74f13 --- /dev/null +++ b/crates/ensure_no_std/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "ensure_no_std" +version = "0.7.0" +authors = ["Supercomputing Systems AG "] +license = "Apache-2.0" +edition = "2021" + +[dependencies] +libc = { version = "0.2.119", default-features = false } + +nostr = { path = "../nostr", default-features = false, features = ["alloc"] } +url_no_std = { package = "url", features = [ + "idna", + "alloc", + "core-error", + "core-net", +], path = "../../../rust-url/url", default-features = false } \ No newline at end of file diff --git a/crates/ensure_no_std/src/main.rs b/crates/ensure_no_std/src/main.rs new file mode 100644 index 000000000..fc1179fa4 --- /dev/null +++ b/crates/ensure_no_std/src/main.rs @@ -0,0 +1,99 @@ +#![feature(start, libc, lang_items)] +#![feature(alloc_error_handler)] +#![no_std] +#![no_main] + +// The libc crate allows importing functions from C. +extern crate libc; +use core::{ + alloc::{GlobalAlloc, Layout}, + cell::UnsafeCell, + panic::PanicInfo, + ptr::null_mut, + sync::atomic::{AtomicUsize, Ordering::SeqCst}, +}; + +// A list of C functions that are being imported +extern "C" { + pub fn printf(format: *const u8, ...) -> i32; +} + +// use nostr; +use url_no_std; + +#[no_mangle] +// The main function, with its input arguments ignored, and an exit status is returned +pub extern "C" fn main(_nargs: i32, _args: *const *const u8) -> i32 { + // Print "Hello, World" to stdout using printf + unsafe { + printf(b"Hello, World!\n" as *const u8); + } + + // Exit with a return status of 0. + 0 +} + +#[lang = "eh_personality"] +extern "C" fn eh_personality() {} + +#[panic_handler] +fn panic(_panic: &PanicInfo<'_>) -> ! { + loop {} +} + +#[alloc_error_handler] +fn foo(_: core::alloc::Layout) -> ! { + extern "C" { + fn abort() -> !; + } + unsafe { abort() } +} + +const ARENA_SIZE: usize = 128 * 1024; +const MAX_SUPPORTED_ALIGN: usize = 4096; +#[repr(C, align(4096))] // 4096 == MAX_SUPPORTED_ALIGN +struct SimpleAllocator { + arena: UnsafeCell<[u8; ARENA_SIZE]>, + remaining: AtomicUsize, // we allocate from the top, counting down +} + +#[global_allocator] +static ALLOCATOR: SimpleAllocator = SimpleAllocator { + arena: UnsafeCell::new([0x55; ARENA_SIZE]), + remaining: AtomicUsize::new(ARENA_SIZE), +}; +unsafe impl Sync for SimpleAllocator {} + +unsafe impl GlobalAlloc for SimpleAllocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + let size = layout.size(); + let align = layout.align(); + + // `Layout` contract forbids making a `Layout` with align=0, or align not power of 2. + // So we can safely use a mask to ensure alignment without worrying about UB. + let align_mask_to_round_down = !(align - 1); + + if align > MAX_SUPPORTED_ALIGN { + return null_mut() + } + + let mut allocated = 0; + if self + .remaining + .fetch_update(SeqCst, SeqCst, |mut remaining| { + if size > remaining { + return None + } + remaining -= size; + remaining &= align_mask_to_round_down; + allocated = remaining; + Some(remaining) + }) + .is_err() + { + return null_mut() + }; + (self.arena.get() as *mut u8).add(allocated) + } + unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {} +} \ No newline at end of file From 084354facc184ccb216ca5a6825f3de1775be4d2 Mon Sep 17 00:00:00 2001 From: Christian Langenbacher Date: Thu, 6 Apr 2023 13:16:10 +0200 Subject: [PATCH 20/77] make it work --- crates/ensure_no_std/Cargo.toml | 20 ++++++++++++++------ crates/ensure_no_std/src/main.rs | 5 +++-- crates/nostr/Cargo.toml | 3 --- crates/nostr/src/event/builder.rs | 6 ++++++ crates/nostr/src/event/mod.rs | 6 ++++++ crates/nostr/src/event/unsigned.rs | 6 ++++++ crates/nostr/src/message/mod.rs | 6 ++++++ 7 files changed, 41 insertions(+), 11 deletions(-) diff --git a/crates/ensure_no_std/Cargo.toml b/crates/ensure_no_std/Cargo.toml index acdc74f13..4a9331eb6 100644 --- a/crates/ensure_no_std/Cargo.toml +++ b/crates/ensure_no_std/Cargo.toml @@ -9,9 +9,17 @@ edition = "2021" libc = { version = "0.2.119", default-features = false } nostr = { path = "../nostr", default-features = false, features = ["alloc"] } -url_no_std = { package = "url", features = [ - "idna", - "alloc", - "core-error", - "core-net", -], path = "../../../rust-url/url", default-features = false } \ No newline at end of file + +#secp256k1 = { version = "0.24", default-features = false, features = ["alloc", "serde", "rand"]} + +#rand = { version = "0.8", features = [ +# "alloc", +# "getrandom", +#], default-features = false } + +#url_no_std = { package = "url", features = [ +# "idna", +# "alloc", +# "core-error", +# "core-net", +#], path = "../../../rust-url/url", default-features = false } \ No newline at end of file diff --git a/crates/ensure_no_std/src/main.rs b/crates/ensure_no_std/src/main.rs index fc1179fa4..0fbd8cec4 100644 --- a/crates/ensure_no_std/src/main.rs +++ b/crates/ensure_no_std/src/main.rs @@ -18,8 +18,9 @@ extern "C" { pub fn printf(format: *const u8, ...) -> i32; } -// use nostr; -use url_no_std; +use nostr; +// use url_no_std; +// use rand; #[no_mangle] // The main function, with its input arguments ignored, and an exit status is returned diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml index 15671f8be..07b67b6f0 100644 --- a/crates/nostr/Cargo.toml +++ b/crates/nostr/Cargo.toml @@ -23,7 +23,6 @@ std = [ "url", "secp256k1/global-context", "secp256k1/rand-std", - "secp256k1/serde", ] alloc = [ "dep:thiserror-core", @@ -40,7 +39,6 @@ alloc = [ "rand_core/getrandom", "rand/alloc", "rand/getrandom", - "rand/serde1", ] blocking = ["reqwest?/blocking"] vanity = ["nip19"] @@ -86,7 +84,6 @@ rand_core = { version = "0.6", features = [ rand = { version = "0.8", features = [ "alloc", "getrandom", - "serde1", ], default-features = false, optional = true } diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index a2d9e8310..d062a6e89 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -96,6 +96,12 @@ impl From for Error { } } +impl From for Error { + fn from(error: serde_json::Error) -> Self { + Self::Json(error) + } +} + /// [`Event`] builder #[derive(Debug, Clone, Eq, PartialEq)] pub struct EventBuilder { diff --git a/crates/nostr/src/event/mod.rs b/crates/nostr/src/event/mod.rs index 0226961c1..fa55ca831 100644 --- a/crates/nostr/src/event/mod.rs +++ b/crates/nostr/src/event/mod.rs @@ -90,6 +90,12 @@ impl From for Error { } } +impl From for Error { + fn from(error: serde_json::Error) -> Self { + Self::Json(error) + } +} + impl From for Error { fn from(error: secp256k1::Error) -> Self { Self::Secp256k1(error) diff --git a/crates/nostr/src/event/unsigned.rs b/crates/nostr/src/event/unsigned.rs index f55ea49ce..aac580f8e 100644 --- a/crates/nostr/src/event/unsigned.rs +++ b/crates/nostr/src/event/unsigned.rs @@ -72,6 +72,12 @@ impl From for Error { } } +impl From for Error { + fn from(error: serde_json::Error) -> Self { + Self::Json(error) + } +} + /// [`UnsignedEvent`] struct #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub struct UnsignedEvent { diff --git a/crates/nostr/src/message/mod.rs b/crates/nostr/src/message/mod.rs index e8dd87adf..6832f336d 100644 --- a/crates/nostr/src/message/mod.rs +++ b/crates/nostr/src/message/mod.rs @@ -47,3 +47,9 @@ impl From for MessageHandleError { Self::Event(e) } } + +impl From for MessageHandleError { + fn from(error: serde_json::Error) -> Self { + Self::Json(error) + } +} From 3add655cf047417af1827436252019d825308e70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Szil=C3=A1rd=20Parrag?= Date: Thu, 6 Apr 2023 10:03:15 +0000 Subject: [PATCH 21/77] ensure_no_std --- crates/ensure_no_std/Cargo.toml | 2 +- crates/ensure_no_std/src/main.rs | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/ensure_no_std/Cargo.toml b/crates/ensure_no_std/Cargo.toml index 4a9331eb6..41bf98afe 100644 --- a/crates/ensure_no_std/Cargo.toml +++ b/crates/ensure_no_std/Cargo.toml @@ -22,4 +22,4 @@ nostr = { path = "../nostr", default-features = false, features = ["alloc"] } # "alloc", # "core-error", # "core-net", -#], path = "../../../rust-url/url", default-features = false } \ No newline at end of file +#], path = "../../../rust-url/url", default-features = false } diff --git a/crates/ensure_no_std/src/main.rs b/crates/ensure_no_std/src/main.rs index 0fbd8cec4..664cf9999 100644 --- a/crates/ensure_no_std/src/main.rs +++ b/crates/ensure_no_std/src/main.rs @@ -75,7 +75,7 @@ unsafe impl GlobalAlloc for SimpleAllocator { let align_mask_to_round_down = !(align - 1); if align > MAX_SUPPORTED_ALIGN { - return null_mut() + return null_mut(); } let mut allocated = 0; @@ -83,7 +83,7 @@ unsafe impl GlobalAlloc for SimpleAllocator { .remaining .fetch_update(SeqCst, SeqCst, |mut remaining| { if size > remaining { - return None + return None; } remaining -= size; remaining &= align_mask_to_round_down; @@ -92,9 +92,9 @@ unsafe impl GlobalAlloc for SimpleAllocator { }) .is_err() { - return null_mut() + return null_mut(); }; (self.arena.get() as *mut u8).add(allocated) } unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {} -} \ No newline at end of file +} From 128b67e65d0534f4adf00c0eebbcda58a63a8375 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Szil=C3=A1rd=20Parrag?= Date: Tue, 11 Apr 2023 07:21:42 +0000 Subject: [PATCH 22/77] nostr: fix std only imports --- crates/nostr/src/event/unsigned.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/nostr/src/event/unsigned.rs b/crates/nostr/src/event/unsigned.rs index aac580f8e..bde8b53fb 100644 --- a/crates/nostr/src/event/unsigned.rs +++ b/crates/nostr/src/event/unsigned.rs @@ -14,7 +14,13 @@ use secp256k1::schnorr::Signature; use secp256k1::{Message, XOnlyPublicKey}; use serde::{Deserialize, Serialize}; -use crate::{Event, EventId, Keys, Kind, Tag, Timestamp}; +#[cfg(feature = "std")] +use secp256k1::Message; + +use crate::{Event, EventId, Kind, Tag, Timestamp}; + +#[cfg(feature = "std")] +use crate::Keys; /// [`UnsignedEvent`] error #[derive(Debug)] From a71817ecf22f3c3ee0186f8ec709b1b291fba35b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Szil=C3=A1rd=20Parrag?= Date: Tue, 11 Apr 2023 10:49:33 +0000 Subject: [PATCH 23/77] nostr: remove feature duplicates --- crates/nostr/Cargo.toml | 4 ---- 1 file changed, 4 deletions(-) diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml index 07b67b6f0..52d8a5b5d 100644 --- a/crates/nostr/Cargo.toml +++ b/crates/nostr/Cargo.toml @@ -15,9 +15,7 @@ keywords = ["nostr", "protocol", "sdk"] default = ["all-nips", "std"] std = [ "dep:thiserror", - "bitcoin_hashes/serde", "bitcoin_hashes/std", - "serde/derive", "serde/std", "serde_json/std", "url", @@ -27,8 +25,6 @@ std = [ alloc = [ "dep:thiserror-core", "bitcoin_hashes/alloc", - "bitcoin_hashes/serde", - "serde/derive", "serde/alloc", "serde_json/alloc", "url_no_std", From ee2443d8d18ad6c18b3f0ec8c150f645b818b269 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Szil=C3=A1rd=20Parrag?= Date: Tue, 11 Apr 2023 11:21:13 +0000 Subject: [PATCH 24/77] emergency backup --- crates/nostr/src/event/builder.rs | 19 +++++++++++++++---- crates/nostr/src/event/id.rs | 9 +++++---- crates/nostr/src/event/mod.rs | 12 ++++++++---- crates/nostr/src/event/tag.rs | 13 +++++++------ crates/nostr/src/key/mod.rs | 4 ++-- crates/nostr/src/lib.rs | 4 ++-- crates/nostr/src/message/subscription.rs | 15 +++++++-------- crates/nostr/src/types/channel_id.rs | 4 ++-- crates/nostr/src/types/time.rs | 12 ++++++++++-- 9 files changed, 58 insertions(+), 34 deletions(-) diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index d062a6e89..74df34a22 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -160,8 +160,13 @@ impl EventBuilder { pub fn to_pow_event(self, keys: &Keys, difficulty: u8) -> Result { #[cfg(target_arch = "wasm32")] use instant::Instant; - #[cfg(target_arch = "wasm32")] - self.to_pow_event_with_time_supplier_with_secp(self, keys, difficulty, Instant, SECP256K1); + #[cfg(all(feature = "std", not(target_arch = "wasm32")))] + use std::time::Instant; + + let now = Instant::now(); + + use secp256k1::SECP256K1; + self.to_pow_event_with_time_supplier_with_secp::(keys, difficulty, &now, SECP256K1) } /// Build POW [`Event`] using the given time supplier @@ -191,9 +196,9 @@ impl EventBuilder { #[cfg(target_arch = "wasm32")] use instant::Instant; #[cfg(all(not(target_arch = "wasm32"), feature = "std"))] - use std::{cmp, time::Instant}; + use std::cmp; - #[cfg(feature = "alloc")] + #[cfg(all(feature = "alloc", not(feature = "std")))] use core::cmp; /// Build unsigned POW [`Event`] @@ -228,8 +233,14 @@ impl EventBuilder { ); let message = Message::from_slice(id.as_bytes())?; + + #[cfg(all(feature = "alloc", not(feature = "std")))] let sig = keys.sign_schnorr_with_secp(&message, &secp)?; + #[cfg(all(feature = "std", not(feature = "alloc")))] + let sig = keys.sign_schnorr(&message)?; + + return self.to_event_internal(keys, created_at, id, sig); } diff --git a/crates/nostr/src/event/id.rs b/crates/nostr/src/event/id.rs index fa587155a..4b3da0906 100644 --- a/crates/nostr/src/event/id.rs +++ b/crates/nostr/src/event/id.rs @@ -6,11 +6,12 @@ use core::fmt; use core::str::FromStr; -#[cfg(feature = "alloc")] +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::str::FromStr; +#[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::string::{String, ToString}; -#[cfg(feature = "alloc")] -use alloc::vec; - +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::{fmt, vec}; use bitcoin_hashes::sha256::Hash as Sha256Hash; use bitcoin_hashes::Hash; diff --git a/crates/nostr/src/event/mod.rs b/crates/nostr/src/event/mod.rs index fa55ca831..401be1619 100644 --- a/crates/nostr/src/event/mod.rs +++ b/crates/nostr/src/event/mod.rs @@ -7,14 +7,18 @@ use core::fmt; use core::str::FromStr; -#[cfg(feature = "alloc")] +#[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::{string::{String, ToString}; -#[cfg(feature = "alloc")] +#[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::vec::Vec; + use secp256k1::schnorr::Signature; -use secp256k1::{Message, XOnlyPublicKey}; -#[cfg(feature = "alloc")] +#[cfg(all(feature = "alloc", not(feature = "std")))] +use secp256k1::Message; + +use secp256k1::XOnlyPublicKey; +#[cfg(all(feature = "alloc", not(feature = "std")))] use secp256k1::{Secp256k1, Verification}; use serde::{Deserialize, Serialize}; use serde_json::Value; diff --git a/crates/nostr/src/event/tag.rs b/crates/nostr/src/event/tag.rs index 7d4142171..7a6a08e68 100644 --- a/crates/nostr/src/event/tag.rs +++ b/crates/nostr/src/event/tag.rs @@ -2,16 +2,17 @@ // Distributed under the MIT software license //! Tag +use core::fmt; + +use core::num::ParseIntError; +use core::str::FromStr; -#[cfg(feature = "alloc")] +#[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::format; -#[cfg(feature = "alloc")] +#[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::string::{String, ToString}; -#[cfg(feature = "alloc")] +#[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::{vec, vec::Vec}; -use core::fmt; -use core::num::ParseIntError; -use core::str::FromStr; use secp256k1::schnorr::Signature; use secp256k1::XOnlyPublicKey; diff --git a/crates/nostr/src/key/mod.rs b/crates/nostr/src/key/mod.rs index 9f29095d7..e2cc5c1f1 100644 --- a/crates/nostr/src/key/mod.rs +++ b/crates/nostr/src/key/mod.rs @@ -10,7 +10,7 @@ use core::fmt; #[cfg(feature = "nip19")] use core::str::FromStr; -#[cfg(feature = "alloc")] +#[cfg(all(feature = "alloc", not(feature = "std")))] use rand_core::OsRng; #[cfg(feature = "std")] use secp256k1::rand::rngs::OsRng; @@ -20,7 +20,7 @@ use secp256k1::Secp256k1; #[cfg(feature = "alloc")] use secp256k1::Signing; -#[cfg(feature = "alloc")] +#[cfg(all(feature = "alloc", not(feature = "std")))] use rand::Rng; #[cfg(feature = "std")] use secp256k1::rand::Rng; diff --git a/crates/nostr/src/lib.rs b/crates/nostr/src/lib.rs index d11434d88..cb60d2507 100644 --- a/crates/nostr/src/lib.rs +++ b/crates/nostr/src/lib.rs @@ -38,7 +38,7 @@ pub use serde_json; #[cfg(feature = "std")] pub use url; -#[cfg(feature = "alloc")] +#[cfg(all(feature = "alloc", not(feature = "std")))] extern crate url_no_std as url; pub use url::Url; @@ -59,5 +59,5 @@ pub use self::types::{ChannelId, Contact, Entity, Metadata, Profile, Timestamp, #[cfg(feature = "std")] pub type Result> = std::result::Result; /// Result -#[cfg(feature = "alloc")] +#[cfg(all(feature = "alloc", not(feature = "std")))] pub type Result> = core::result::Result; diff --git a/crates/nostr/src/message/subscription.rs b/crates/nostr/src/message/subscription.rs index f0c65fcad..4b4329988 100644 --- a/crates/nostr/src/message/subscription.rs +++ b/crates/nostr/src/message/subscription.rs @@ -7,17 +7,16 @@ #![allow(missing_docs)] use core::fmt; -#[cfg(feature = "alloc")] -use alloc::{ - fmt, - string::{String, ToString}, - vec, - vec::Vec, -}; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::fmt; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::string::{String, ToString}; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::{vec, vec::Vec}; use bitcoin_hashes::sha256::Hash as Sha256Hash; use bitcoin_hashes::Hash; -#[cfg(feature = "alloc")] +#[cfg(all(feature = "alloc", not(feature = "std")))] use rand_core::{OsRng, RngCore}; #[cfg(feature = "std")] use secp256k1::rand::{rngs::OsRng, RngCore}; diff --git a/crates/nostr/src/types/channel_id.rs b/crates/nostr/src/types/channel_id.rs index 8d06991c6..010fb6302 100644 --- a/crates/nostr/src/types/channel_id.rs +++ b/crates/nostr/src/types/channel_id.rs @@ -6,9 +6,9 @@ use core::fmt; use core::str::FromStr; -#[cfg(feature = "alloc")] +#[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::string::{String, ToString}; -#[cfg(feature = "alloc")] +#[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::vec::Vec; #[cfg(feature = "nip19")] diff --git a/crates/nostr/src/types/time.rs b/crates/nostr/src/types/time.rs index fd72cfaf0..6bca7c72a 100644 --- a/crates/nostr/src/types/time.rs +++ b/crates/nostr/src/types/time.rs @@ -13,9 +13,9 @@ use std::{ time::{SystemTime, UNIX_EPOCH}, }; -#[cfg(feature = "alloc")] +#[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::fmt; -#[cfg(feature = "alloc")] +#[cfg(all(feature = "alloc", not(feature = "std")))] use core::num; #[cfg(target_arch = "wasm32")] @@ -82,14 +82,22 @@ use std::time::Instant; #[cfg(all(not(target_arch = "wasm32"), feature = "std"))] impl TimeSupplier for Instant { type Now = Instant; + type StartingPoint = std::time::SystemTime; fn now(&self) -> Self::Now { Instant::now() } + fn starting_point(&self) -> Self::StartingPoint { + std::time::UNIX_EPOCH + } + fn elapsed_since(&self, now: Self::Now, since: Self::Now) -> Duration { now - since } + fn elapsed_duration(&self, now: Self::Now, since: Self::StartingPoint) -> Duration { + now - since + } fn as_i64(&self, duration: Duration) -> i64 { duration.as_millis() as i64 From 69d3d2e689e45dfaf96170f9d5c5ca2b5f633aa2 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Tue, 11 Apr 2023 16:41:21 +0200 Subject: [PATCH 25/77] nostr: std feature fixed --- crates/nostr/src/event/builder.rs | 7 +++-- crates/nostr/src/event/mod.rs | 4 +-- crates/nostr/src/types/time.rs | 45 ++++++++++++++++++++++--------- 3 files changed, 37 insertions(+), 19 deletions(-) diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index 74df34a22..83c516350 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -188,7 +188,7 @@ impl EventBuilder { keys: &Keys, difficulty: u8, time_supplier: &T, - secp: &Secp256k1, + _secp: &Secp256k1, ) -> Result where T: TimeSupplier, @@ -216,8 +216,7 @@ impl EventBuilder { tags.push(Tag::POW { nonce, difficulty }); let new_now = time_supplier.now(); - let starting_point = time_supplier.starting_point(); - let created_at = time_supplier.elapsed_duration(new_now.clone(), starting_point); + let created_at = time_supplier.duration_since_starting_point(now.clone()); let created_at = time_supplier.to_timestamp(created_at); let id = EventId::new(&pubkey, created_at, &self.kind, &tags, &self.content); @@ -235,7 +234,7 @@ impl EventBuilder { let message = Message::from_slice(id.as_bytes())?; #[cfg(all(feature = "alloc", not(feature = "std")))] - let sig = keys.sign_schnorr_with_secp(&message, &secp)?; + let sig = keys.sign_schnorr_with_secp(&message, &_secp)?; #[cfg(all(feature = "std", not(feature = "alloc")))] let sig = keys.sign_schnorr(&message)?; diff --git a/crates/nostr/src/event/mod.rs b/crates/nostr/src/event/mod.rs index 401be1619..91546f3c5 100644 --- a/crates/nostr/src/event/mod.rs +++ b/crates/nostr/src/event/mod.rs @@ -14,11 +14,9 @@ use alloc::vec::Vec; use secp256k1::schnorr::Signature; -#[cfg(all(feature = "alloc", not(feature = "std")))] use secp256k1::Message; use secp256k1::XOnlyPublicKey; -#[cfg(all(feature = "alloc", not(feature = "std")))] use secp256k1::{Secp256k1, Verification}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -144,7 +142,7 @@ impl Event { } /// Verify Event - #[cfg(not(feature = "std"))] + //#[cfg(not(feature = "std"))] pub fn verify_with_context(&self, secp: &Secp256k1) -> Result<(), Error> { let id = EventId::new( &self.pubkey, diff --git a/crates/nostr/src/types/time.rs b/crates/nostr/src/types/time.rs index 6bca7c72a..7258c29d0 100644 --- a/crates/nostr/src/types/time.rs +++ b/crates/nostr/src/types/time.rs @@ -30,18 +30,25 @@ pub trait TimeSupplier { /// The current time from the specified `TimeSupplier` type Now: Clone; /// The starting point for the specified `TimeSupplier` - type StartingPoint; + type StartingPoint: Clone; /// Get the current time as the associated `Now` type - fn now(&self) -> Self::Now; + fn instant_now(&self) -> Self::Now; + /// Get the current time as the associated `StartingPoint` type + fn now(&self) -> Self::StartingPoint; + /// Get a duration since the StartingPoint. + fn duration_since_starting_point(&self, now: Self::StartingPoint) -> Duration; /// Get the starting point from the specified `TimeSupplier` fn starting_point(&self) -> Self::StartingPoint; /// Get the elapsed time as `Duration` starting from `since` to `now` - fn elapsed_since(&self, now: Self::Now, since: Self::Now) -> Duration; + fn elapsed_instant_since(&self, now: Self::Now, since: Self::Now) -> Duration; /// Get the elapsed time as `Duration` starting from `since` to `now` - /// This is the specialised case for handling the `StartingPoint` in case its type is different - /// than the `Now` type. - fn elapsed_duration(&self, now: Self::Now, since: Self::StartingPoint) -> Duration; + fn elapsed_since(&self, now: Self::StartingPoint, since: Self::StartingPoint) -> Duration; + + // /// Get the elapsed time as `Duration` starting from `since` to `now` + // /// This is the specialised case for handling the `StartingPoint` in case its type is different + // /// than the `Now` type. + // fn elapsed_duration(&self, now: Self::Now, since: Self::StartingPoint) -> Duration; /// Convert the specified `Duration` to `i64` fn as_i64(&self, duration: Duration) -> i64; @@ -56,7 +63,7 @@ impl TimeSupplier for InstantWasm32 { type Now = InstantWasm32; type StartingPoint = std::time::SystemTime; - fn now(&self) -> Self::Now { + fn instant_now(&self) -> Self::Now { InstantWasm32::now() } @@ -84,27 +91,41 @@ impl TimeSupplier for Instant { type Now = Instant; type StartingPoint = std::time::SystemTime; - fn now(&self) -> Self::Now { + fn now(&self) -> Self::StartingPoint { + SystemTime::now() + } + + fn instant_now(&self) -> Self::Now { Instant::now() } + fn duration_since_starting_point(&self, now: Self::StartingPoint) -> Duration { + now.duration_since(self.starting_point()).expect("duration_since panicked") + } + fn starting_point(&self) -> Self::StartingPoint { std::time::UNIX_EPOCH } - fn elapsed_since(&self, now: Self::Now, since: Self::Now) -> Duration { + fn elapsed_instant_since(&self, now: Self::Now, since: Self::Now) -> Duration { now - since } - fn elapsed_duration(&self, now: Self::Now, since: Self::StartingPoint) -> Duration { - now - since + + fn elapsed_since(&self, now: Self::StartingPoint, since: Self::StartingPoint) -> Duration { + now.duration_since(since).expect("duration_since panicked") } +// fn elapsed_duration(&self, now: Self::Now, since: Self::StartingPoint) -> Duration { +// let dur = since.duration_since(self.starting_point).expect("Clock may have gone backwards"); +// now - since +// } +// fn as_i64(&self, duration: Duration) -> i64 { duration.as_millis() as i64 } fn to_timestamp(&self, duration: Duration) -> Timestamp { - Timestamp(duration.as_i64()) + Timestamp(self.as_i64(duration)) } } From 92bb83d19d192dbb719cb769a00d980ec1399f0d Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Wed, 12 Apr 2023 09:17:43 +0200 Subject: [PATCH 26/77] nostr: followup for TimeSupplier changes --- crates/nostr/src/types/time.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/nostr/src/types/time.rs b/crates/nostr/src/types/time.rs index 7258c29d0..e6ca01af5 100644 --- a/crates/nostr/src/types/time.rs +++ b/crates/nostr/src/types/time.rs @@ -152,7 +152,7 @@ impl Timestamp { { let now = time_supplier.now(); let starting_point = time_supplier.starting_point(); - let duration = time_supplier.elapsed_duration(now, starting_point); + let duration = time_supplier.elapsed_since(now, starting_point); time_supplier.to_timestamp(duration) } From 703581fbdb85a6618cfae3b1408e500a0dee7e11 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Wed, 12 Apr 2023 10:39:02 +0200 Subject: [PATCH 27/77] nostr: remove duplicate feature --- crates/nostr/Cargo.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml index 52d8a5b5d..8302c6050 100644 --- a/crates/nostr/Cargo.toml +++ b/crates/nostr/Cargo.toml @@ -29,7 +29,6 @@ alloc = [ "serde_json/alloc", "url_no_std", "secp256k1/alloc", - "secp256k1/serde", "secp256k1/rand", "rand_core/alloc", "rand_core/getrandom", From 0b0f6abaf0d0716efc27ab739d759cbbb4b8ca47 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Wed, 12 Apr 2023 15:10:04 +0200 Subject: [PATCH 28/77] nostr: switch to rust-url no_std PR --- crates/nostr/Cargo.toml | 5 +---- crates/nostr/src/event/tag.rs | 6 ++++++ 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml index 8302c6050..c3a2db963 100644 --- a/crates/nostr/Cargo.toml +++ b/crates/nostr/Cargo.toml @@ -65,11 +65,8 @@ serde_json = { version = "1.0", optional = true, default-features = false } url = { version = "2", features = ["serde"], optional = true } url_no_std = { package = "url", features = [ - "idna", "alloc", - "core-error", - "core-net", -], path = "../../../rust-url/url", optional = true, default-features = false } +], git = "https://github.com/domenukk/rust-url", branch = "no_std", optional = true, default-features = false } rand_core = { version = "0.6", features = [ "alloc", diff --git a/crates/nostr/src/event/tag.rs b/crates/nostr/src/event/tag.rs index 7a6a08e68..392fede89 100644 --- a/crates/nostr/src/event/tag.rs +++ b/crates/nostr/src/event/tag.rs @@ -128,6 +128,12 @@ impl From for Error { } } +impl From for Error { + fn from(error: url::ParseError) -> Self { + Self::Url(error) + } +} + /// Marker #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Marker { From 64913a5afb0a8da48bae2887afc2d17082132a67 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 13 Apr 2023 08:14:30 +0200 Subject: [PATCH 29/77] nostr: nip19 port to no_std --- crates/nostr/Cargo.toml | 9 ++++----- crates/nostr/src/key/mod.rs | 26 +++++++++++++++++++++++++- crates/nostr/src/nips/nip19.rs | 22 ++++++++++++++++++++++ crates/nostr/src/prelude.rs | 4 ++-- crates/nostr/src/types/channel_id.rs | 3 +++ crates/nostr/src/types/profile.rs | 9 +++++++-- 6 files changed, 63 insertions(+), 10 deletions(-) diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml index c3a2db963..c920a39c7 100644 --- a/crates/nostr/Cargo.toml +++ b/crates/nostr/Cargo.toml @@ -43,14 +43,15 @@ nip04 = ["dep:aes", "dep:base64", "dep:cbc"] nip05 = ["dep:reqwest"] nip06 = ["dep:bip39", "dep:bitcoin"] nip11 = ["dep:reqwest"] -nip19 = ["dep:bech32"] +nip19 = ["bech32/alloc"] +nip19-std = ["bech32/std"] nip21 = ["nip19"] nip46 = ["nip04"] [dependencies] aes = { version = "0.8", optional = true } base64 = { version = "0.21", optional = true } -bech32 = { version = "0.9", optional = true } +bech32 = { git = "https://github.com/rust-bitcoin/rust-bech32", rev = "360af7e0647fa94bce892fa69f31c0ef02452b63", optional = true, default-features = false } bip39 = { version = "2.0", optional = true } bitcoin = { version = "0.30", optional = true } bitcoin_hashes = { version = "0.12", features = ["serde"] } @@ -71,7 +72,7 @@ url_no_std = { package = "url", features = [ rand_core = { version = "0.6", features = [ "alloc", "getrandom", -], optional = true, default-features = false} +], optional = true, default-features = false } rand = { version = "0.8", features = [ "alloc", @@ -79,8 +80,6 @@ rand = { version = "0.8", features = [ ], default-features = false, optional = true } - - #[target.'cfg(target_arch = "wasm32")'.dependencies] #getrandom = { version = "0.2", features = ["js"] } #instant = { version = "0.1", features = ["wasm-bindgen", "inaccurate"] } diff --git a/crates/nostr/src/key/mod.rs b/crates/nostr/src/key/mod.rs index e2cc5c1f1..a19ac0224 100644 --- a/crates/nostr/src/key/mod.rs +++ b/crates/nostr/src/key/mod.rs @@ -76,8 +76,15 @@ impl From for Error { pub trait FromSkStr: Sized { /// Error type Err; + #[cfg(all(feature = "std", not(feature = "alloc")))] /// Init [`Keys`] from `hex` or `bech32` secret key string fn from_sk_str(secret_key: &str) -> Result; + #[cfg(all(feature = "alloc", not(feature = "std")))] + /// Init [`Keys`] from `hex` or `bech32` secret key string + fn from_sk_str( + secret_key: &str, + secp: &Secp256k1, + ) -> Result; } /// Trait for [`Keys`] @@ -270,7 +277,7 @@ impl Keys { } } -#[cfg(feature = "nip19")] +#[cfg(all(feature = "std", feature = "nip19", not(feature = "alloc")))] impl FromSkStr for Keys { type Err = Error; @@ -285,7 +292,24 @@ impl FromSkStr for Keys { } } } +#[cfg(all(feature = "alloc", feature = "nip19", not(feature = "std")))] +impl FromSkStr for Keys { + type Err = Error; + /// Init [`Keys`] from `hex` or `bech32` secret key + fn from_sk_str( + secret_key: &str, + secp: &Secp256k1, + ) -> Result { + match SecretKey::from_str(secret_key) { + Ok(secret_key) => Ok(Self::new_with_secp(secret_key, &secp)), + Err(_) => match SecretKey::from_bech32(secret_key) { + Ok(secret_key) => Ok(Self::new_with_secp(secret_key, &secp)), + Err(_) => Err(Error::InvalidSecretKey), + }, + } + } +} #[cfg(feature = "nip19")] impl FromPkStr for Keys { type Err = Error; diff --git a/crates/nostr/src/nips/nip19.rs b/crates/nostr/src/nips/nip19.rs index 3f4bc89ac..bb485e1fa 100644 --- a/crates/nostr/src/nips/nip19.rs +++ b/crates/nostr/src/nips/nip19.rs @@ -7,7 +7,12 @@ #![allow(missing_docs)] +#[cfg(not(feature = "std"))] +use alloc::string::{FromUtf8Error, ToString}; +#[cfg(not(feature = "std"))] +use alloc::vec::{self, Vec}; use core::fmt; +#[cfg(feature = "std")] use std::string::FromUtf8Error; use bech32::{self, FromBase32, ToBase32, Variant}; @@ -101,6 +106,23 @@ impl From for Error { Self::EventId(e) } } +impl From for Error { + fn from(error: secp256k1::Error) -> Self { + Self::Secp256k1(error) + } +} + +impl From for Error { + fn from(error: bitcoin_hashes::Error) -> Self { + Self::Hash(error) + } +} + +impl From for Error { + fn from(error: bech32::Error) -> Self { + Self::Bech32(error) + } +} pub trait FromBech32: Sized { type Err; diff --git a/crates/nostr/src/prelude.rs b/crates/nostr/src/prelude.rs index 3820c8d47..df39e11e1 100644 --- a/crates/nostr/src/prelude.rs +++ b/crates/nostr/src/prelude.rs @@ -6,7 +6,7 @@ // External crates pub use ::url::*; #[cfg(feature = "nip19")] -pub use bech32::*; +pub use bech32; #[cfg(feature = "nip06")] pub use bip39::*; #[cfg(feature = "nip06")] @@ -41,7 +41,7 @@ pub use crate::nips::nip06::*; pub use crate::nips::nip11::*; pub use crate::nips::nip13::*; #[cfg(feature = "nip19")] -pub use crate::nips::nip19::*; +pub use crate::nips::nip19; pub use crate::nips::nip26::*; #[cfg(feature = "nip46")] pub use crate::nips::nip46::*; diff --git a/crates/nostr/src/types/channel_id.rs b/crates/nostr/src/types/channel_id.rs index 010fb6302..9fdb4cc27 100644 --- a/crates/nostr/src/types/channel_id.rs +++ b/crates/nostr/src/types/channel_id.rs @@ -159,6 +159,9 @@ impl FromBech32 for ChannelId { } } +#[cfg(all(feature = "nip19", feature = "alloc", not(feature = "std")))] +use alloc::vec; + #[cfg(feature = "nip19")] impl ToBech32 for ChannelId { type Err = Bech32Error; diff --git a/crates/nostr/src/types/profile.rs b/crates/nostr/src/types/profile.rs index 79188e651..5776695b6 100644 --- a/crates/nostr/src/types/profile.rs +++ b/crates/nostr/src/types/profile.rs @@ -3,16 +3,19 @@ //! Profile +#[cfg(all(feature = "nip19", feature = "alloc"))] +use alloc::string::ToString; #[cfg(feature = "nip19")] use bech32::{self, FromBase32, ToBase32, Variant}; use secp256k1::XOnlyPublicKey; -use serde::{Deserialize, Serialize}; #[cfg(feature = "nip19")] use crate::nips::nip19::{Error, FromBech32, ToBech32, PREFIX_BECH32_PROFILE, RELAY, SPECIAL}; #[cfg(feature = "alloc")] -use alloc::{string::String, vec::Vec}; +use alloc::string::String; +#[cfg(feature = "alloc")] +use alloc::vec::Vec; /// Profile #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] @@ -83,6 +86,8 @@ impl FromBech32 for Profile { } } +#[cfg(all(feature = "nip19", feature = "alloc"))] +use alloc::vec; #[cfg(feature = "nip19")] impl ToBech32 for Profile { type Err = Error; From 77c56f6f736a48ab2ba11dbd80b48864b403e0c4 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Tue, 18 Apr 2023 12:58:22 +0200 Subject: [PATCH 30/77] nostr: switch rust-url to personal fork for easier testing --- crates/nostr/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml index c920a39c7..52e3e9e4b 100644 --- a/crates/nostr/Cargo.toml +++ b/crates/nostr/Cargo.toml @@ -67,7 +67,7 @@ serde_json = { version = "1.0", optional = true, default-features = false } url = { version = "2", features = ["serde"], optional = true } url_no_std = { package = "url", features = [ "alloc", -], git = "https://github.com/domenukk/rust-url", branch = "no_std", optional = true, default-features = false } +], git = "https://github.com/OverOrion/rust-url", branch = "no_std_net", optional = true, default-features = false } rand_core = { version = "0.6", features = [ "alloc", From 837f0e01cc023a73022f0f341fcc23bf6cef04a9 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Tue, 18 Apr 2023 13:13:58 +0200 Subject: [PATCH 31/77] nostr: remove commented out code which was not used --- crates/nostr/src/event/mod.rs | 2 -- crates/nostr/src/types/time.rs | 14 ++------------ 2 files changed, 2 insertions(+), 14 deletions(-) diff --git a/crates/nostr/src/event/mod.rs b/crates/nostr/src/event/mod.rs index 91546f3c5..411702537 100644 --- a/crates/nostr/src/event/mod.rs +++ b/crates/nostr/src/event/mod.rs @@ -110,7 +110,6 @@ impl From for Error { } } - /// [`Event`] struct #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub struct Event { @@ -142,7 +141,6 @@ impl Event { } /// Verify Event - //#[cfg(not(feature = "std"))] pub fn verify_with_context(&self, secp: &Secp256k1) -> Result<(), Error> { let id = EventId::new( &self.pubkey, diff --git a/crates/nostr/src/types/time.rs b/crates/nostr/src/types/time.rs index e6ca01af5..dc782990b 100644 --- a/crates/nostr/src/types/time.rs +++ b/crates/nostr/src/types/time.rs @@ -44,12 +44,6 @@ pub trait TimeSupplier { fn elapsed_instant_since(&self, now: Self::Now, since: Self::Now) -> Duration; /// Get the elapsed time as `Duration` starting from `since` to `now` fn elapsed_since(&self, now: Self::StartingPoint, since: Self::StartingPoint) -> Duration; - - // /// Get the elapsed time as `Duration` starting from `since` to `now` - // /// This is the specialised case for handling the `StartingPoint` in case its type is different - // /// than the `Now` type. - // fn elapsed_duration(&self, now: Self::Now, since: Self::StartingPoint) -> Duration; - /// Convert the specified `Duration` to `i64` fn as_i64(&self, duration: Duration) -> i64; /// Convert the specified `Duration` to `Timestamp` @@ -100,7 +94,8 @@ impl TimeSupplier for Instant { } fn duration_since_starting_point(&self, now: Self::StartingPoint) -> Duration { - now.duration_since(self.starting_point()).expect("duration_since panicked") + now.duration_since(self.starting_point()) + .expect("duration_since panicked") } fn starting_point(&self) -> Self::StartingPoint { @@ -115,11 +110,6 @@ impl TimeSupplier for Instant { now.duration_since(since).expect("duration_since panicked") } -// fn elapsed_duration(&self, now: Self::Now, since: Self::StartingPoint) -> Duration { -// let dur = since.duration_since(self.starting_point).expect("Clock may have gone backwards"); -// now - since -// } -// fn as_i64(&self, duration: Duration) -> i64 { duration.as_millis() as i64 } From 38b4b1db2a438ce6b4748f4c53bc19b30ecc3d1d Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Tue, 18 Apr 2023 13:15:09 +0200 Subject: [PATCH 32/77] nostr: remove commented out wildcard exports as they interfered with each other --- crates/nostr/src/prelude.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/crates/nostr/src/prelude.rs b/crates/nostr/src/prelude.rs index df39e11e1..4ab26fe8c 100644 --- a/crates/nostr/src/prelude.rs +++ b/crates/nostr/src/prelude.rs @@ -9,9 +9,6 @@ pub use ::url::*; pub use bech32; #[cfg(feature = "nip06")] pub use bip39::*; -#[cfg(feature = "nip06")] -//pub use bitcoin::*; -//pub use bitcoin_hashes::*; pub use secp256k1::*; //pub use serde_json::*; From 5fb529289430f7fad05297ba04679dc1657112eb Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 20 Apr 2023 09:52:57 +0200 Subject: [PATCH 33/77] ensure_no_std: remove commented out dependencies --- crates/ensure_no_std/Cargo.toml | 14 -------------- crates/ensure_no_std/src/main.rs | 2 -- 2 files changed, 16 deletions(-) diff --git a/crates/ensure_no_std/Cargo.toml b/crates/ensure_no_std/Cargo.toml index 41bf98afe..13ac2d2c8 100644 --- a/crates/ensure_no_std/Cargo.toml +++ b/crates/ensure_no_std/Cargo.toml @@ -9,17 +9,3 @@ edition = "2021" libc = { version = "0.2.119", default-features = false } nostr = { path = "../nostr", default-features = false, features = ["alloc"] } - -#secp256k1 = { version = "0.24", default-features = false, features = ["alloc", "serde", "rand"]} - -#rand = { version = "0.8", features = [ -# "alloc", -# "getrandom", -#], default-features = false } - -#url_no_std = { package = "url", features = [ -# "idna", -# "alloc", -# "core-error", -# "core-net", -#], path = "../../../rust-url/url", default-features = false } diff --git a/crates/ensure_no_std/src/main.rs b/crates/ensure_no_std/src/main.rs index 664cf9999..cc7393cac 100644 --- a/crates/ensure_no_std/src/main.rs +++ b/crates/ensure_no_std/src/main.rs @@ -19,8 +19,6 @@ extern "C" { } use nostr; -// use url_no_std; -// use rand; #[no_mangle] // The main function, with its input arguments ignored, and an exit status is returned From 565d3c65c857909353afad65d2129dcb29c450f7 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 20 Apr 2023 10:28:39 +0200 Subject: [PATCH 34/77] nostr: fix prelude wildcard import --- crates/nostr/src/prelude.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/nostr/src/prelude.rs b/crates/nostr/src/prelude.rs index 4ab26fe8c..4f0efffdd 100644 --- a/crates/nostr/src/prelude.rs +++ b/crates/nostr/src/prelude.rs @@ -9,8 +9,7 @@ pub use ::url::*; pub use bech32; #[cfg(feature = "nip06")] pub use bip39::*; -pub use secp256k1::*; -//pub use serde_json::*; +pub use secp256k1; // Internal modules pub use crate::event::builder::*; From 4ae7a3e1eff05b1230999de57b1ec0387acbb3e2 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 20 Apr 2023 10:29:05 +0200 Subject: [PATCH 35/77] nostr: add back wasm32 dependencies --- crates/nostr/Cargo.toml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml index 52e3e9e4b..ab3a8c920 100644 --- a/crates/nostr/Cargo.toml +++ b/crates/nostr/Cargo.toml @@ -80,9 +80,9 @@ rand = { version = "0.8", features = [ ], default-features = false, optional = true } -#[target.'cfg(target_arch = "wasm32")'.dependencies] -#getrandom = { version = "0.2", features = ["js"] } -#instant = { version = "0.1", features = ["wasm-bindgen", "inaccurate"] } +[target.'cfg(target_arch = "wasm32")'.dependencies] +getrandom = { version = "0.2", features = ["js"] } +instant = { version = "0.1", features = ["wasm-bindgen", "inaccurate"] } [dev-dependencies] csv = "1.1.5" From 3215e574db766b2d8cd58019abc89de77e96b51d Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 20 Apr 2023 10:34:32 +0200 Subject: [PATCH 36/77] ensure_no_std: add link to GlobalAlloc implementation source --- crates/ensure_no_std/src/main.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ensure_no_std/src/main.rs b/crates/ensure_no_std/src/main.rs index cc7393cac..a244cb217 100644 --- a/crates/ensure_no_std/src/main.rs +++ b/crates/ensure_no_std/src/main.rs @@ -63,6 +63,7 @@ static ALLOCATOR: SimpleAllocator = SimpleAllocator { }; unsafe impl Sync for SimpleAllocator {} +// From https://doc.rust-lang.org/core/alloc/trait.GlobalAlloc.html unsafe impl GlobalAlloc for SimpleAllocator { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { let size = layout.size(); From 12e475976c4d096f9e93c50392cd15b15dbe8ce4 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 20 Apr 2023 13:34:29 +0200 Subject: [PATCH 37/77] fix rebase issues --- crates/nostr/src/event/builder.rs | 42 ++++++++++++++++++++++++++----- crates/nostr/src/event/tag.rs | 1 - crates/nostr/src/key/mod.rs | 1 + crates/nostr/src/nips/nip26.rs | 4 +-- 4 files changed, 39 insertions(+), 9 deletions(-) diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index 83c516350..49f60a019 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -7,6 +7,7 @@ use core::fmt; #[cfg(feature = "alloc")] use alloc::{ string::{String, ToString}, + vec, vec::Vec, }; @@ -127,6 +128,12 @@ impl EventBuilder { #[cfg(feature = "std")] pub fn to_event(self, keys: &Keys) -> Result { let pubkey: XOnlyPublicKey = keys.public_key(); + Ok(self.to_unsigned_event(pubkey).sign(keys)?) + } + + /// Build [`UnsignedEvent`] + #[cfg(feature = "std")] + pub fn to_unsigned_event(self, pubkey: XOnlyPublicKey) -> UnsignedEvent { let created_at: Timestamp = Timestamp::now(); let id = EventId::new(&pubkey, created_at, &self.kind, &self.tags, &self.content); let message = Message::from_slice(id.as_bytes())?; @@ -145,19 +152,42 @@ impl EventBuilder { ) -> Result { let pubkey: XOnlyPublicKey = keys.public_key(); let id = EventId::new(&pubkey, created_at, &self.kind, &self.tags, &self.content); - UnsignedEvent { + let message = Message::from_slice(id.as_bytes())?; + let signature = keys.sign_schnorr_with_secp(&message, secp)?; + + Self::to_event_internal(self, keys, created_at, id, signature) + } + + fn to_event_internal( + self, + keys: &Keys, + created_at: Timestamp, + id: EventId, + sig: Signature, + ) -> Result { + let pubkey: XOnlyPublicKey = keys.public_key(); + + Ok(Event { id, pubkey, created_at, kind: self.kind, tags: self.tags, content: self.content, - } + sig, + }) } /// Build POW [`Event`] #[cfg(feature = "std")] pub fn to_pow_event(self, keys: &Keys, difficulty: u8) -> Result { + let pubkey: XOnlyPublicKey = keys.public_key(); + Ok(self.to_unsigned_pow_event(pubkey, difficulty).sign(keys)?) + } + + /// Build unsigned POW [`Event`] + #[cfg(feature = "std")] + pub fn to_unsigned_pow_event(self, pubkey: XOnlyPublicKey, difficulty: u8) -> UnsignedEvent { #[cfg(target_arch = "wasm32")] use instant::Instant; #[cfg(all(feature = "std", not(target_arch = "wasm32")))] @@ -166,7 +196,9 @@ impl EventBuilder { let now = Instant::now(); use secp256k1::SECP256K1; - self.to_pow_event_with_time_supplier_with_secp::(keys, difficulty, &now, SECP256K1) + self.to_pow_event_with_time_supplier_with_secp::( + keys, difficulty, &now, SECP256K1, + ) } /// Build POW [`Event`] using the given time supplier @@ -201,8 +233,6 @@ impl EventBuilder { #[cfg(all(feature = "alloc", not(feature = "std")))] use core::cmp; - /// Build unsigned POW [`Event`] - pub fn to_unsigned_pow_event(self, pubkey: XOnlyPublicKey, difficulty: u8) -> UnsignedEvent { let mut nonce: u128 = 0; let mut tags: Vec = self.tags.clone(); @@ -239,7 +269,6 @@ impl EventBuilder { #[cfg(all(feature = "std", not(feature = "alloc")))] let sig = keys.sign_schnorr(&message)?; - return self.to_event_internal(keys, created_at, id, sig); } @@ -290,6 +319,7 @@ impl EventBuilder { /// /// # Example /// ```rust,no_run + /// use nostr::url::Url; /// use nostr::{EventBuilder, Metadata}; /// /// let metadata = Metadata::new() diff --git a/crates/nostr/src/event/tag.rs b/crates/nostr/src/event/tag.rs index 392fede89..11c44ea9a 100644 --- a/crates/nostr/src/event/tag.rs +++ b/crates/nostr/src/event/tag.rs @@ -3,7 +3,6 @@ //! Tag use core::fmt; - use core::num::ParseIntError; use core::str::FromStr; diff --git a/crates/nostr/src/key/mod.rs b/crates/nostr/src/key/mod.rs index a19ac0224..22db823c8 100644 --- a/crates/nostr/src/key/mod.rs +++ b/crates/nostr/src/key/mod.rs @@ -228,6 +228,7 @@ impl Keys { } /// Get [`PublicKey`] + #[cfg(feature = "std")] pub fn normalized_public_key(&self) -> Result { Ok(self.secret_key()?.public_key(SECP256K1)) } diff --git a/crates/nostr/src/nips/nip26.rs b/crates/nostr/src/nips/nip26.rs index bf0736376..736fba098 100644 --- a/crates/nostr/src/nips/nip26.rs +++ b/crates/nostr/src/nips/nip26.rs @@ -146,7 +146,7 @@ pub fn sign_delegation_with_signer( ) -> Result { let unhashed_token = DelegationToken::new(delegatee_pk, conditions); let hashed_token = Sha256Hash::hash(unhashed_token.as_bytes()); - let message = Message::from_slice(&hashed_token)?; + let message = Message::from_slice(hashed_token.as_byte_array())?; Ok(delegator_keys.sign_schnorr_with_secp(&message, secp)?) } @@ -176,7 +176,7 @@ pub fn verify_delegation_signature( ) -> Result<(), Error> { let unhashed_token = DelegationToken::new(delegatee_public_key, conditions); let hashed_token = Sha256Hash::hash(unhashed_token.as_bytes()); - let message = Message::from_slice(&hashed_token)?; + let message = Message::from_slice(hashed_token.as_byte_array())?; secp.verify_schnorr(&signature, &message, &delegator_public_key)?; Ok(()) } From 3de5f835073d2244613ab14bb630ad3d16c21625 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 21 Apr 2023 14:13:09 +0200 Subject: [PATCH 38/77] deps: remove default features for bitcoin_hashes --- crates/nostr/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml index ab3a8c920..2fed9c3d5 100644 --- a/crates/nostr/Cargo.toml +++ b/crates/nostr/Cargo.toml @@ -54,7 +54,7 @@ base64 = { version = "0.21", optional = true } bech32 = { git = "https://github.com/rust-bitcoin/rust-bech32", rev = "360af7e0647fa94bce892fa69f31c0ef02452b63", optional = true, default-features = false } bip39 = { version = "2.0", optional = true } bitcoin = { version = "0.30", optional = true } -bitcoin_hashes = { version = "0.12", features = ["serde"] } +bitcoin_hashes = { version = "0.12", default-features = false, features = ["serde"] } cbc = { version = "0.1", features = ["alloc"], optional = true } log = "0.4" # no_std compatible by-default nostr-ots = { version = "0.2", optional = true } From b0ac2e13f3f0de42d2ce46a24dd65bd58e979273 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 21 Apr 2023 14:14:05 +0200 Subject: [PATCH 39/77] deps: add missing feature to secp256k1 --- crates/nostr/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml index 2fed9c3d5..34747234a 100644 --- a/crates/nostr/Cargo.toml +++ b/crates/nostr/Cargo.toml @@ -59,7 +59,7 @@ cbc = { version = "0.1", features = ["alloc"], optional = true } log = "0.4" # no_std compatible by-default nostr-ots = { version = "0.2", optional = true } reqwest = { version = "0.11", default-features = false, features = ["json", "rustls-tls-webpki-roots", "socks"], optional = true } -secp256k1 = { version = "0.27", default-features = false } +secp256k1 = { version = "0.27", default-features = false, features = ["serde"] } serde = { version = "1.0", features = ["derive"], default-features = false, optional = true } serde_json = { version = "1.0", optional = true, default-features = false } From d6bc1dcc5d9ff7efb4aca3cc2af6a73e7e4d783c Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 21 Apr 2023 14:16:43 +0200 Subject: [PATCH 40/77] event: compress imports from the secp256k1 --- crates/nostr/src/event/mod.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/crates/nostr/src/event/mod.rs b/crates/nostr/src/event/mod.rs index 411702537..972f1d1bd 100644 --- a/crates/nostr/src/event/mod.rs +++ b/crates/nostr/src/event/mod.rs @@ -12,12 +12,7 @@ use alloc::{string::{String, ToString}; #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::vec::Vec; - -use secp256k1::schnorr::Signature; -use secp256k1::Message; - -use secp256k1::XOnlyPublicKey; -use secp256k1::{Secp256k1, Verification}; +use secp256k1::{schnorr::Signature, Message, Secp256k1, Verification, XOnlyPublicKey}; use serde::{Deserialize, Serialize}; use serde_json::Value; From 6665889f3ba58779ff0f1581dd642c77ebfa5331 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 21 Apr 2023 14:37:29 +0200 Subject: [PATCH 41/77] nostr: compress secp256k1 imports --- crates/nostr/src/event/unsigned.rs | 12 +++++------- crates/nostr/src/prelude.rs | 12 ++++++++---- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/crates/nostr/src/event/unsigned.rs b/crates/nostr/src/event/unsigned.rs index bde8b53fb..a13684357 100644 --- a/crates/nostr/src/event/unsigned.rs +++ b/crates/nostr/src/event/unsigned.rs @@ -3,15 +3,13 @@ //! Unsigned Event -#[cfg(feature = "alloc")] -use alloc::{ - string::{String, ToString}, - vec::Vec, -}; use core::fmt; +======= +use alloc::string::{String, ToString}; +#[cfg(feature = "alloc")] +use alloc::vec::Vec; -use secp256k1::schnorr::Signature; -use secp256k1::{Message, XOnlyPublicKey}; +use secp256k1::{schnorr::Signature, XOnlyPublicKey}; use serde::{Deserialize, Serialize}; #[cfg(feature = "std")] diff --git a/crates/nostr/src/prelude.rs b/crates/nostr/src/prelude.rs index 4f0efffdd..884643663 100644 --- a/crates/nostr/src/prelude.rs +++ b/crates/nostr/src/prelude.rs @@ -2,14 +2,19 @@ // Distributed under the MIT software license //! Prelude +#![allow(ambiguous_glob_reexports)] // External crates pub use ::url::*; #[cfg(feature = "nip19")] -pub use bech32; +pub use bech32::*; #[cfg(feature = "nip06")] pub use bip39::*; -pub use secp256k1; +#[cfg(feature = "nip06")] +pub use bitcoin::*; +pub use bitcoin_hashes::*; +pub use secp256k1::*; +pub use serde_json::*; // Internal modules pub use crate::event::builder::*; @@ -22,7 +27,6 @@ pub use crate::key::*; pub use crate::message::*; pub use crate::types::*; pub use crate::Result; - #[cfg(feature = "std")] pub use crate::SECP256K1; @@ -37,7 +41,7 @@ pub use crate::nips::nip06::*; pub use crate::nips::nip11::*; pub use crate::nips::nip13::*; #[cfg(feature = "nip19")] -pub use crate::nips::nip19; +pub use crate::nips::nip19::*; pub use crate::nips::nip26::*; #[cfg(feature = "nip46")] pub use crate::nips::nip46::*; From ab803283e87c35f9757aa905a81dad94472ea313 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 11 May 2023 12:49:30 +0200 Subject: [PATCH 42/77] fix event/unsigned.rs file --- crates/nostr/src/event/unsigned.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/nostr/src/event/unsigned.rs b/crates/nostr/src/event/unsigned.rs index a13684357..78f78e145 100644 --- a/crates/nostr/src/event/unsigned.rs +++ b/crates/nostr/src/event/unsigned.rs @@ -4,7 +4,7 @@ //! Unsigned Event use core::fmt; -======= + use alloc::string::{String, ToString}; #[cfg(feature = "alloc")] use alloc::vec::Vec; From c0c007ca15afa879b603b6dba42db49a44ceceb9 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 21 Apr 2023 16:24:40 +0200 Subject: [PATCH 43/77] fixed tests/examples --- Cargo.toml | 2 +- crates/nostr-sdk/README.md | 3 + crates/nostr-sdk/examples/client-with-opts.rs | 3 + crates/nostr-sdk/examples/client.rs | 2 + crates/nostr-sdk/examples/nostr-connect.rs | 6 ++ crates/nostr-sdk/src/client/mod.rs | 37 ++++++--- crates/nostr-sdk/src/client/signer/remote.rs | 3 + crates/nostr-sdk/src/prelude.rs | 4 +- crates/nostr/README.md | 6 ++ crates/nostr/examples/nip13.rs | 4 + crates/nostr/examples/nip19.rs | 3 + crates/nostr/examples/nip65.rs | 2 +- crates/nostr/src/event/builder.rs | 81 +++++++++++++++---- crates/nostr/src/key/mod.rs | 4 +- crates/nostr/src/lib.rs | 2 +- crates/nostr/src/nips/nip26.rs | 2 +- crates/nostr/src/prelude.rs | 14 ++-- 17 files changed, 136 insertions(+), 42 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index b070fcbc9..e4e3c1e44 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,7 @@ members = [ "crates/nostr-sdk-net", "crates/ensure_no_std", ] -default-members = ["crates/*"] +default-members = ["crates/nostr*"] resolver = "2" [workspace.package] diff --git a/crates/nostr-sdk/README.md b/crates/nostr-sdk/README.md index fab308af1..0c2c1bc3c 100644 --- a/crates/nostr-sdk/README.md +++ b/crates/nostr-sdk/README.md @@ -32,6 +32,9 @@ tokio = { version = "1", features = ["full"] } use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; use nostr_sdk::prelude::*; +use nostr_sdk::key::XOnlyPublicKey; +use crate::nostr_sdk::prelude::nip19::FromBech32; +use crate::nostr_sdk::prelude::nip19::ToBech32; #[tokio::main] async fn main() -> Result<()> { diff --git a/crates/nostr-sdk/examples/client-with-opts.rs b/crates/nostr-sdk/examples/client-with-opts.rs index a9ed3dd08..788466e1b 100644 --- a/crates/nostr-sdk/examples/client-with-opts.rs +++ b/crates/nostr-sdk/examples/client-with-opts.rs @@ -3,6 +3,9 @@ use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; +use nostr_sdk::key::SecretKey; +use nostr_sdk::nips::nip04::decrypt; +use nostr_sdk::prelude::nip19::FromBech32; use nostr_sdk::prelude::*; const BECH32_SK: &str = "nsec1ufnus6pju578ste3v90xd5m2decpuzpql2295m3sknqcjzyys9ls0qlc85"; diff --git a/crates/nostr-sdk/examples/client.rs b/crates/nostr-sdk/examples/client.rs index cb25a2442..2bac880ea 100644 --- a/crates/nostr-sdk/examples/client.rs +++ b/crates/nostr-sdk/examples/client.rs @@ -1,6 +1,8 @@ // Copyright (c) 2022-2023 Yuki Kishimoto // Distributed under the MIT software license +use nostr_sdk::key::SecretKey; +use nostr_sdk::prelude::nip19::FromBech32; use nostr_sdk::prelude::*; const BECH32_SK: &str = "nsec1ufnus6pju578ste3v90xd5m2decpuzpql2295m3sknqcjzyys9ls0qlc85"; diff --git a/crates/nostr-sdk/examples/nostr-connect.rs b/crates/nostr-sdk/examples/nostr-connect.rs index fbfa72dad..8e8b60c96 100644 --- a/crates/nostr-sdk/examples/nostr-connect.rs +++ b/crates/nostr-sdk/examples/nostr-connect.rs @@ -3,6 +3,12 @@ use std::time::Duration; +use nostr_sdk::client::RemoteSigner; +use nostr_sdk::key::SecretKey; +use nostr_sdk::key::XOnlyPublicKey; +use nostr_sdk::nips::nip46::NostrConnectMetadata; +use nostr_sdk::nips::nip46::NostrConnectURI; +use nostr_sdk::prelude::nip19::FromBech32; use nostr_sdk::prelude::*; const APP_SECRET_KEY: &str = "nsec1j4c6269y9w0q2er2xjw8sv2ehyrtfxq3jwgdlxj6qfn8z4gjsq5qfvfk99"; diff --git a/crates/nostr-sdk/src/client/mod.rs b/crates/nostr-sdk/src/client/mod.rs index d17799762..55e6881f0 100644 --- a/crates/nostr-sdk/src/client/mod.rs +++ b/crates/nostr-sdk/src/client/mod.rs @@ -121,6 +121,7 @@ impl Client { /// # Example /// ```rust,no_run /// use nostr_sdk::prelude::*; + /// use nostr::Keys; /// /// let my_keys = Keys::generate(); /// let client = Client::new(&my_keys); @@ -134,6 +135,7 @@ impl Client { /// # Example /// ```rust,no_run /// use nostr_sdk::prelude::*; + /// use nostr::Keys; /// /// let my_keys = Keys::generate(); /// let opts = Options::new().wait_for_send(true); @@ -223,6 +225,7 @@ impl Client { /// # Example /// ```rust,no_run /// use nostr_sdk::prelude::*; + /// use nostr::Keys; /// /// # #[tokio::main] /// # async fn main() { @@ -261,6 +264,7 @@ impl Client { /// # Example /// ```rust,no_run /// use nostr_sdk::prelude::*; + /// use nostr::Keys; /// /// # #[tokio::main] /// # async fn main() { @@ -306,7 +310,7 @@ impl Client { /// # Example /// ```rust,no_run /// use nostr_sdk::prelude::*; - /// + /// use nostr::Keys; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -352,6 +356,7 @@ impl Client { /// # Example /// ```rust,no_run /// use nostr_sdk::prelude::*; + /// use nostr::Keys; /// /// # #[tokio::main] /// # async fn main() { @@ -382,6 +387,7 @@ impl Client { /// # Example /// ```rust,no_run /// use nostr_sdk::prelude::*; + /// use nostr::Keys; /// /// # #[tokio::main] /// # async fn main() { @@ -410,7 +416,7 @@ impl Client { /// # Example /// ```rust,no_run /// use nostr_sdk::prelude::*; - /// + /// use nostr::Keys; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -427,7 +433,7 @@ impl Client { /// # Example /// ```rust,no_run /// use nostr_sdk::prelude::*; - /// + /// use nostr::Keys; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -444,7 +450,7 @@ impl Client { /// # Example /// ```rust,no_run /// use nostr_sdk::prelude::*; - /// + /// use nostr::Keys; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -474,7 +480,7 @@ impl Client { /// use std::time::Duration; /// /// use nostr_sdk::prelude::*; - /// + /// use nostr::Keys; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -606,7 +612,7 @@ impl Client { /// # Example /// ```rust,no_run /// use nostr_sdk::prelude::*; - /// + /// use nostr::Keys; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -633,7 +639,7 @@ impl Client { /// # Example /// ```rust,no_run /// use nostr_sdk::prelude::*; - /// + /// use nostr::Keys; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -659,7 +665,7 @@ impl Client { /// # Example /// ```rust,no_run /// use nostr_sdk::prelude::*; - /// + /// use nostr::Keys; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -724,7 +730,7 @@ impl Client { /// use std::time::Duration; /// /// use nostr_sdk::prelude::*; - /// + /// use nostr::Keys; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -822,7 +828,9 @@ impl Client { /// # Example /// ```rust,no_run /// use nostr_sdk::prelude::*; - /// + /// use nostr_sdk::key::XOnlyPublicKey; + /// use nostr_sdk::prelude::nip19::FromBech32; + /// use nostr::Keys; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -909,7 +917,8 @@ impl Client { /// use std::str::FromStr; /// /// use nostr_sdk::prelude::*; - /// + /// use nostr_sdk::key::XOnlyPublicKey; + /// use nostr::Keys; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -943,7 +952,8 @@ impl Client { /// use std::str::FromStr; /// /// use nostr_sdk::prelude::*; - /// + /// use nostr_sdk::key::XOnlyPublicKey; + /// use nostr::Keys; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -977,7 +987,8 @@ impl Client { /// use std::str::FromStr; /// /// use nostr_sdk::prelude::*; - /// + /// use nostr_sdk::key::XOnlyPublicKey; + /// use nostr::Keys; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); diff --git a/crates/nostr-sdk/src/client/signer/remote.rs b/crates/nostr-sdk/src/client/signer/remote.rs index 7b18d9db6..ae35c5732 100644 --- a/crates/nostr-sdk/src/client/signer/remote.rs +++ b/crates/nostr-sdk/src/client/signer/remote.rs @@ -66,6 +66,7 @@ impl Client { /// use std::time::Duration; /// /// use nostr_sdk::prelude::*; + /// use nostr_sdk::client::RemoteSigner; /// /// #[tokio::main] /// async fn main() { @@ -87,6 +88,8 @@ impl Client { /// use std::str::FromStr; /// /// use nostr_sdk::prelude::*; + /// use nostr_sdk::key::XOnlyPublicKey; + /// use nostr_sdk::client::RemoteSigner; /// /// #[tokio::main] /// async fn main() { diff --git a/crates/nostr-sdk/src/prelude.rs b/crates/nostr-sdk/src/prelude.rs index dc6e9d520..eb7bca6b4 100644 --- a/crates/nostr-sdk/src/prelude.rs +++ b/crates/nostr-sdk/src/prelude.rs @@ -7,6 +7,6 @@ pub use nostr::prelude::*; // Internal modules -pub use crate::client::*; -pub use crate::relay::*; +pub use crate::client; +pub use crate::relay; pub use crate::*; diff --git a/crates/nostr/README.md b/crates/nostr/README.md index 214aeecbc..6cf5c3bae 100644 --- a/crates/nostr/README.md +++ b/crates/nostr/README.md @@ -24,6 +24,12 @@ tungstenite = { version = "0.18", features = ["rustls-tls-webpki-roots"]} ```rust,no_run use nostr::prelude::*; +use nostr::Keys; +use nostr::Event; +use nostr::Metadata; +use nostr::EventBuilder; +use nostr::ClientMessage; +use crate::nostr::nips::nip19::ToBech32; use tungstenite::{Message as WsMessage}; fn main() -> Result<()> { diff --git a/crates/nostr/examples/nip13.rs b/crates/nostr/examples/nip13.rs index ccf2c9fc2..a8efc17c8 100644 --- a/crates/nostr/examples/nip13.rs +++ b/crates/nostr/examples/nip13.rs @@ -3,7 +3,11 @@ use std::str::FromStr; +use nostr::key::SecretKey; use nostr::prelude::*; +use nostr::Event; +use nostr::EventBuilder; +use nostr::Keys; const ALICE_SK: &str = "6b911fd37cdf5c81d4c0adb1ab7fa822ed253ab0ad9aa18d77257c88b29b718e"; diff --git a/crates/nostr/examples/nip19.rs b/crates/nostr/examples/nip19.rs index 49cdbdf1b..66bbf26b0 100644 --- a/crates/nostr/examples/nip19.rs +++ b/crates/nostr/examples/nip19.rs @@ -3,7 +3,10 @@ use std::str::FromStr; +use nostr::key::XOnlyPublicKey; +use nostr::nips::nip19::ToBech32; use nostr::prelude::*; +use nostr::Profile; fn main() -> Result<()> { env_logger::init(); diff --git a/crates/nostr/examples/nip65.rs b/crates/nostr/examples/nip65.rs index 675a3dffe..23d932c69 100644 --- a/crates/nostr/examples/nip65.rs +++ b/crates/nostr/examples/nip65.rs @@ -1,5 +1,5 @@ use nostr::nips::nip65; -use nostr::prelude::FromBech32; +use nostr::prelude::nip19::FromBech32; use nostr::secp256k1::XOnlyPublicKey; use nostr::{ClientMessage, Filter, Kind, RelayMessage, Result, SubscriptionId}; use tungstenite::{connect, Message as WsMessage}; diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index 49f60a019..1c79a2370 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -131,17 +131,6 @@ impl EventBuilder { Ok(self.to_unsigned_event(pubkey).sign(keys)?) } - /// Build [`UnsignedEvent`] - #[cfg(feature = "std")] - pub fn to_unsigned_event(self, pubkey: XOnlyPublicKey) -> UnsignedEvent { - let created_at: Timestamp = Timestamp::now(); - let id = EventId::new(&pubkey, created_at, &self.kind, &self.tags, &self.content); - let message = Message::from_slice(id.as_bytes())?; - let signature = keys.sign_schnorr(&message)?; - - Self::to_event_internal(self, keys, created_at, id, signature) - } - /// Build [`Event`] with a `timestamp` #[cfg(not(feature = "std"))] pub fn to_event_with_timestamp_with_secp( @@ -196,8 +185,8 @@ impl EventBuilder { let now = Instant::now(); use secp256k1::SECP256K1; - self.to_pow_event_with_time_supplier_with_secp::( - keys, difficulty, &now, SECP256K1, + self.to_unsigned_pow_event_with_time_supplier_with_secp::( + pubkey, difficulty, &now, SECP256K1, ) } @@ -266,7 +255,7 @@ impl EventBuilder { #[cfg(all(feature = "alloc", not(feature = "std")))] let sig = keys.sign_schnorr_with_secp(&message, &_secp)?; - #[cfg(all(feature = "std", not(feature = "alloc")))] + #[cfg(feature = "std")] let sig = keys.sign_schnorr(&message)?; return self.to_event_internal(keys, created_at, id, sig); @@ -275,6 +264,70 @@ impl EventBuilder { tags.pop(); } } + /// Build POW [`Event`] using the given time supplier + pub fn to_unsigned_pow_event_with_time_supplier_with_secp( + self, + pubkey: XOnlyPublicKey, + difficulty: u8, + time_supplier: &impl TimeSupplier, + secp: &Secp256k1, + ) -> UnsignedEvent + where + T: TimeSupplier, + { + self.to_pow_unsigned_event_internal(pubkey, difficulty, time_supplier, secp) + } + + fn to_pow_unsigned_event_internal( + self, + pubkey: XOnlyPublicKey, + difficulty: u8, + time_supplier: &T, + _secp: &Secp256k1, + ) -> UnsignedEvent + where + T: TimeSupplier, + { + #[cfg(target_arch = "wasm32")] + use instant::Instant; + #[cfg(all(not(target_arch = "wasm32"), feature = "std"))] + use std::cmp; + + #[cfg(all(feature = "alloc", not(feature = "std")))] + use core::cmp; + + let mut nonce: u128 = 0; + let mut tags: Vec = self.tags.clone(); + + let now = time_supplier.now(); + + loop { + nonce += 1; + + tags.push(Tag::POW { nonce, difficulty }); + + let new_now = time_supplier.now(); + let created_at = time_supplier.duration_since_starting_point(now.clone()); + let created_at = time_supplier.to_timestamp(created_at); + let id = EventId::new(&pubkey, created_at, &self.kind, &tags, &self.content); + + if nip13::get_leading_zero_bits(id.inner()) >= difficulty { + log::debug!( + "{} iterations in {} ms. Avg rate {} hashes/second", + nonce, + time_supplier + .elapsed_since(now.clone(), new_now.clone()) + .as_millis(), + nonce * 1000 + / cmp::max(1, time_supplier.elapsed_since(now, new_now).as_millis()) + ); + + return self.to_unsigned_event(pubkey); + } + + tags.pop(); + } + } /// Build [`UnsignedEvent`] #[cfg(feature = "std")] diff --git a/crates/nostr/src/key/mod.rs b/crates/nostr/src/key/mod.rs index 22db823c8..e5eb9b147 100644 --- a/crates/nostr/src/key/mod.rs +++ b/crates/nostr/src/key/mod.rs @@ -15,9 +15,9 @@ use rand_core::OsRng; #[cfg(feature = "std")] use secp256k1::rand::rngs::OsRng; -#[cfg(feature = "alloc")] +#[cfg(all(feature = "alloc", not(feature = "std")))] use secp256k1::Secp256k1; -#[cfg(feature = "alloc")] +#[cfg(all(feature = "alloc", not(feature = "std")))] use secp256k1::Signing; #[cfg(all(feature = "alloc", not(feature = "std")))] diff --git a/crates/nostr/src/lib.rs b/crates/nostr/src/lib.rs index cb60d2507..0f15f9ae3 100644 --- a/crates/nostr/src/lib.rs +++ b/crates/nostr/src/lib.rs @@ -1,7 +1,7 @@ // Copyright (c) 2022-2023 Yuki Kishimoto // Distributed under the MIT software license -#![cfg_attr(not(feature = "std"), feature(error_in_core))] +#![feature(error_in_core)] #![warn(missing_docs)] #![warn(rustdoc::bare_urls)] diff --git a/crates/nostr/src/nips/nip26.rs b/crates/nostr/src/nips/nip26.rs index 736fba098..173f10096 100644 --- a/crates/nostr/src/nips/nip26.rs +++ b/crates/nostr/src/nips/nip26.rs @@ -545,7 +545,7 @@ mod test { use std::str::FromStr; use super::*; - use crate::prelude::SecretKey; + use crate::key::SecretKey; #[test] fn test_serialize_conditions() { diff --git a/crates/nostr/src/prelude.rs b/crates/nostr/src/prelude.rs index 884643663..38b3a5464 100644 --- a/crates/nostr/src/prelude.rs +++ b/crates/nostr/src/prelude.rs @@ -32,17 +32,17 @@ pub use crate::SECP256K1; // NIPs #[cfg(feature = "nip04")] -pub use crate::nips::nip04::*; +pub use crate::nips::nip04; #[cfg(feature = "nip05")] -pub use crate::nips::nip05::*; +pub use crate::nips::nip05; #[cfg(feature = "nip06")] -pub use crate::nips::nip06::*; +pub use crate::nips::nip06; #[cfg(feature = "nip11")] -pub use crate::nips::nip11::*; -pub use crate::nips::nip13::*; +pub use crate::nips::nip11; +pub use crate::nips::nip13; #[cfg(feature = "nip19")] pub use crate::nips::nip19::*; pub use crate::nips::nip26::*; #[cfg(feature = "nip46")] -pub use crate::nips::nip46::*; -pub use crate::nips::nip65::*; +pub use crate::nips::nip46; +pub use crate::nips::nip65; From a1224ca76ac40a05b530216b093a50aaff64225d Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Mon, 8 May 2023 13:52:40 +0200 Subject: [PATCH 44/77] nostr: fix std::error::Error import in url --- crates/nostr/src/types/url.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/nostr/src/types/url.rs b/crates/nostr/src/types/url.rs index 205f556ae..4c6854eb4 100644 --- a/crates/nostr/src/types/url.rs +++ b/crates/nostr/src/types/url.rs @@ -9,6 +9,11 @@ use core::str::FromStr; use serde::{Deserialize, Serialize}; use url::{ParseError, Url}; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use core::error::Error as StdError; +#[cfg(feature = "std")] +use std::error::Error as StdError; + /// Url Error #[derive(Debug, PartialEq, Eq)] pub enum Error { @@ -16,7 +21,7 @@ pub enum Error { Url(ParseError), } -impl std::error::Error for Error {} +impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { From 98603db66473ee3758a3f25662ec83b38330bb50 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Mon, 8 May 2023 16:08:12 +0200 Subject: [PATCH 45/77] nostr/event: make is_expired method no_std compatible --- crates/nostr/src/event/mod.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/nostr/src/event/mod.rs b/crates/nostr/src/event/mod.rs index 972f1d1bd..e3179c354 100644 --- a/crates/nostr/src/event/mod.rs +++ b/crates/nostr/src/event/mod.rs @@ -171,11 +171,18 @@ impl Event { /// Returns `true` if the event has an expiration tag that is expired. /// If an event has no `Expiration` tag, then it will return `false`. + #[cfg(feature = "std")] pub fn is_expired(&self) -> bool { let now = Timestamp::now(); + self.is_expired_since(now) + } + + /// Returns `true` if the event has an expiration tag that is expired `since`. + /// If an event has no `Expiration` tag, then it will return `false`. + pub fn is_expired_since(&self, since: Timestamp) -> bool { for tag in self.tags.iter() { if let Tag::Expiration(timestamp) = tag { - return timestamp < &now; + return timestamp < &since; } } false From d5b2408e2cef50eb2669978a09f1b157430c6f2d Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Mon, 8 May 2023 16:09:05 +0200 Subject: [PATCH 46/77] nostr/event/builder: fix EventBuilder in no_std --- crates/nostr/src/event/builder.rs | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index 1c79a2370..6c03d2925 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -5,11 +5,9 @@ use core::fmt; #[cfg(feature = "alloc")] -use alloc::{ - string::{String, ToString}, - vec, - vec::Vec, -}; +use alloc::string::{String, ToString}; +#[cfg(feature = "alloc")] +use alloc::{vec, vec::Vec}; use secp256k1::schnorr::Signature; use secp256k1::{Message, XOnlyPublicKey}; @@ -309,7 +307,13 @@ impl EventBuilder { let new_now = time_supplier.now(); let created_at = time_supplier.duration_since_starting_point(now.clone()); let created_at = time_supplier.to_timestamp(created_at); - let id = EventId::new(&pubkey, created_at, &self.kind, &tags, &self.content); + let id = EventId::new( + &pubkey, + created_at.clone(), + &self.kind, + &tags, + &self.content, + ); if nip13::get_leading_zero_bits(id.inner()) >= difficulty { log::debug!( @@ -322,7 +326,7 @@ impl EventBuilder { / cmp::max(1, time_supplier.elapsed_since(now, new_now).as_millis()) ); - return self.to_unsigned_event(pubkey); + return self.to_unsigned_event_with_timestamp(pubkey, created_at); } tags.pop(); From b6a4d382ea51d0446f5cf17daf42880d150c5121 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Mon, 8 May 2023 16:09:47 +0200 Subject: [PATCH 47/77] fix import in time.rs --- crates/nostr/src/types/time.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/crates/nostr/src/types/time.rs b/crates/nostr/src/types/time.rs index dc782990b..3523e5c38 100644 --- a/crates/nostr/src/types/time.rs +++ b/crates/nostr/src/types/time.rs @@ -16,6 +16,10 @@ use std::{ #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::fmt; #[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::string::String; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::vec::Vec; +#[cfg(all(feature = "alloc", not(feature = "std")))] use core::num; #[cfg(target_arch = "wasm32")] From e19325595e8358c459b52101a7f679cfdb50cbce Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Mon, 8 May 2023 16:09:59 +0200 Subject: [PATCH 48/77] fix import in url.rs --- crates/nostr/src/types/url.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/nostr/src/types/url.rs b/crates/nostr/src/types/url.rs index 4c6854eb4..56b2a93fa 100644 --- a/crates/nostr/src/types/url.rs +++ b/crates/nostr/src/types/url.rs @@ -9,6 +9,8 @@ use core::str::FromStr; use serde::{Deserialize, Serialize}; use url::{ParseError, Url}; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::string::String; #[cfg(all(feature = "alloc", not(feature = "std")))] use core::error::Error as StdError; #[cfg(feature = "std")] From 8e4b91bf54bd140fe3373eed214d0688a591ae9f Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Tue, 9 May 2023 08:16:04 +0200 Subject: [PATCH 49/77] nostr: move ensure_no_std test crate to example --- Cargo.toml | 1 - crates/{ => nostr/examples}/ensure_no_std/Cargo.toml | 6 +++++- crates/{ => nostr/examples}/ensure_no_std/src/main.rs | 0 3 files changed, 5 insertions(+), 2 deletions(-) rename crates/{ => nostr/examples}/ensure_no_std/Cargo.toml (67%) rename crates/{ => nostr/examples}/ensure_no_std/src/main.rs (100%) diff --git a/Cargo.toml b/Cargo.toml index e4e3c1e44..93a14a4a3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,6 @@ members = [ "crates/nostr", "crates/nostr-sdk", "crates/nostr-sdk-net", - "crates/ensure_no_std", ] default-members = ["crates/nostr*"] resolver = "2" diff --git a/crates/ensure_no_std/Cargo.toml b/crates/nostr/examples/ensure_no_std/Cargo.toml similarity index 67% rename from crates/ensure_no_std/Cargo.toml rename to crates/nostr/examples/ensure_no_std/Cargo.toml index 13ac2d2c8..6ddd520df 100644 --- a/crates/ensure_no_std/Cargo.toml +++ b/crates/nostr/examples/ensure_no_std/Cargo.toml @@ -8,4 +8,8 @@ edition = "2021" [dependencies] libc = { version = "0.2.119", default-features = false } -nostr = { path = "../nostr", default-features = false, features = ["alloc"] } +nostr = { path = "../../../nostr", default-features = false, features = [ + "alloc", +] } + +[workspace] diff --git a/crates/ensure_no_std/src/main.rs b/crates/nostr/examples/ensure_no_std/src/main.rs similarity index 100% rename from crates/ensure_no_std/src/main.rs rename to crates/nostr/examples/ensure_no_std/src/main.rs From d98e11e21311ddf9522e6a9cf107c211db812b65 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Wed, 10 May 2023 08:55:43 +0200 Subject: [PATCH 50/77] remove rand_core dep --- crates/nostr/Cargo.toml | 7 ------- crates/nostr/src/key/mod.rs | 2 +- crates/nostr/src/message/subscription.rs | 2 +- 3 files changed, 2 insertions(+), 9 deletions(-) diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml index 34747234a..2397cec95 100644 --- a/crates/nostr/Cargo.toml +++ b/crates/nostr/Cargo.toml @@ -30,8 +30,6 @@ alloc = [ "url_no_std", "secp256k1/alloc", "secp256k1/rand", - "rand_core/alloc", - "rand_core/getrandom", "rand/alloc", "rand/getrandom", ] @@ -69,11 +67,6 @@ url_no_std = { package = "url", features = [ "alloc", ], git = "https://github.com/OverOrion/rust-url", branch = "no_std_net", optional = true, default-features = false } -rand_core = { version = "0.6", features = [ - "alloc", - "getrandom", -], optional = true, default-features = false } - rand = { version = "0.8", features = [ "alloc", "getrandom", diff --git a/crates/nostr/src/key/mod.rs b/crates/nostr/src/key/mod.rs index e5eb9b147..c810561cf 100644 --- a/crates/nostr/src/key/mod.rs +++ b/crates/nostr/src/key/mod.rs @@ -11,7 +11,7 @@ use core::fmt; use core::str::FromStr; #[cfg(all(feature = "alloc", not(feature = "std")))] -use rand_core::OsRng; +use rand::rngs::OsRng; #[cfg(feature = "std")] use secp256k1::rand::rngs::OsRng; diff --git a/crates/nostr/src/message/subscription.rs b/crates/nostr/src/message/subscription.rs index 4b4329988..3bc81df28 100644 --- a/crates/nostr/src/message/subscription.rs +++ b/crates/nostr/src/message/subscription.rs @@ -17,7 +17,7 @@ use alloc::{vec, vec::Vec}; use bitcoin_hashes::sha256::Hash as Sha256Hash; use bitcoin_hashes::Hash; #[cfg(all(feature = "alloc", not(feature = "std")))] -use rand_core::{OsRng, RngCore}; +use rand::{rngs::OsRng, RngCore}; #[cfg(feature = "std")] use secp256k1::rand::{rngs::OsRng, RngCore}; use secp256k1::XOnlyPublicKey; From 4bf5dd7ff18479998feae73788748ce5051d91ff Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 11 May 2023 12:47:52 +0200 Subject: [PATCH 51/77] remove thiserror from Cargo.toml --- crates/nostr/Cargo.toml | 2 -- crates/nostr/src/lib.rs | 3 --- 2 files changed, 5 deletions(-) diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml index 2397cec95..2abdb7924 100644 --- a/crates/nostr/Cargo.toml +++ b/crates/nostr/Cargo.toml @@ -14,7 +14,6 @@ keywords = ["nostr", "protocol", "sdk"] [features] default = ["all-nips", "std"] std = [ - "dep:thiserror", "bitcoin_hashes/std", "serde/std", "serde_json/std", @@ -23,7 +22,6 @@ std = [ "secp256k1/rand-std", ] alloc = [ - "dep:thiserror-core", "bitcoin_hashes/alloc", "serde/alloc", "serde_json/alloc", diff --git a/crates/nostr/src/lib.rs b/crates/nostr/src/lib.rs index 0f15f9ae3..85c05fe3b 100644 --- a/crates/nostr/src/lib.rs +++ b/crates/nostr/src/lib.rs @@ -15,9 +15,6 @@ #[cfg(feature = "alloc")] extern crate alloc; -#[cfg(feature = "alloc")] -extern crate thiserror_core as thiserror; - #[cfg(feature = "alloc")] use alloc::boxed::Box; From 1cdbd7636ee470d324a3061848c60d15fe4d61ad Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 11 May 2023 12:48:21 +0200 Subject: [PATCH 52/77] fix event/mod.rs file --- crates/nostr/src/event/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/nostr/src/event/mod.rs b/crates/nostr/src/event/mod.rs index e3179c354..6d93434c7 100644 --- a/crates/nostr/src/event/mod.rs +++ b/crates/nostr/src/event/mod.rs @@ -8,7 +8,7 @@ use core::fmt; use core::str::FromStr; #[cfg(all(feature = "alloc", not(feature = "std")))] -use alloc::{string::{String, ToString}; +use alloc::string::{String, ToString}; #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::vec::Vec; From c3ba426dc6fa01413de18f711743381f1a47721b Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 11 May 2023 12:48:45 +0200 Subject: [PATCH 53/77] fix event/id.rs file --- crates/nostr/src/event/id.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/nostr/src/event/id.rs b/crates/nostr/src/event/id.rs index 4b3da0906..ad33b01c1 100644 --- a/crates/nostr/src/event/id.rs +++ b/crates/nostr/src/event/id.rs @@ -39,6 +39,7 @@ impl fmt::Display for Error { Self::Hex(e) => write!(f, "{e}"), Self::Hash(e) => write!(f, "{e}"), } + } impl From for Error { From 05352e50e743cf995291ad74d7e4f504c35a9707 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 11 May 2023 12:48:59 +0200 Subject: [PATCH 54/77] fix event/id.rs file --- crates/nostr/src/event/id.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/nostr/src/event/id.rs b/crates/nostr/src/event/id.rs index ad33b01c1..a13ba669a 100644 --- a/crates/nostr/src/event/id.rs +++ b/crates/nostr/src/event/id.rs @@ -40,7 +40,7 @@ impl fmt::Display for Error { Self::Hash(e) => write!(f, "{e}"), } } - +} impl From for Error { fn from(e: bitcoin_hashes::hex::Error) -> Self { From ccd238f1127cc1bfe5aa0c900cc5456702585454 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 11 May 2023 12:50:20 +0200 Subject: [PATCH 55/77] fix event/id.rs file --- crates/nostr/src/event/id.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/nostr/src/event/id.rs b/crates/nostr/src/event/id.rs index a13ba669a..93bf7c358 100644 --- a/crates/nostr/src/event/id.rs +++ b/crates/nostr/src/event/id.rs @@ -6,12 +6,10 @@ use core::fmt; use core::str::FromStr; -#[cfg(all(feature = "alloc", not(feature = "std")))] -use alloc::str::FromStr; #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::string::{String, ToString}; #[cfg(all(feature = "alloc", not(feature = "std")))] -use alloc::{fmt, vec}; +use alloc::vec; use bitcoin_hashes::sha256::Hash as Sha256Hash; use bitcoin_hashes::Hash; From ccca6772d28c8e0b966c7ce432bee9ad12c0bbfd Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 11 May 2023 12:51:37 +0200 Subject: [PATCH 56/77] fix nips/nip58.rs file --- crates/nostr/src/nips/nip58.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/nostr/src/nips/nip58.rs b/crates/nostr/src/nips/nip58.rs index 6d765d30b..aebc7622c 100644 --- a/crates/nostr/src/nips/nip58.rs +++ b/crates/nostr/src/nips/nip58.rs @@ -4,6 +4,11 @@ use core::fmt; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::string::String; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use alloc::{vec, vec::Vec}; + use secp256k1::XOnlyPublicKey; use crate::event::builder::Error as BuilderError; From 9d4e5421377b6fe84753182ab3f62bf6c5bf2cb0 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 11 May 2023 13:05:31 +0200 Subject: [PATCH 57/77] nostr: use core::error::Error where possible --- crates/nostr/src/event/builder.rs | 12 +++++++++--- crates/nostr/src/event/id.rs | 8 +++++++- crates/nostr/src/event/mod.rs | 8 +++++++- crates/nostr/src/event/tag.rs | 8 +++++++- crates/nostr/src/event/unsigned.rs | 7 ++++++- crates/nostr/src/key/mod.rs | 8 +++++++- crates/nostr/src/key/vanity.rs | 2 +- crates/nostr/src/message/mod.rs | 8 +++++++- crates/nostr/src/nips/nip04.rs | 2 +- crates/nostr/src/nips/nip05.rs | 2 +- crates/nostr/src/nips/nip06.rs | 2 +- crates/nostr/src/nips/nip11.rs | 2 +- crates/nostr/src/nips/nip19.rs | 2 +- crates/nostr/src/nips/nip21.rs | 2 +- crates/nostr/src/nips/nip26.rs | 10 ++++++++-- crates/nostr/src/nips/nip46.rs | 2 +- crates/nostr/src/nips/nip58.rs | 10 ++++++++-- crates/nostr/src/types/channel_id.rs | 8 +++++++- crates/nostr/src/types/metadata.rs | 8 +++++++- 19 files changed, 88 insertions(+), 23 deletions(-) diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index 6c03d2925..624d7b04a 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -4,11 +4,17 @@ //! Event builder use core::fmt; -#[cfg(feature = "alloc")] +#[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::string::{String, ToString}; -#[cfg(feature = "alloc")] +#[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::{vec, vec::Vec}; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use core::error::Error as StdError; + +#[cfg(feature = "std")] +use std::error::Error as StdError; + use secp256k1::schnorr::Signature; use secp256k1::{Message, XOnlyPublicKey}; use secp256k1::{Secp256k1, Signing}; @@ -43,7 +49,7 @@ pub enum Error { NIP04(nip04::Error), } -impl std::error::Error for Error {} +impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/nostr/src/event/id.rs b/crates/nostr/src/event/id.rs index 93bf7c358..12b7257f0 100644 --- a/crates/nostr/src/event/id.rs +++ b/crates/nostr/src/event/id.rs @@ -11,6 +11,12 @@ use alloc::string::{String, ToString}; #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::vec; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use core::error::Error as StdError; + +#[cfg(feature = "std")] +use std::error::Error as StdError; + use bitcoin_hashes::sha256::Hash as Sha256Hash; use bitcoin_hashes::Hash; use secp256k1::XOnlyPublicKey; @@ -29,7 +35,7 @@ pub enum Error { Hash(bitcoin_hashes::Error), } -impl std::error::Error for Error {} +impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/nostr/src/event/mod.rs b/crates/nostr/src/event/mod.rs index 6d93434c7..cebcd9c80 100644 --- a/crates/nostr/src/event/mod.rs +++ b/crates/nostr/src/event/mod.rs @@ -12,6 +12,12 @@ use alloc::string::{String, ToString}; #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::vec::Vec; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use core::error::Error as StdError; + +#[cfg(feature = "std")] +use std::error::Error as StdError; + use secp256k1::{schnorr::Signature, Message, Secp256k1, Verification, XOnlyPublicKey}; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -47,7 +53,7 @@ pub enum Error { OpenTimestamps(nostr_ots::Error), } -impl std::error::Error for Error {} +impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/nostr/src/event/tag.rs b/crates/nostr/src/event/tag.rs index 11c44ea9a..d6d70c4bc 100644 --- a/crates/nostr/src/event/tag.rs +++ b/crates/nostr/src/event/tag.rs @@ -13,6 +13,12 @@ use alloc::string::{String, ToString}; #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::{vec, vec::Vec}; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use core::error::Error as StdError; + +#[cfg(feature = "std")] +use std::error::Error as StdError; + use secp256k1::schnorr::Signature; use secp256k1::XOnlyPublicKey; use serde::de::Error as DeserializerError; @@ -52,7 +58,7 @@ pub enum Error { Event(crate::event::Error), } -impl std::error::Error for Error {} +impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/nostr/src/event/unsigned.rs b/crates/nostr/src/event/unsigned.rs index 78f78e145..8b3c56060 100644 --- a/crates/nostr/src/event/unsigned.rs +++ b/crates/nostr/src/event/unsigned.rs @@ -8,6 +8,11 @@ use core::fmt; use alloc::string::{String, ToString}; #[cfg(feature = "alloc")] use alloc::vec::Vec; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use core::error::Error as StdError; + +#[cfg(feature = "std")] +use std::error::Error as StdError; use secp256k1::{schnorr::Signature, XOnlyPublicKey}; use serde::{Deserialize, Serialize}; @@ -33,7 +38,7 @@ pub enum Error { Event(super::Error), } -impl std::error::Error for Error {} +impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/nostr/src/key/mod.rs b/crates/nostr/src/key/mod.rs index c810561cf..e3e76394a 100644 --- a/crates/nostr/src/key/mod.rs +++ b/crates/nostr/src/key/mod.rs @@ -10,6 +10,12 @@ use core::fmt; #[cfg(feature = "nip19")] use core::str::FromStr; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use core::error::Error as StdError; + +#[cfg(feature = "std")] +use std::error::Error as StdError; + #[cfg(all(feature = "alloc", not(feature = "std")))] use rand::rngs::OsRng; #[cfg(feature = "std")] @@ -52,7 +58,7 @@ pub enum Error { Secp256k1(secp256k1::Error), } -impl std::error::Error for Error {} +impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/nostr/src/key/vanity.rs b/crates/nostr/src/key/vanity.rs index d42ace481..125370e5b 100644 --- a/crates/nostr/src/key/vanity.rs +++ b/crates/nostr/src/key/vanity.rs @@ -30,7 +30,7 @@ pub enum Error { JoinHandleError, } -impl std::error::Error for Error {} +impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/nostr/src/message/mod.rs b/crates/nostr/src/message/mod.rs index 6832f336d..4586f1e25 100644 --- a/crates/nostr/src/message/mod.rs +++ b/crates/nostr/src/message/mod.rs @@ -5,6 +5,12 @@ use core::fmt; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use core::error::Error as StdError; + +#[cfg(feature = "std")] +use std::error::Error as StdError; + pub mod client; pub mod relay; pub mod subscription; @@ -24,7 +30,7 @@ pub enum MessageHandleError { Event(crate::event::Error), } -impl std::error::Error for MessageHandleError {} +impl StdError for MessageHandleError {} impl fmt::Display for MessageHandleError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/nostr/src/nips/nip04.rs b/crates/nostr/src/nips/nip04.rs index 454b99369..89a03e818 100644 --- a/crates/nostr/src/nips/nip04.rs +++ b/crates/nostr/src/nips/nip04.rs @@ -35,7 +35,7 @@ pub enum Error { Secp256k1(secp256k1::Error), } -impl std::error::Error for Error {} +impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/nostr/src/nips/nip05.rs b/crates/nostr/src/nips/nip05.rs index 1c43903f7..4ff7deb63 100644 --- a/crates/nostr/src/nips/nip05.rs +++ b/crates/nostr/src/nips/nip05.rs @@ -32,7 +32,7 @@ pub enum Error { Secp256k1(secp256k1::Error), } -impl std::error::Error for Error {} +impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/nostr/src/nips/nip06.rs b/crates/nostr/src/nips/nip06.rs index ba03949cc..cf8e949f4 100644 --- a/crates/nostr/src/nips/nip06.rs +++ b/crates/nostr/src/nips/nip06.rs @@ -27,7 +27,7 @@ pub enum Error { BIP39(bip39::Error), } -impl std::error::Error for Error {} +impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/nostr/src/nips/nip11.rs b/crates/nostr/src/nips/nip11.rs index 0ccca2e2d..f9dc4a053 100644 --- a/crates/nostr/src/nips/nip11.rs +++ b/crates/nostr/src/nips/nip11.rs @@ -28,7 +28,7 @@ pub enum Error { Reqwest(reqwest::Error), } -impl std::error::Error for Error {} +impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/nostr/src/nips/nip19.rs b/crates/nostr/src/nips/nip19.rs index bb485e1fa..f5fcbbf93 100644 --- a/crates/nostr/src/nips/nip19.rs +++ b/crates/nostr/src/nips/nip19.rs @@ -59,7 +59,7 @@ pub enum Error { TryFromSlice, } -impl std::error::Error for Error {} +impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/nostr/src/nips/nip21.rs b/crates/nostr/src/nips/nip21.rs index ee0261809..3afd14c42 100644 --- a/crates/nostr/src/nips/nip21.rs +++ b/crates/nostr/src/nips/nip21.rs @@ -27,7 +27,7 @@ pub enum Error { InvalidURI, } -impl std::error::Error for Error {} +impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/nostr/src/nips/nip26.rs b/crates/nostr/src/nips/nip26.rs index 173f10096..b49e4c27f 100644 --- a/crates/nostr/src/nips/nip26.rs +++ b/crates/nostr/src/nips/nip26.rs @@ -16,6 +16,12 @@ use alloc::string::{String, ToString}; #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::{vec, vec::Vec}; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use core::error::Error as StdError; + +#[cfg(feature = "std")] +use std::error::Error as StdError; + use bitcoin_hashes::sha256::Hash as Sha256Hash; use bitcoin_hashes::Hash; use secp256k1::schnorr::Signature; @@ -52,7 +58,7 @@ pub enum Error { DelegationTagParse, } -impl std::error::Error for Error {} +impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -108,7 +114,7 @@ pub enum ValidationError { CreatedTooLate, } -impl std::error::Error for ValidationError {} +impl StdError for ValidationError {} impl fmt::Display for ValidationError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/nostr/src/nips/nip46.rs b/crates/nostr/src/nips/nip46.rs index 50b48ae5a..cc665250c 100644 --- a/crates/nostr/src/nips/nip46.rs +++ b/crates/nostr/src/nips/nip46.rs @@ -52,7 +52,7 @@ pub enum Error { InvalidURIScheme, } -impl std::error::Error for Error {} +impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/nostr/src/nips/nip58.rs b/crates/nostr/src/nips/nip58.rs index aebc7622c..9106b0d09 100644 --- a/crates/nostr/src/nips/nip58.rs +++ b/crates/nostr/src/nips/nip58.rs @@ -9,6 +9,12 @@ use alloc::string::String; #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::{vec, vec::Vec}; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use core::error::Error as StdError; + +#[cfg(feature = "std")] +use std::error::Error as StdError; + use secp256k1::XOnlyPublicKey; use crate::event::builder::Error as BuilderError; @@ -25,7 +31,7 @@ pub enum Error { EventBuilder(crate::event::builder::Error), } -impl std::error::Error for Error {} +impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -219,7 +225,7 @@ pub enum ProfileBadgesEventError { EventBuilder(crate::event::builder::Error), } -impl std::error::Error for ProfileBadgesEventError {} +impl StdError for ProfileBadgesEventError {} impl fmt::Display for ProfileBadgesEventError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/nostr/src/types/channel_id.rs b/crates/nostr/src/types/channel_id.rs index 9fdb4cc27..cd0b57a25 100644 --- a/crates/nostr/src/types/channel_id.rs +++ b/crates/nostr/src/types/channel_id.rs @@ -11,6 +11,12 @@ use alloc::string::{String, ToString}; #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::vec::Vec; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use core::error::Error as StdError; + +#[cfg(feature = "std")] +use std::error::Error as StdError; + #[cfg(feature = "nip19")] use bech32::{self, FromBase32, ToBase32, Variant}; use bitcoin_hashes::sha256::Hash as Sha256Hash; @@ -32,7 +38,7 @@ pub enum Error { Hash(bitcoin_hashes::Error), } -impl std::error::Error for Error {} +impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { diff --git a/crates/nostr/src/types/metadata.rs b/crates/nostr/src/types/metadata.rs index 266886290..9cc539fc8 100644 --- a/crates/nostr/src/types/metadata.rs +++ b/crates/nostr/src/types/metadata.rs @@ -5,6 +5,12 @@ use core::fmt; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use core::error::Error as StdError; + +#[cfg(feature = "std")] +use std::error::Error as StdError; + use serde::{Deserialize, Serialize}; use url::Url; @@ -18,7 +24,7 @@ pub enum Error { Json(serde_json::Error), } -impl std::error::Error for Error {} +impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { From 94647c21575253910aa01973bc8a8d01bdf6c0fb Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 11 May 2023 13:07:45 +0200 Subject: [PATCH 58/77] remove duplicate impl froms --- crates/nostr/src/event/builder.rs | 12 ------------ crates/nostr/src/event/mod.rs | 18 ------------------ crates/nostr/src/event/tag.rs | 18 ------------------ crates/nostr/src/event/unsigned.rs | 12 ------------ crates/nostr/src/message/mod.rs | 6 ------ 5 files changed, 66 deletions(-) diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index 624d7b04a..f25aee620 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -95,18 +95,6 @@ impl From for Error { } } -impl From for Error { - fn from(error: secp256k1::Error) -> Self { - Self::Secp256k1(error) - } -} - -impl From for Error { - fn from(error: serde_json::Error) -> Self { - Self::Json(error) - } -} - /// [`Event`] builder #[derive(Debug, Clone, Eq, PartialEq)] pub struct EventBuilder { diff --git a/crates/nostr/src/event/mod.rs b/crates/nostr/src/event/mod.rs index cebcd9c80..ea96953a9 100644 --- a/crates/nostr/src/event/mod.rs +++ b/crates/nostr/src/event/mod.rs @@ -93,24 +93,6 @@ impl From for Error { } } -impl From for Error { - fn from(error: serde_json::Error) -> Self { - Self::Json(error) - } -} - -impl From for Error { - fn from(error: secp256k1::Error) -> Self { - Self::Secp256k1(error) - } -} - -impl From for Error { - fn from(error: bitcoin_hashes::hex::Error) -> Self { - Self::Hex(error) - } -} - /// [`Event`] struct #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub struct Event { diff --git a/crates/nostr/src/event/tag.rs b/crates/nostr/src/event/tag.rs index d6d70c4bc..fedda4894 100644 --- a/crates/nostr/src/event/tag.rs +++ b/crates/nostr/src/event/tag.rs @@ -121,24 +121,6 @@ impl From for Error { } } -impl From for Error { - fn from(error: secp256k1::Error) -> Self { - Self::Secp256k1(error) - } -} - -impl From for Error { - fn from(error: bitcoin_hashes::hex::Error) -> Self { - Self::Hex(error) - } -} - -impl From for Error { - fn from(error: url::ParseError) -> Self { - Self::Url(error) - } -} - /// Marker #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Marker { diff --git a/crates/nostr/src/event/unsigned.rs b/crates/nostr/src/event/unsigned.rs index 8b3c56060..17f3beb46 100644 --- a/crates/nostr/src/event/unsigned.rs +++ b/crates/nostr/src/event/unsigned.rs @@ -75,18 +75,6 @@ impl From for Error { } } -impl From for Error { - fn from(error: secp256k1::Error) -> Self { - Self::Secp256k1(error) - } -} - -impl From for Error { - fn from(error: serde_json::Error) -> Self { - Self::Json(error) - } -} - /// [`UnsignedEvent`] struct #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] pub struct UnsignedEvent { diff --git a/crates/nostr/src/message/mod.rs b/crates/nostr/src/message/mod.rs index 4586f1e25..16a34322e 100644 --- a/crates/nostr/src/message/mod.rs +++ b/crates/nostr/src/message/mod.rs @@ -53,9 +53,3 @@ impl From for MessageHandleError { Self::Event(e) } } - -impl From for MessageHandleError { - fn from(error: serde_json::Error) -> Self { - Self::Json(error) - } -} From f04176517639330e86acfb05a724418583b7ecdc Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 11 May 2023 13:08:46 +0200 Subject: [PATCH 59/77] fix missing import in nip58.rs --- crates/nostr/src/nips/nip58.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/nostr/src/nips/nip58.rs b/crates/nostr/src/nips/nip58.rs index 9106b0d09..a33e2bdef 100644 --- a/crates/nostr/src/nips/nip58.rs +++ b/crates/nostr/src/nips/nip58.rs @@ -4,6 +4,8 @@ use core::fmt; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use crate::alloc::borrow::ToOwned; #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::string::String; #[cfg(all(feature = "alloc", not(feature = "std")))] From 8e0547412be966887b69333731cedc9e4c047fac Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 11 May 2023 15:27:24 +0200 Subject: [PATCH 60/77] nostr/nips: port NIP58 to no_std --- crates/nostr/src/nips/nip58.rs | 99 ++++++++++++++++++++++++++++++---- 1 file changed, 90 insertions(+), 9 deletions(-) diff --git a/crates/nostr/src/nips/nip58.rs b/crates/nostr/src/nips/nip58.rs index a33e2bdef..21441bdb5 100644 --- a/crates/nostr/src/nips/nip58.rs +++ b/crates/nostr/src/nips/nip58.rs @@ -17,6 +17,11 @@ use core::error::Error as StdError; #[cfg(feature = "std")] use std::error::Error as StdError; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use crate::prelude::{Secp256k1, Signing}; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use crate::types::Timestamp; + use secp256k1::XOnlyPublicKey; use crate::event::builder::Error as BuilderError; @@ -112,7 +117,29 @@ impl BadgeDefinitionBuilder { } /// Build [`Event`] + #[cfg(feature = "std")] pub fn build(self, keys: &Keys) -> Result { + let event_builder = self.build_internal(keys)?; + let event = event_builder.to_event(keys)?; + + Ok(BadgeDefinition(event)) + } + + /// Build [`Event`] + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub fn build( + self, + keys: &Keys, + created_at: Timestamp, + secp: &Secp256k1, + ) -> Result { + let event_builder = self.build_internal()?; + let event = event_builder.to_event_with_timestamp_with_secp(&keys, created_at, secp)?; + + Ok(BadgeDefinition(event)) + } + /// Build [`Event`] + fn build_internal(self) -> Result { let mut tags: Vec = Vec::new(); let badge_id = Tag::Identifier(self.badge_id); tags.push(badge_id); @@ -150,8 +177,7 @@ impl BadgeDefinitionBuilder { } let event_builder = EventBuilder::new(Kind::BadgeDefinition, String::new(), &tags); - let event = event_builder.to_event(keys)?; - Ok(BadgeDefinition(event)) + Ok(event_builder) } } @@ -164,12 +190,39 @@ pub struct BadgeDefinition(Event); pub struct BadgeAward(Event); impl BadgeAward { - /// + /// New [`BadgeAward`] + #[cfg(feature = "std")] pub fn new( badge_definition: &Event, awarded_pub_keys: Vec, keys: &Keys, ) -> Result { + let event_builder = BadgeAward::new_internal(badge_definition, awarded_pub_keys, keys)?; + let event = event_builder.to_event(keys)?; + + Ok(BadgeAward(event)) + } + + /// New [`BadgeAward`] + #[cfg(all(feature = "alloc", not(feature = "std")))] + pub fn new( + badge_definition: &Event, + awarded_pub_keys: Vec, + keys: &Keys, + created_at: Timestamp, + secp: &Secp256k1, + ) -> Result { + let event_builder = BadgeAward::new_internal(badge_definition, awarded_pub_keys, keys)?; + let event = event_builder.to_event_with_timestamp_with_secp(&keys, created_at, secp)?; + + Ok(BadgeAward(event)) + } + + fn new_internal( + badge_definition: &Event, + awarded_pub_keys: Vec, + keys: &Keys, + ) -> Result { let badge_id = match badge_definition.kind { Kind::BadgeDefinition => badge_definition.tags.iter().find_map(|t| match t { Tag::Identifier(id) => Some(id), @@ -198,9 +251,7 @@ impl BadgeAward { tags.extend(awarded_pub_keys); let event_builder = EventBuilder::new(Kind::BadgeAward, String::new(), &tags); - let event = event_builder.to_event(keys)?; - - Ok(BadgeAward(event)) + Ok(event_builder) } } @@ -282,6 +333,24 @@ impl ProfileBadgesEvent { }) } + #[cfg(all(feature = "alloc", not(feature = "std")))] + /// Create a new [`ProfileBadgesEvent`] from badge definition and awards events + /// [`badge_definitions`] and [`badge_awards`] must be ordered, so on the same position they refer to the same badge + pub fn new( + badge_definitions: Vec, + badge_awards: Vec, + pubkey_awarded: &XOnlyPublicKey, + keys: &Keys, + created_at: Timestamp, + secp: &Secp256k1, + ) -> Result { + let event_builder = + ProfileBadgesEvent::new_internal(badge_definitions, badge_awards, pubkey_awarded)?; + let event = event_builder.to_event_with_timestamp_with_secp(keys, created_at, &secp)?; + + Ok(ProfileBadgesEvent(event)) + } + #[cfg(feature = "std")] /// Create a new [`ProfileBadgesEvent`] from badge definition and awards events /// [`badge_definitions`] and [`badge_awards`] must be ordered, so on the same position they refer to the same badge pub fn new( @@ -290,6 +359,20 @@ impl ProfileBadgesEvent { pubkey_awarded: &XOnlyPublicKey, keys: &Keys, ) -> Result { + let event_builder = + ProfileBadgesEvent::new_internal(badge_definitions, badge_awards, pubkey_awarded)?; + let event = event_builder.to_event(keys)?; + + Ok(ProfileBadgesEvent(event)) + } + + /// Create a new [`ProfileBadgesEvent`] from badge definition and awards events + /// [`badge_definitions`] and [`badge_awards`] must be ordered, so on the same position they refer to the same badge + fn new_internal( + badge_definitions: Vec, + badge_awards: Vec, + pubkey_awarded: &XOnlyPublicKey, + ) -> Result { if badge_definitions.len() != badge_awards.len() { return Err(ProfileBadgesEventError::InvalidLength); } @@ -375,9 +458,7 @@ impl ProfileBadgesEvent { // Badge definitions and awards have been validated let event_builder = EventBuilder::new(Kind::ProfileBadges, String::new(), &tags); - let event = event_builder.to_event(keys)?; - - Ok(ProfileBadgesEvent(event)) + Ok(event_builder) } } From 0135ca7a75937a4cf909ed43f212afba815dcc62 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Thu, 11 May 2023 16:37:20 +0200 Subject: [PATCH 61/77] minor fixes --- crates/nostr/src/event/builder.rs | 2 +- crates/nostr/src/event/unsigned.rs | 1 + crates/nostr/src/lib.rs | 2 +- crates/nostr/src/nips/nip04.rs | 6 ++++++ crates/nostr/src/nips/nip05.rs | 7 +++++++ crates/nostr/src/nips/nip06.rs | 6 ++++++ crates/nostr/src/nips/nip11.rs | 7 +++++++ crates/nostr/src/nips/nip19.rs | 24 +++++++----------------- crates/nostr/src/nips/nip21.rs | 6 ++++++ crates/nostr/src/nips/nip46.rs | 6 ++++++ crates/nostr/src/nips/nip58.rs | 2 +- crates/nostr/src/prelude.rs | 10 +++++++--- 12 files changed, 56 insertions(+), 23 deletions(-) diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index f25aee620..300d7d19c 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -334,7 +334,7 @@ impl EventBuilder { Self::to_unsigned_event_internal(self, pubkey, created_at) } - #[cfg(not(feature = "std"))] + /// Build [`UnsignedEvent`] with the given `Timestamp` /// Mostly useful for cases where the time source comes from the outside, not from builtin /// functions diff --git a/crates/nostr/src/event/unsigned.rs b/crates/nostr/src/event/unsigned.rs index 17f3beb46..58ec6747c 100644 --- a/crates/nostr/src/event/unsigned.rs +++ b/crates/nostr/src/event/unsigned.rs @@ -5,6 +5,7 @@ use core::fmt; +#[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::string::{String, ToString}; #[cfg(feature = "alloc")] use alloc::vec::Vec; diff --git a/crates/nostr/src/lib.rs b/crates/nostr/src/lib.rs index 85c05fe3b..b3365b39d 100644 --- a/crates/nostr/src/lib.rs +++ b/crates/nostr/src/lib.rs @@ -1,7 +1,7 @@ // Copyright (c) 2022-2023 Yuki Kishimoto // Distributed under the MIT software license -#![feature(error_in_core)] +#![cfg_attr(all(not(feature = "std"), feature = "alloc"), feature(error_in_core))] #![warn(missing_docs)] #![warn(rustdoc::bare_urls)] diff --git a/crates/nostr/src/nips/nip04.rs b/crates/nostr/src/nips/nip04.rs index 89a03e818..b1ccbae51 100644 --- a/crates/nostr/src/nips/nip04.rs +++ b/crates/nostr/src/nips/nip04.rs @@ -10,6 +10,12 @@ use core::convert::From; use core::fmt; use core::str::FromStr; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use core::error::Error as StdError; + +#[cfg(feature = "std")] +use std::error::Error as StdError; + use aes::cipher::block_padding::Pkcs7; use aes::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit}; use aes::Aes256; diff --git a/crates/nostr/src/nips/nip05.rs b/crates/nostr/src/nips/nip05.rs index 4ff7deb63..7b9a48a43 100644 --- a/crates/nostr/src/nips/nip05.rs +++ b/crates/nostr/src/nips/nip05.rs @@ -7,6 +7,13 @@ use core::fmt; use core::str::FromStr; + +#[cfg(all(feature = "alloc", not(feature = "std")))] +use core::error::Error as StdError; + +#[cfg(feature = "std")] +use std::error::Error as StdError; + #[cfg(not(target_arch = "wasm32"))] use std::net::SocketAddr; diff --git a/crates/nostr/src/nips/nip06.rs b/crates/nostr/src/nips/nip06.rs index cf8e949f4..bac554f73 100644 --- a/crates/nostr/src/nips/nip06.rs +++ b/crates/nostr/src/nips/nip06.rs @@ -8,6 +8,12 @@ use core::fmt; use core::str::FromStr; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use core::error::Error as StdError; + +#[cfg(feature = "std")] +use std::error::Error as StdError; + use bip39::Mnemonic; use bitcoin::bip32::{DerivationPath, ExtendedPrivKey}; use bitcoin::Network; diff --git a/crates/nostr/src/nips/nip11.rs b/crates/nostr/src/nips/nip11.rs index f9dc4a053..b78c3e83b 100644 --- a/crates/nostr/src/nips/nip11.rs +++ b/crates/nostr/src/nips/nip11.rs @@ -7,6 +7,13 @@ //! use core::fmt; + +#[cfg(all(feature = "alloc", not(feature = "std")))] +use core::error::Error as StdError; + +#[cfg(feature = "std")] +use std::error::Error as StdError; + #[cfg(not(target_arch = "wasm32"))] use std::net::SocketAddr; diff --git a/crates/nostr/src/nips/nip19.rs b/crates/nostr/src/nips/nip19.rs index f5fcbbf93..c8d0b5c30 100644 --- a/crates/nostr/src/nips/nip19.rs +++ b/crates/nostr/src/nips/nip19.rs @@ -12,6 +12,13 @@ use alloc::string::{FromUtf8Error, ToString}; #[cfg(not(feature = "std"))] use alloc::vec::{self, Vec}; use core::fmt; + +#[cfg(all(feature = "alloc", not(feature = "std")))] +use core::error::Error as StdError; + +#[cfg(feature = "std")] +use std::error::Error as StdError; + #[cfg(feature = "std")] use std::string::FromUtf8Error; @@ -106,23 +113,6 @@ impl From for Error { Self::EventId(e) } } -impl From for Error { - fn from(error: secp256k1::Error) -> Self { - Self::Secp256k1(error) - } -} - -impl From for Error { - fn from(error: bitcoin_hashes::Error) -> Self { - Self::Hash(error) - } -} - -impl From for Error { - fn from(error: bech32::Error) -> Self { - Self::Bech32(error) - } -} pub trait FromBech32: Sized { type Err; diff --git a/crates/nostr/src/nips/nip21.rs b/crates/nostr/src/nips/nip21.rs index 3afd14c42..2ac8daf98 100644 --- a/crates/nostr/src/nips/nip21.rs +++ b/crates/nostr/src/nips/nip21.rs @@ -7,6 +7,12 @@ use core::fmt; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use core::error::Error as StdError; + +#[cfg(feature = "std")] +use std::error::Error as StdError; + use secp256k1::XOnlyPublicKey; use super::nip19::{ diff --git a/crates/nostr/src/nips/nip46.rs b/crates/nostr/src/nips/nip46.rs index cc665250c..3430e491d 100644 --- a/crates/nostr/src/nips/nip46.rs +++ b/crates/nostr/src/nips/nip46.rs @@ -9,6 +9,12 @@ use core::fmt; use core::str::FromStr; use std::borrow::Cow; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use core::error::Error as StdError; + +#[cfg(feature = "std")] +use std::error::Error as StdError; + use bitcoin_hashes::sha256::Hash as Sha256Hash; use bitcoin_hashes::Hash; use secp256k1::schnorr::Signature; diff --git a/crates/nostr/src/nips/nip58.rs b/crates/nostr/src/nips/nip58.rs index 21441bdb5..9f80e2940 100644 --- a/crates/nostr/src/nips/nip58.rs +++ b/crates/nostr/src/nips/nip58.rs @@ -119,7 +119,7 @@ impl BadgeDefinitionBuilder { /// Build [`Event`] #[cfg(feature = "std")] pub fn build(self, keys: &Keys) -> Result { - let event_builder = self.build_internal(keys)?; + let event_builder = self.build_internal()?; let event = event_builder.to_event(keys)?; Ok(BadgeDefinition(event)) diff --git a/crates/nostr/src/prelude.rs b/crates/nostr/src/prelude.rs index 38b3a5464..6da547e1f 100644 --- a/crates/nostr/src/prelude.rs +++ b/crates/nostr/src/prelude.rs @@ -2,12 +2,16 @@ // Distributed under the MIT software license //! Prelude -#![allow(ambiguous_glob_reexports)] +//#![allow(ambiguous_glob_reexports)] +#![cfg_attr( + all(not(feature = "std"), feature = "alloc"), + allow(ambiguous_glob_reexports) +)] // External crates -pub use ::url::*; #[cfg(feature = "nip19")] -pub use bech32::*; +pub use ::bech32::*; +pub use ::url::*; #[cfg(feature = "nip06")] pub use bip39::*; #[cfg(feature = "nip06")] From f1f518abd5eeb2c535a485119a6351c9ec010274 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 12 May 2023 08:43:17 +0200 Subject: [PATCH 62/77] gha: add job for no_std nostr --- .github/workflows/ci.yml | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a3e309a5f..2a8eb7f5d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -95,4 +95,39 @@ jobs: run: cargo build ${{ matrix.build-args }} --target wasm32-unknown-unknown - name: Clippy run: cargo clippy ${{ matrix.build-args }} --target wasm32-unknown-unknown -- -D warnings + + buld-no-std: + name: Build the `no_std` crate (ensure_no_std) + runs-on: ubuntu-latest + strategy: + matrix: + rust: + - version: nightly + build-args: + [ + --no-default-features, + ] + steps: + - name: Checkout + uses: actions/checkout@v3 + - name: Cache + uses: actions/cache@v3 + with: + path: | + ~/.cargo/registry + ~/.cargo/git + target + key: ${{ runner.os }}-cargo-wasm32-${{ hashFiles('**/Cargo.toml','**/Cargo.lock') }} + - name: Set default toolchain + run: rustup default ${{ matrix.rust.version }} + - name: Add WASM + run: rustup target add wasm32-unknown-unknown + - name: Set profile + run: rustup set profile minimal && rustup component add clippy + - name: Build + run: cargo build ${{ matrix.build-args }} + working-directory: ./crates/nostr/examples/ensure_no_std + - name: Clippy + run: cargo clippy ${{ matrix.build-args }} -- -D warnings + working-directory: ./crates/nostr/examples/ensure_no_std \ No newline at end of file From 1ac775e62ceb5110c76d31d25c530af8586c6afd Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 12 May 2023 08:45:35 +0200 Subject: [PATCH 63/77] examples format, should be dropped --- crates/nostr-sdk/src/client/mod.rs | 46 ++++++++++---------- crates/nostr-sdk/src/client/signer/remote.rs | 6 +-- 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/crates/nostr-sdk/src/client/mod.rs b/crates/nostr-sdk/src/client/mod.rs index 55e6881f0..6e707f377 100644 --- a/crates/nostr-sdk/src/client/mod.rs +++ b/crates/nostr-sdk/src/client/mod.rs @@ -120,8 +120,8 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr_sdk::prelude::*; /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// /// let my_keys = Keys::generate(); /// let client = Client::new(&my_keys); @@ -134,8 +134,8 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr_sdk::prelude::*; /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// /// let my_keys = Keys::generate(); /// let opts = Options::new().wait_for_send(true); @@ -224,8 +224,8 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr_sdk::prelude::*; /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// /// # #[tokio::main] /// # async fn main() { @@ -263,8 +263,8 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr_sdk::prelude::*; /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// /// # #[tokio::main] /// # async fn main() { @@ -309,8 +309,8 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr_sdk::prelude::*; /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -355,8 +355,8 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr_sdk::prelude::*; /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// /// # #[tokio::main] /// # async fn main() { @@ -386,8 +386,8 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr_sdk::prelude::*; /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// /// # #[tokio::main] /// # async fn main() { @@ -415,8 +415,8 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr_sdk::prelude::*; /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -432,8 +432,8 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr_sdk::prelude::*; /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -449,8 +449,8 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr_sdk::prelude::*; /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -479,8 +479,8 @@ impl Client { /// ```rust,no_run /// use std::time::Duration; /// - /// use nostr_sdk::prelude::*; /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -611,8 +611,8 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr_sdk::prelude::*; /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -638,8 +638,8 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr_sdk::prelude::*; /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -664,8 +664,8 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr_sdk::prelude::*; /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -729,8 +729,8 @@ impl Client { /// ```rust,no_run /// use std::time::Duration; /// - /// use nostr_sdk::prelude::*; /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -827,10 +827,10 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr_sdk::prelude::*; + /// use nostr::Keys; /// use nostr_sdk::key::XOnlyPublicKey; /// use nostr_sdk::prelude::nip19::FromBech32; - /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -916,9 +916,9 @@ impl Client { /// ```rust,no_run /// use std::str::FromStr; /// - /// use nostr_sdk::prelude::*; - /// use nostr_sdk::key::XOnlyPublicKey; /// use nostr::Keys; + /// use nostr_sdk::key::XOnlyPublicKey; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -951,9 +951,9 @@ impl Client { /// ```rust,no_run /// use std::str::FromStr; /// - /// use nostr_sdk::prelude::*; - /// use nostr_sdk::key::XOnlyPublicKey; /// use nostr::Keys; + /// use nostr_sdk::key::XOnlyPublicKey; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); @@ -986,9 +986,9 @@ impl Client { /// ```rust,no_run /// use std::str::FromStr; /// - /// use nostr_sdk::prelude::*; - /// use nostr_sdk::key::XOnlyPublicKey; /// use nostr::Keys; + /// use nostr_sdk::key::XOnlyPublicKey; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { /// # let my_keys = Keys::generate(); diff --git a/crates/nostr-sdk/src/client/signer/remote.rs b/crates/nostr-sdk/src/client/signer/remote.rs index ae35c5732..4d574b02d 100644 --- a/crates/nostr-sdk/src/client/signer/remote.rs +++ b/crates/nostr-sdk/src/client/signer/remote.rs @@ -65,8 +65,8 @@ impl Client { /// ```rust,no_run /// use std::time::Duration; /// - /// use nostr_sdk::prelude::*; /// use nostr_sdk::client::RemoteSigner; + /// use nostr_sdk::prelude::*; /// /// #[tokio::main] /// async fn main() { @@ -87,9 +87,9 @@ impl Client { /// ```rust,no_run /// use std::str::FromStr; /// - /// use nostr_sdk::prelude::*; - /// use nostr_sdk::key::XOnlyPublicKey; /// use nostr_sdk::client::RemoteSigner; + /// use nostr_sdk::key::XOnlyPublicKey; + /// use nostr_sdk::prelude::*; /// /// #[tokio::main] /// async fn main() { From 44987eb27ed3561764964962e01afd937f8632a2 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 12 May 2023 08:50:02 +0200 Subject: [PATCH 64/77] fix ensure_no_std ci --- crates/nostr/examples/ensure_no_std/src/main.rs | 3 +++ crates/nostr/src/lib.rs | 1 + 2 files changed, 4 insertions(+) diff --git a/crates/nostr/examples/ensure_no_std/src/main.rs b/crates/nostr/examples/ensure_no_std/src/main.rs index a244cb217..4d1190222 100644 --- a/crates/nostr/examples/ensure_no_std/src/main.rs +++ b/crates/nostr/examples/ensure_no_std/src/main.rs @@ -1,5 +1,6 @@ #![feature(start, libc, lang_items)] #![feature(alloc_error_handler)] +#![allow(unused_imports)] #![no_std] #![no_main] @@ -18,6 +19,7 @@ extern "C" { pub fn printf(format: *const u8, ...) -> i32; } +#[allow(clippy::single_component_path_imports)] use nostr; #[no_mangle] @@ -64,6 +66,7 @@ static ALLOCATOR: SimpleAllocator = SimpleAllocator { unsafe impl Sync for SimpleAllocator {} // From https://doc.rust-lang.org/core/alloc/trait.GlobalAlloc.html +#[allow(clippy::blocks_in_if_conditions)] unsafe impl GlobalAlloc for SimpleAllocator { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { let size = layout.size(); diff --git a/crates/nostr/src/lib.rs b/crates/nostr/src/lib.rs index b3365b39d..76fa8a393 100644 --- a/crates/nostr/src/lib.rs +++ b/crates/nostr/src/lib.rs @@ -19,6 +19,7 @@ extern crate alloc; use alloc::boxed::Box; #[macro_use] +/// Serde crate pub extern crate serde; #[cfg(feature = "nip19")] From 41de424e1cd68e5d4797a827606ebacf38a865d9 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 12 May 2023 08:57:20 +0200 Subject: [PATCH 65/77] gha: fix std build --- .github/workflows/ci.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2a8eb7f5d..dc5e5a4d5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,9 +28,9 @@ jobs: build-args: [ -p nostr, - -p nostr --no-default-features, - -p nostr --no-default-features --features all-nips, - -p nostr --no-default-features --features vanity, + -p nostr --no-default-features --features std, + -p nostr --no-default-features --features 'std all-nips', + -p nostr --no-default-features --features 'std vanity', -p nostr --features blocking, -p nostr-sdk, -p nostr-sdk --no-default-features, From a37e0ca8526c4f0d53076cd69a780a23e222ef70 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 12 May 2023 09:10:00 +0200 Subject: [PATCH 66/77] fix std::error::Error in vanity.rs --- crates/nostr/src/key/vanity.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/nostr/src/key/vanity.rs b/crates/nostr/src/key/vanity.rs index 125370e5b..064abad68 100644 --- a/crates/nostr/src/key/vanity.rs +++ b/crates/nostr/src/key/vanity.rs @@ -9,6 +9,12 @@ use std::sync::mpsc::{sync_channel, RecvError}; use std::sync::Arc; use std::thread; +#[cfg(all(feature = "alloc", not(feature = "std")))] +use core::error::Error as StdError; + +#[cfg(feature = "std")] +use std::error::Error as StdError; + use secp256k1::rand; use secp256k1::SecretKey; From 26759e779922b8069a7681a9688ea9610a1a0e68 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 12 May 2023 09:14:13 +0200 Subject: [PATCH 67/77] nostr-*: add nostr with std feature --- bindings/nostr-js/Cargo.toml | 2 +- crates/nostr-sdk/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/bindings/nostr-js/Cargo.toml b/bindings/nostr-js/Cargo.toml index 115ad3c39..24a72f458 100644 --- a/bindings/nostr-js/Cargo.toml +++ b/bindings/nostr-js/Cargo.toml @@ -12,7 +12,7 @@ crate-type = ["lib", "cdylib"] [dependencies] console_error_panic_hook = "0.1" js-sys = "0.3" -nostr = { path = "../../crates/nostr" } +nostr = { path = "../../crates/nostr", features = ["std"]} serde-wasm-bindgen = "0.5" wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" diff --git a/crates/nostr-sdk/Cargo.toml b/crates/nostr-sdk/Cargo.toml index 064cab788..137e1b9fe 100644 --- a/crates/nostr-sdk/Cargo.toml +++ b/crates/nostr-sdk/Cargo.toml @@ -26,7 +26,7 @@ nip46 = ["nostr/nip46"] [dependencies] log = "0.4" -nostr = { version = "0.21", path = "../nostr", default-features = false } +nostr = { version = "0.21", path = "../nostr", default-features = false, features = ["std"]} nostr-sdk-net = { version = "0.21", path = "../nostr-sdk-net" } once_cell = { version = "1.17", optional = true } thiserror = "1.0" From 15c5de1caeda2ffbf2eaf70e79d0b8628e11d766 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 12 May 2023 09:18:09 +0200 Subject: [PATCH 68/77] nostr: fix vanity feature --- crates/nostr/Cargo.toml | 16 ++++++++++++---- crates/nostr/src/nips/mod.rs | 2 +- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/crates/nostr/Cargo.toml b/crates/nostr/Cargo.toml index 2abdb7924..b252ee946 100644 --- a/crates/nostr/Cargo.toml +++ b/crates/nostr/Cargo.toml @@ -32,7 +32,7 @@ alloc = [ "rand/getrandom", ] blocking = ["reqwest?/blocking"] -vanity = ["nip19"] +vanity = ["nip19-std"] all-nips = ["nip04", "nip05", "nip06", "nip11", "nip19", "nip21", "nip46"] nip03 = ["dep:nostr-ots"] nip04 = ["dep:aes", "dep:base64", "dep:cbc"] @@ -50,14 +50,22 @@ base64 = { version = "0.21", optional = true } bech32 = { git = "https://github.com/rust-bitcoin/rust-bech32", rev = "360af7e0647fa94bce892fa69f31c0ef02452b63", optional = true, default-features = false } bip39 = { version = "2.0", optional = true } bitcoin = { version = "0.30", optional = true } -bitcoin_hashes = { version = "0.12", default-features = false, features = ["serde"] } +bitcoin_hashes = { version = "0.12", default-features = false, features = [ + "serde", +] } cbc = { version = "0.1", features = ["alloc"], optional = true } log = "0.4" # no_std compatible by-default nostr-ots = { version = "0.2", optional = true } -reqwest = { version = "0.11", default-features = false, features = ["json", "rustls-tls-webpki-roots", "socks"], optional = true } +reqwest = { version = "0.11", default-features = false, features = [ + "json", + "rustls-tls-webpki-roots", + "socks", +], optional = true } secp256k1 = { version = "0.27", default-features = false, features = ["serde"] } -serde = { version = "1.0", features = ["derive"], default-features = false, optional = true } +serde = { version = "1.0", features = [ + "derive", +], default-features = false, optional = true } serde_json = { version = "1.0", optional = true, default-features = false } url = { version = "2", features = ["serde"], optional = true } diff --git a/crates/nostr/src/nips/mod.rs b/crates/nostr/src/nips/mod.rs index 85fc534f1..c49ef7460 100644 --- a/crates/nostr/src/nips/mod.rs +++ b/crates/nostr/src/nips/mod.rs @@ -14,7 +14,7 @@ pub mod nip06; #[cfg(feature = "nip11")] pub mod nip11; pub mod nip13; -#[cfg(feature = "nip19")] +#[cfg(any(feature = "nip19", feature = "nip19-std"))] pub mod nip19; #[cfg(feature = "nip21")] pub mod nip21; From da450d0eb3880db447f93b1988c0f804c8bee6e8 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 12 May 2023 09:31:43 +0200 Subject: [PATCH 69/77] fix clippy warnings --- crates/nostr/src/event/builder.rs | 20 +++++++------------- 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index 300d7d19c..7936e6a79 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -136,10 +136,10 @@ impl EventBuilder { let message = Message::from_slice(id.as_bytes())?; let signature = keys.sign_schnorr_with_secp(&message, secp)?; - Self::to_event_internal(self, keys, created_at, id, signature) + Self::into_event_internal(self, keys, created_at, id, signature) } - fn to_event_internal( + fn into_event_internal( self, keys: &Keys, created_at: Timestamp, @@ -250,7 +250,7 @@ impl EventBuilder { #[cfg(feature = "std")] let sig = keys.sign_schnorr(&message)?; - return self.to_event_internal(keys, created_at, id, sig); + return self.into_event_internal(keys, created_at, id, sig); } tags.pop(); @@ -301,13 +301,7 @@ impl EventBuilder { let new_now = time_supplier.now(); let created_at = time_supplier.duration_since_starting_point(now.clone()); let created_at = time_supplier.to_timestamp(created_at); - let id = EventId::new( - &pubkey, - created_at.clone(), - &self.kind, - &tags, - &self.content, - ); + let id = EventId::new(&pubkey, created_at, &self.kind, &tags, &self.content); if nip13::get_leading_zero_bits(id.inner()) >= difficulty { log::debug!( @@ -332,7 +326,7 @@ impl EventBuilder { pub fn to_unsigned_event(self, pubkey: XOnlyPublicKey) -> UnsignedEvent { let created_at: Timestamp = Timestamp::now(); - Self::to_unsigned_event_internal(self, pubkey, created_at) + Self::into_unsigned_event_internal(self, pubkey, created_at) } /// Build [`UnsignedEvent`] with the given `Timestamp` @@ -343,10 +337,10 @@ impl EventBuilder { pubkey: XOnlyPublicKey, created_at: Timestamp, ) -> UnsignedEvent { - Self::to_unsigned_event_internal(self, pubkey, created_at) + Self::into_unsigned_event_internal(self, pubkey, created_at) } - fn to_unsigned_event_internal( + fn into_unsigned_event_internal( self, pubkey: XOnlyPublicKey, created_at: Timestamp, From 2af0f3f2af831be5d544ab4f3c35977e9e5e6adc Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 12 May 2023 09:38:26 +0200 Subject: [PATCH 70/77] nostr: vanity.rs fix --- crates/nostr/examples/vanity.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/nostr/examples/vanity.rs b/crates/nostr/examples/vanity.rs index 66b418770..77177c0f1 100644 --- a/crates/nostr/examples/vanity.rs +++ b/crates/nostr/examples/vanity.rs @@ -1,6 +1,7 @@ // Copyright (c) 2022-2023 Yuki Kishimoto // Distributed under the MIT software license +use nostr::nips::nip19::ToBech32; use nostr::prelude::*; fn main() -> Result<()> { From a2d86bdee94f25304d1c154e92f334412b9ea42e Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 12 May 2023 09:43:14 +0200 Subject: [PATCH 71/77] nostr: fix clippy warning --- crates/nostr/src/event/builder.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index 7936e6a79..60cf0bbbe 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -193,10 +193,10 @@ impl EventBuilder { where T: TimeSupplier, { - self.to_pow_event_internal(keys, difficulty, time_supplier, secp) + self.into_pow_event_internal(keys, difficulty, time_supplier, secp) } - fn to_pow_event_internal( + fn into_pow_event_internal( self, keys: &Keys, difficulty: u8, @@ -267,10 +267,10 @@ impl EventBuilder { where T: TimeSupplier, { - self.to_pow_unsigned_event_internal(pubkey, difficulty, time_supplier, secp) + self.into_pow_unsigned_event_internal(pubkey, difficulty, time_supplier, secp) } - fn to_pow_unsigned_event_internal( + fn into_pow_unsigned_event_internal( self, pubkey: XOnlyPublicKey, difficulty: u8, From 7b82286c61f8c7579485c1b01ed1e8f1e25fb895 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 12 May 2023 09:48:59 +0200 Subject: [PATCH 72/77] nostr/examples/nip65: fix example --- crates/nostr/examples/nip65.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/nostr/examples/nip65.rs b/crates/nostr/examples/nip65.rs index 23d932c69..675a3dffe 100644 --- a/crates/nostr/examples/nip65.rs +++ b/crates/nostr/examples/nip65.rs @@ -1,5 +1,5 @@ use nostr::nips::nip65; -use nostr::prelude::nip19::FromBech32; +use nostr::prelude::FromBech32; use nostr::secp256k1::XOnlyPublicKey; use nostr::{ClientMessage, Filter, Kind, RelayMessage, Result, SubscriptionId}; use tungstenite::{connect, Message as WsMessage}; From fd736df8db66aa54c2adeabe70031de69ab2bfbb Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 12 May 2023 09:54:00 +0200 Subject: [PATCH 73/77] fix bech32 imports --- crates/nostr-sdk/README.md | 2 -- crates/nostr-sdk/examples/client-with-opts.rs | 2 +- crates/nostr-sdk/examples/client.rs | 2 +- crates/nostr-sdk/examples/nostr-connect.rs | 2 +- crates/nostr-sdk/src/client/mod.rs | 2 +- 5 files changed, 4 insertions(+), 6 deletions(-) diff --git a/crates/nostr-sdk/README.md b/crates/nostr-sdk/README.md index 0c2c1bc3c..6cb63e5fc 100644 --- a/crates/nostr-sdk/README.md +++ b/crates/nostr-sdk/README.md @@ -33,8 +33,6 @@ use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; use nostr_sdk::prelude::*; use nostr_sdk::key::XOnlyPublicKey; -use crate::nostr_sdk::prelude::nip19::FromBech32; -use crate::nostr_sdk::prelude::nip19::ToBech32; #[tokio::main] async fn main() -> Result<()> { diff --git a/crates/nostr-sdk/examples/client-with-opts.rs b/crates/nostr-sdk/examples/client-with-opts.rs index 788466e1b..a341baad5 100644 --- a/crates/nostr-sdk/examples/client-with-opts.rs +++ b/crates/nostr-sdk/examples/client-with-opts.rs @@ -5,7 +5,7 @@ use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; use nostr_sdk::key::SecretKey; use nostr_sdk::nips::nip04::decrypt; -use nostr_sdk::prelude::nip19::FromBech32; +use nostr_sdk::prelude::FromBech32; use nostr_sdk::prelude::*; const BECH32_SK: &str = "nsec1ufnus6pju578ste3v90xd5m2decpuzpql2295m3sknqcjzyys9ls0qlc85"; diff --git a/crates/nostr-sdk/examples/client.rs b/crates/nostr-sdk/examples/client.rs index 2bac880ea..45f25aded 100644 --- a/crates/nostr-sdk/examples/client.rs +++ b/crates/nostr-sdk/examples/client.rs @@ -2,7 +2,7 @@ // Distributed under the MIT software license use nostr_sdk::key::SecretKey; -use nostr_sdk::prelude::nip19::FromBech32; +use nostr_sdk::prelude::FromBech32; use nostr_sdk::prelude::*; const BECH32_SK: &str = "nsec1ufnus6pju578ste3v90xd5m2decpuzpql2295m3sknqcjzyys9ls0qlc85"; diff --git a/crates/nostr-sdk/examples/nostr-connect.rs b/crates/nostr-sdk/examples/nostr-connect.rs index 8e8b60c96..e538955c3 100644 --- a/crates/nostr-sdk/examples/nostr-connect.rs +++ b/crates/nostr-sdk/examples/nostr-connect.rs @@ -8,7 +8,7 @@ use nostr_sdk::key::SecretKey; use nostr_sdk::key::XOnlyPublicKey; use nostr_sdk::nips::nip46::NostrConnectMetadata; use nostr_sdk::nips::nip46::NostrConnectURI; -use nostr_sdk::prelude::nip19::FromBech32; +use nostr_sdk::prelude::FromBech32; use nostr_sdk::prelude::*; const APP_SECRET_KEY: &str = "nsec1j4c6269y9w0q2er2xjw8sv2ehyrtfxq3jwgdlxj6qfn8z4gjsq5qfvfk99"; diff --git a/crates/nostr-sdk/src/client/mod.rs b/crates/nostr-sdk/src/client/mod.rs index 6e707f377..a180e6225 100644 --- a/crates/nostr-sdk/src/client/mod.rs +++ b/crates/nostr-sdk/src/client/mod.rs @@ -829,7 +829,7 @@ impl Client { /// ```rust,no_run /// use nostr::Keys; /// use nostr_sdk::key::XOnlyPublicKey; - /// use nostr_sdk::prelude::nip19::FromBech32; + /// use nostr_sdk::prelude::FromBech32; /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { From d264da8dc2c8b1b12b672649869ac902103ed7e6 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 12 May 2023 10:13:31 +0200 Subject: [PATCH 74/77] nostr: fix WASM build --- crates/nostr/src/event/builder.rs | 8 ++------ crates/nostr/src/types/time.rs | 24 ++++++++++++++++-------- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/crates/nostr/src/event/builder.rs b/crates/nostr/src/event/builder.rs index 60cf0bbbe..ebf810c25 100644 --- a/crates/nostr/src/event/builder.rs +++ b/crates/nostr/src/event/builder.rs @@ -206,9 +206,7 @@ impl EventBuilder { where T: TimeSupplier, { - #[cfg(target_arch = "wasm32")] - use instant::Instant; - #[cfg(all(not(target_arch = "wasm32"), feature = "std"))] + #[cfg(feature = "std")] use std::cmp; #[cfg(all(feature = "alloc", not(feature = "std")))] @@ -280,9 +278,7 @@ impl EventBuilder { where T: TimeSupplier, { - #[cfg(target_arch = "wasm32")] - use instant::Instant; - #[cfg(all(not(target_arch = "wasm32"), feature = "std"))] + #[cfg(feature = "std")] use std::cmp; #[cfg(all(feature = "alloc", not(feature = "std")))] diff --git a/crates/nostr/src/types/time.rs b/crates/nostr/src/types/time.rs index 3523e5c38..6c21f92fb 100644 --- a/crates/nostr/src/types/time.rs +++ b/crates/nostr/src/types/time.rs @@ -22,13 +22,8 @@ use alloc::vec::Vec; #[cfg(all(feature = "alloc", not(feature = "std")))] use core::num; -#[cfg(target_arch = "wasm32")] -use instant::SystemTime; use serde::{Deserialize, Serialize}; -#[cfg(target_arch = "wasm32")] -const UNIX_EPOCH: SystemTime = SystemTime::UNIX_EPOCH; - /// Helper trait for acquiring time in `no_std` environments. pub trait TimeSupplier { /// The current time from the specified `TimeSupplier` @@ -61,24 +56,37 @@ impl TimeSupplier for InstantWasm32 { type Now = InstantWasm32; type StartingPoint = std::time::SystemTime; + fn now(&self) -> Self::StartingPoint { + SystemTime::now() + } + fn instant_now(&self) -> Self::Now { InstantWasm32::now() } - fn starting_point(&self) -> Self::Now { + fn duration_since_starting_point(&self, now: Self::StartingPoint) -> Duration { + now.duration_since(self.starting_point()) + .expect("duration_since panicked") + } + + fn starting_point(&self) -> Self::StartingPoint { std::time::UNIX_EPOCH } - fn elapsed_since(&self, now: Self::Now, since: Self::Now) -> Duration { + fn elapsed_instant_since(&self, now: Self::Now, since: Self::Now) -> Duration { now - since } + fn elapsed_since(&self, now: Self::StartingPoint, since: Self::StartingPoint) -> Duration { + now.duration_since(since).expect("duration_since panicked") + } + fn as_i64(&self, duration: Duration) -> i64 { duration.as_millis() as i64 } fn to_timestamp(&self, duration: Duration) -> Timestamp { - Timestamp(duration.as_millis() as i64) + Timestamp(self.as_i64(duration)) } } From 7b1a4f343d8650521075e252af335c4a00bda32e Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 12 May 2023 12:07:04 +0200 Subject: [PATCH 75/77] partially revert examples modification --- crates/nostr-sdk/README.md | 1 - crates/nostr-sdk/examples/client-with-opts.rs | 3 -- crates/nostr-sdk/examples/client.rs | 2 - crates/nostr-sdk/examples/nostr-connect.rs | 6 --- crates/nostr-sdk/src/client/mod.rs | 47 +++++++------------ crates/nostr-sdk/src/client/signer/remote.rs | 3 -- crates/nostr/README.md | 6 --- crates/nostr/examples/nip13.rs | 4 -- 8 files changed, 18 insertions(+), 54 deletions(-) diff --git a/crates/nostr-sdk/README.md b/crates/nostr-sdk/README.md index 6cb63e5fc..fab308af1 100644 --- a/crates/nostr-sdk/README.md +++ b/crates/nostr-sdk/README.md @@ -32,7 +32,6 @@ tokio = { version = "1", features = ["full"] } use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; use nostr_sdk::prelude::*; -use nostr_sdk::key::XOnlyPublicKey; #[tokio::main] async fn main() -> Result<()> { diff --git a/crates/nostr-sdk/examples/client-with-opts.rs b/crates/nostr-sdk/examples/client-with-opts.rs index a341baad5..a9ed3dd08 100644 --- a/crates/nostr-sdk/examples/client-with-opts.rs +++ b/crates/nostr-sdk/examples/client-with-opts.rs @@ -3,9 +3,6 @@ use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4}; -use nostr_sdk::key::SecretKey; -use nostr_sdk::nips::nip04::decrypt; -use nostr_sdk::prelude::FromBech32; use nostr_sdk::prelude::*; const BECH32_SK: &str = "nsec1ufnus6pju578ste3v90xd5m2decpuzpql2295m3sknqcjzyys9ls0qlc85"; diff --git a/crates/nostr-sdk/examples/client.rs b/crates/nostr-sdk/examples/client.rs index 45f25aded..cb25a2442 100644 --- a/crates/nostr-sdk/examples/client.rs +++ b/crates/nostr-sdk/examples/client.rs @@ -1,8 +1,6 @@ // Copyright (c) 2022-2023 Yuki Kishimoto // Distributed under the MIT software license -use nostr_sdk::key::SecretKey; -use nostr_sdk::prelude::FromBech32; use nostr_sdk::prelude::*; const BECH32_SK: &str = "nsec1ufnus6pju578ste3v90xd5m2decpuzpql2295m3sknqcjzyys9ls0qlc85"; diff --git a/crates/nostr-sdk/examples/nostr-connect.rs b/crates/nostr-sdk/examples/nostr-connect.rs index e538955c3..fbfa72dad 100644 --- a/crates/nostr-sdk/examples/nostr-connect.rs +++ b/crates/nostr-sdk/examples/nostr-connect.rs @@ -3,12 +3,6 @@ use std::time::Duration; -use nostr_sdk::client::RemoteSigner; -use nostr_sdk::key::SecretKey; -use nostr_sdk::key::XOnlyPublicKey; -use nostr_sdk::nips::nip46::NostrConnectMetadata; -use nostr_sdk::nips::nip46::NostrConnectURI; -use nostr_sdk::prelude::FromBech32; use nostr_sdk::prelude::*; const APP_SECRET_KEY: &str = "nsec1j4c6269y9w0q2er2xjw8sv2ehyrtfxq3jwgdlxj6qfn8z4gjsq5qfvfk99"; diff --git a/crates/nostr-sdk/src/client/mod.rs b/crates/nostr-sdk/src/client/mod.rs index a180e6225..d437c309d 100644 --- a/crates/nostr-sdk/src/client/mod.rs +++ b/crates/nostr-sdk/src/client/mod.rs @@ -120,7 +120,6 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr::Keys; /// use nostr_sdk::prelude::*; /// /// let my_keys = Keys::generate(); @@ -134,7 +133,7 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// /// let my_keys = Keys::generate(); @@ -224,7 +223,7 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// /// # #[tokio::main] @@ -263,7 +262,7 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// /// # #[tokio::main] @@ -309,7 +308,7 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { @@ -355,7 +354,7 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// /// # #[tokio::main] @@ -386,7 +385,7 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// /// # #[tokio::main] @@ -415,7 +414,7 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { @@ -432,7 +431,7 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { @@ -449,7 +448,7 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { @@ -478,8 +477,7 @@ impl Client { /// # Example /// ```rust,no_run /// use std::time::Duration; - /// - /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { @@ -611,7 +609,7 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { @@ -638,7 +636,7 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { @@ -664,7 +662,7 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { @@ -728,8 +726,7 @@ impl Client { /// # Example /// ```rust,no_run /// use std::time::Duration; - /// - /// use nostr::Keys; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { @@ -827,9 +824,7 @@ impl Client { /// /// # Example /// ```rust,no_run - /// use nostr::Keys; - /// use nostr_sdk::key::XOnlyPublicKey; - /// use nostr_sdk::prelude::FromBech32; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { @@ -915,9 +910,7 @@ impl Client { /// # Example /// ```rust,no_run /// use std::str::FromStr; - /// - /// use nostr::Keys; - /// use nostr_sdk::key::XOnlyPublicKey; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { @@ -950,9 +943,7 @@ impl Client { /// # Example /// ```rust,no_run /// use std::str::FromStr; - /// - /// use nostr::Keys; - /// use nostr_sdk::key::XOnlyPublicKey; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { @@ -985,9 +976,7 @@ impl Client { /// # Example /// ```rust,no_run /// use std::str::FromStr; - /// - /// use nostr::Keys; - /// use nostr_sdk::key::XOnlyPublicKey; + /// use nostr_sdk::prelude::*; /// # #[tokio::main] /// # async fn main() { diff --git a/crates/nostr-sdk/src/client/signer/remote.rs b/crates/nostr-sdk/src/client/signer/remote.rs index 4d574b02d..7b18d9db6 100644 --- a/crates/nostr-sdk/src/client/signer/remote.rs +++ b/crates/nostr-sdk/src/client/signer/remote.rs @@ -65,7 +65,6 @@ impl Client { /// ```rust,no_run /// use std::time::Duration; /// - /// use nostr_sdk::client::RemoteSigner; /// use nostr_sdk::prelude::*; /// /// #[tokio::main] @@ -87,8 +86,6 @@ impl Client { /// ```rust,no_run /// use std::str::FromStr; /// - /// use nostr_sdk::client::RemoteSigner; - /// use nostr_sdk::key::XOnlyPublicKey; /// use nostr_sdk::prelude::*; /// /// #[tokio::main] diff --git a/crates/nostr/README.md b/crates/nostr/README.md index 6cf5c3bae..214aeecbc 100644 --- a/crates/nostr/README.md +++ b/crates/nostr/README.md @@ -24,12 +24,6 @@ tungstenite = { version = "0.18", features = ["rustls-tls-webpki-roots"]} ```rust,no_run use nostr::prelude::*; -use nostr::Keys; -use nostr::Event; -use nostr::Metadata; -use nostr::EventBuilder; -use nostr::ClientMessage; -use crate::nostr::nips::nip19::ToBech32; use tungstenite::{Message as WsMessage}; fn main() -> Result<()> { diff --git a/crates/nostr/examples/nip13.rs b/crates/nostr/examples/nip13.rs index a8efc17c8..ccf2c9fc2 100644 --- a/crates/nostr/examples/nip13.rs +++ b/crates/nostr/examples/nip13.rs @@ -3,11 +3,7 @@ use std::str::FromStr; -use nostr::key::SecretKey; use nostr::prelude::*; -use nostr::Event; -use nostr::EventBuilder; -use nostr::Keys; const ALICE_SK: &str = "6b911fd37cdf5c81d4c0adb1ab7fa822ed253ab0ad9aa18d77257c88b29b718e"; From 2add30333d06f27180e24984729020fd6604f967 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 12 May 2023 13:21:23 +0200 Subject: [PATCH 76/77] fix preludes --- crates/nostr-sdk/src/prelude.rs | 4 ++-- crates/nostr/src/prelude.rs | 14 +++++++------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/crates/nostr-sdk/src/prelude.rs b/crates/nostr-sdk/src/prelude.rs index eb7bca6b4..dc6e9d520 100644 --- a/crates/nostr-sdk/src/prelude.rs +++ b/crates/nostr-sdk/src/prelude.rs @@ -7,6 +7,6 @@ pub use nostr::prelude::*; // Internal modules -pub use crate::client; -pub use crate::relay; +pub use crate::client::*; +pub use crate::relay::*; pub use crate::*; diff --git a/crates/nostr/src/prelude.rs b/crates/nostr/src/prelude.rs index 6da547e1f..2a20b4473 100644 --- a/crates/nostr/src/prelude.rs +++ b/crates/nostr/src/prelude.rs @@ -36,17 +36,17 @@ pub use crate::SECP256K1; // NIPs #[cfg(feature = "nip04")] -pub use crate::nips::nip04; +pub use crate::nips::nip04::*; #[cfg(feature = "nip05")] -pub use crate::nips::nip05; +pub use crate::nips::nip05::*; #[cfg(feature = "nip06")] -pub use crate::nips::nip06; +pub use crate::nips::nip06::*; #[cfg(feature = "nip11")] -pub use crate::nips::nip11; -pub use crate::nips::nip13; +pub use crate::nips::nip11::*; +pub use crate::nips::nip13::*; #[cfg(feature = "nip19")] pub use crate::nips::nip19::*; pub use crate::nips::nip26::*; #[cfg(feature = "nip46")] -pub use crate::nips::nip46; -pub use crate::nips::nip65; +pub use crate::nips::nip46::*; +pub use crate::nips::nip65::*; From b389fdbac77b2c94a130d053b53cb4c3c17ee3a7 Mon Sep 17 00:00:00 2001 From: Szilard Parrag Date: Fri, 12 May 2023 13:35:01 +0200 Subject: [PATCH 77/77] nostr/message/subscription: remove duplicate fmt import --- crates/nostr/src/message/subscription.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/crates/nostr/src/message/subscription.rs b/crates/nostr/src/message/subscription.rs index 3bc81df28..84ab313c1 100644 --- a/crates/nostr/src/message/subscription.rs +++ b/crates/nostr/src/message/subscription.rs @@ -7,8 +7,6 @@ #![allow(missing_docs)] use core::fmt; -#[cfg(all(feature = "alloc", not(feature = "std")))] -use alloc::fmt; #[cfg(all(feature = "alloc", not(feature = "std")))] use alloc::string::{String, ToString}; #[cfg(all(feature = "alloc", not(feature = "std")))]