Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

key-utils: make it no_std with a std default feature #1398

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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions roles/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions utils/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 8 additions & 2 deletions utils/key-utils/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,15 @@ name = "key-utils-bin"
path = "src/main.rs"

[dependencies]
bs58 = { version ="0.4.0", features = ["check"] }
secp256k1 = { version = "0.28.2", default-features = false, features =["alloc","rand","rand-std"] }
bs58 = { version ="0.4.0", default-features = false, features = ["check", "alloc"] }
secp256k1 = { version = "0.28.2", default-features = false, features =["alloc","rand"] }
serde = { version = "1.0.89", features = ["derive","alloc"], default-features = false }
rand = {version = "0.8.5", default-features = false }
rustversion = "1.0"

[dev-dependencies]
toml = { version = "0.5.6", git = "https://github.com/diondokter/toml-rs", default-features = false, rev = "c4161aa" }

[features]
default = ["std"]
std = ["bs58/std","secp256k1/rand-std", "rand/std", "rand/std_rng"]
39 changes: 32 additions & 7 deletions utils/key-utils/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
#![cfg_attr(not(feature = "std"), no_std)]

extern crate alloc;

use alloc::{
string::{String, ToString},
vec::Vec,
};
use bs58::{decode, decode::Error as Bs58DecodeError};
use core::convert::TryFrom;
use core::{convert::TryFrom, fmt::Display, str::FromStr};
use secp256k1::{
schnorr::Signature, Keypair, Message as SecpMessage, Secp256k1, SecretKey, SignOnly,
VerifyOnly, XOnlyPublicKey,
};
use serde::{Deserialize, Serialize};
use std::{fmt::Display, str::FromStr};

#[derive(Debug)]
pub enum Error {
Expand All @@ -17,7 +24,7 @@ pub enum Error {
}

impl Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Bs58Decode(error) => write!(f, "Base58 code error: {error}"),
Self::Secp256k1(error) => write!(f, "Secp256k1 error: {error}"),
Expand All @@ -30,7 +37,11 @@ impl Display for Error {
}
}

#[cfg(feature = "std")]
impl std::error::Error for Error {}
#[cfg(not(feature = "std"))]
#[rustversion::since(1.81)]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this added? why we want the core:error::Error implemenation only after 1.81?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

core::error::Error trait has been added on Rust 1.81, so this is the way we implement it, only if toolchain is recent enough.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

will it still work if Rust is smaller than this? the MSRV on SRI is 1.75

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's the purpose of the rustversion macro. If Rusty version is before 1.81 (like 1.75) the core::error::Error trait is not implemented (because it does not exist). If we use a newer Rust, then it is implemented and user can profit from it.

In the end, using this rustversion macro is to not have to bump MSRV to 1.81 just for this trait, but letting user can profit from it if they need.

impl core::error::Error for Error {}

impl From<Bs58DecodeError> for Error {
fn from(e: Bs58DecodeError) -> Self {
Expand Down Expand Up @@ -73,7 +84,7 @@ impl From<Secp256k1SecretKey> for String {
}

impl Display for Secp256k1SecretKey {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
let bytes = self.0.secret_bytes();
f.write_str(&bs58::encode(bytes).with_check().into_string())
}
Expand Down Expand Up @@ -116,7 +127,7 @@ impl From<Secp256k1PublicKey> for String {
}

impl Display for Secp256k1PublicKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let mut output = [0_u8; 34];
output[0] = 1;
let bytes = self.0.serialize();
Expand Down Expand Up @@ -157,12 +168,26 @@ impl SignatureService {
}
}

#[cfg(feature = "std")]
pub fn sign(&self, message: Vec<u8>, private_key: SecretKey) -> Signature {
self.sign_with_rng(message, private_key, &mut rand::thread_rng())
}

#[inline]
pub fn sign_with_rng<R: rand::Rng + rand::CryptoRng>(
Georges760 marked this conversation as resolved.
Show resolved Hide resolved
&self,
message: Vec<u8>,
private_key: SecretKey,
rng: &mut R,
) -> Signature {
let secret_key = private_key;
let kp = Keypair::from_secret_key(&self.secp_sign, &secret_key);

self.secp_sign
.sign_schnorr(&SecpMessage::from_digest_slice(&message).unwrap(), &kp)
self.secp_sign.sign_schnorr_with_rng(
&SecpMessage::from_digest_slice(&message).unwrap(),
&kp,
rng,
)
}

pub fn verify(
Expand Down
7 changes: 7 additions & 0 deletions utils/key-utils/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
#[cfg(feature = "std")]
use ::key_utils::{Secp256k1PublicKey, Secp256k1SecretKey};
#[cfg(feature = "std")]
use secp256k1::{rand, Keypair, Secp256k1};

#[cfg(feature = "std")]
fn generate_key() -> (Secp256k1SecretKey, Secp256k1PublicKey) {
let secp = Secp256k1::new();
let (secret_key, _) = secp.generate_keypair(&mut rand::thread_rng());
Expand All @@ -15,10 +18,14 @@ fn generate_key() -> (Secp256k1SecretKey, Secp256k1PublicKey) {
}
}

#[cfg(feature = "std")]
fn main() {
let (secret, public) = generate_key();
let secret: String = secret.into();
let public: String = public.into();
println!("Secret Key: {}", secret);
println!("Public Key: {}", public);
}

#[cfg(not(feature = "std"))]
fn main() {}
Loading