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

core: replace secp256k with k256 in crypto::ecdsa #3525

Merged
merged 23 commits into from
Mar 9, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
fa7589c
core: crypto/ecdsa switch to k256
michalkucharczyk Feb 29, 2024
d6cf147
Cargo.lock
michalkucharczyk Feb 29, 2024
682ddf0
fixes for no-std
michalkucharczyk Feb 29, 2024
277068b
Cargo.lock
michalkucharczyk Feb 29, 2024
80b133e
".git/.scripts/commands/fmt/fmt.sh"
Feb 29, 2024
35878b2
seed doc improved
michalkucharczyk Mar 1, 2024
e63fbac
secp256k1 is used on host
michalkucharczyk Mar 4, 2024
7db5674
Cargo.lock
michalkucharczyk Mar 4, 2024
93086ec
features fix
michalkucharczyk Mar 4, 2024
42bb70c
make clippy happy
michalkucharczyk Mar 4, 2024
0fc7201
backend features removed: std/no-std used
michalkucharczyk Mar 4, 2024
8b4c147
Merge branch 'master' into mku-k256-in-core-crypto-ecdsa
michalkucharczyk Mar 4, 2024
0ff4aa2
Apply suggestions from code review
michalkucharczyk Mar 4, 2024
1ab98f6
taplo for frame/support/Cargo.toml
michalkucharczyk Mar 4, 2024
6797ec4
fixes
michalkucharczyk Mar 4, 2024
461998e
minor fixes
michalkucharczyk Mar 5, 2024
2d468dd
Merge remote-tracking branch 'origin/master' into mku-k256-in-core-cr…
michalkucharczyk Mar 5, 2024
237b155
Merge branch 'master' into mku-k256-in-core-crypto-ecdsa
michalkucharczyk Mar 6, 2024
2349f61
Merge branch 'master' into mku-k256-in-core-crypto-ecdsa
michalkucharczyk Mar 8, 2024
c6d3bf2
Update substrate/primitives/core/src/ecdsa.rs
michalkucharczyk Mar 8, 2024
38de881
Update substrate/primitives/core/Cargo.toml
michalkucharczyk Mar 8, 2024
b5ddea9
Merge branch 'master' into mku-k256-in-core-crypto-ecdsa
michalkucharczyk Mar 8, 2024
b7b215a
Revert "Update substrate/primitives/core/Cargo.toml"
michalkucharczyk Mar 8, 2024
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
15 changes: 8 additions & 7 deletions Cargo.lock

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

5 changes: 1 addition & 4 deletions substrate/primitives/core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ blake2 = { version = "0.10.4", default-features = false, optional = true }
libsecp256k1 = { version = "0.7", default-features = false, features = ["static-context"], optional = true }
schnorrkel = { version = "0.11.4", features = ["preaudit_deprecated"], default-features = false }
merlin = { version = "3.0", default-features = false }
secp256k1 = { version = "0.28.0", default-features = false, features = ["alloc", "recovery"], optional = true }
sp-crypto-hashing = { path = "../crypto/hashing", default-features = false, optional = true }
sp-runtime-interface = { path = "../runtime-interface", default-features = false }
k256 = { version = "0.13.3", features = ["ecdsa"] }

# bls crypto
w3f-bls = { version = "0.1.3", default-features = false, optional = true }
Expand Down Expand Up @@ -105,8 +105,6 @@ std = [
"rand",
"scale-info/std",
"schnorrkel/std",
"secp256k1/global-context",
"secp256k1/std",
"secrecy/alloc",
"serde/std",
"sp-crypto-hashing/std",
Expand Down Expand Up @@ -147,7 +145,6 @@ full_crypto = [
"blake2",
"ed25519-zebra",
"libsecp256k1",
"secp256k1",
"sp-crypto-hashing",
"sp-runtime-interface/disable_target_static_assertions",
]
Expand Down
99 changes: 34 additions & 65 deletions substrate/primitives/core/src/ecdsa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,7 @@ use crate::crypto::{
};
#[cfg(feature = "full_crypto")]
use crate::crypto::{DeriveError, DeriveJunction, Pair as TraitPair, SecretStringError};
#[cfg(all(feature = "full_crypto", not(feature = "std")))]
use secp256k1::Secp256k1;
#[cfg(feature = "std")]
use secp256k1::SECP256K1;
#[cfg(feature = "full_crypto")]
use secp256k1::{
ecdsa::{RecoverableSignature, RecoveryId},
Message, PublicKey, SecretKey,
};
use k256::ecdsa::{RecoveryId, SigningKey, VerifyingKey};
#[cfg(feature = "serde")]
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
#[cfg(all(not(feature = "std"), feature = "serde"))]
Expand All @@ -53,7 +45,7 @@ pub const PUBLIC_KEY_SERIALIZED_SIZE: usize = 33;
/// The byte length of signature
pub const SIGNATURE_SERIALIZED_SIZE: usize = 65;

/// A secret seed (which is bytewise essentially equivalent to a SecretKey).
michalkucharczyk marked this conversation as resolved.
Show resolved Hide resolved
/// A secret seed (which is bytewise essentially equivalent to a SigningKey).
///
/// We need it as a different type because `Seed` is expected to be AsRef<[u8]>.
#[cfg(feature = "full_crypto")]
Expand Down Expand Up @@ -103,11 +95,11 @@ impl Public {
let mut tagged_full = [0u8; 65];
tagged_full[0] = 0x04;
tagged_full[1..].copy_from_slice(full);
secp256k1::PublicKey::from_slice(&tagged_full)
VerifyingKey::from_sec1_bytes(&tagged_full)
} else {
secp256k1::PublicKey::from_slice(full)
VerifyingKey::from_sec1_bytes(full)
};
pubkey.map(|k| Self(k.serialize())).map_err(|_| ())
pubkey.map(|k| k.into()).map_err(|_| ())
}
}

Expand All @@ -131,6 +123,16 @@ impl AsMut<[u8]> for Public {
}
}

impl From<VerifyingKey> for Public {
fn from(pubkey: VerifyingKey) -> Self {
Self::unchecked_from(
pubkey.to_sec1_bytes()[..]
.try_into()
.expect("valid key is serializable to [u8,33]. qed."),
Copy link
Contributor Author

Choose a reason for hiding this comment

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

double-check needed here. Can we actually fail?

)
}
}

impl TryFrom<&[u8]> for Public {
type Error = ();

Expand Down Expand Up @@ -331,30 +333,19 @@ impl Signature {
/// Recover the public key from this signature and a pre-hashed message.
#[cfg(feature = "full_crypto")]
pub fn recover_prehashed(&self, message: &[u8; 32]) -> Option<Public> {
let rid = RecoveryId::from_i32(self.0[64] as i32).ok()?;
let sig = RecoverableSignature::from_compact(&self.0[..64], rid).ok()?;
let message = Message::from_digest_slice(message).expect("Message is 32 bytes; qed");

#[cfg(feature = "std")]
let context = SECP256K1;
#[cfg(not(feature = "std"))]
let context = Secp256k1::verification_only();
let rid = RecoveryId::from_byte(self.0[64])?;
let sig = k256::ecdsa::Signature::from_bytes((&self.0[..64]).into()).ok()?;

context
.recover_ecdsa(&message, &sig)
.ok()
.map(|pubkey| Public(pubkey.serialize()))
VerifyingKey::recover_from_prehash(message, &sig, rid).map(|p| p.into()).ok()
}
}

#[cfg(feature = "full_crypto")]
impl From<RecoverableSignature> for Signature {
fn from(recsig: RecoverableSignature) -> Signature {
impl From<(k256::ecdsa::Signature, RecoveryId)> for Signature {
Copy link
Contributor Author

@michalkucharczyk michalkucharczyk Feb 29, 2024

Choose a reason for hiding this comment

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

note: (k256::ecdsa::Signature, RecoveryId) is a result of sign_prehash_recoverable. Convenient From.

fn from(recsig: (k256::ecdsa::Signature, RecoveryId)) -> Signature {
let mut r = Self::default();
let (recid, sig) = recsig.serialize_compact();
r.0[..64].copy_from_slice(&sig);
// This is safe due to the limited range of possible valid ids.
r.0[64] = recid.to_i32() as u8;
r.0[..64].copy_from_slice(&recsig.0.to_bytes());
r.0[64] = recsig.1.to_byte();
r
}
}
Expand All @@ -370,7 +361,7 @@ fn derive_hard_junction(secret_seed: &Seed, cc: &[u8; 32]) -> Seed {
#[derive(Clone)]
pub struct Pair {
public: Public,
secret: SecretKey,
secret: SigningKey,
}

#[cfg(feature = "full_crypto")]
Expand All @@ -385,16 +376,8 @@ impl TraitPair for Pair {
/// You should never need to use this; generate(), generate_with_phrase
fn from_seed_slice(seed_slice: &[u8]) -> Result<Pair, SecretStringError> {
let secret =
SecretKey::from_slice(seed_slice).map_err(|_| SecretStringError::InvalidSeedLength)?;

#[cfg(feature = "std")]
let context = SECP256K1;
#[cfg(not(feature = "std"))]
let context = Secp256k1::signing_only();

let public = PublicKey::from_secret_key(&context, &secret);
let public = Public(public.serialize());
Ok(Pair { public, secret })
SigningKey::from_slice(seed_slice).map_err(|_| SecretStringError::InvalidSeedLength)?;
Ok(Pair { public: VerifyingKey::from(&secret).into(), secret })
}

/// Derive a child key from a series of given junctions.
Expand Down Expand Up @@ -438,7 +421,7 @@ impl TraitPair for Pair {
impl Pair {
/// Get the seed for this key.
pub fn seed(&self) -> Seed {
self.secret.secret_bytes()
self.secret.to_bytes().into()
}

/// Exactly as `from_string` except that if no matches are found then, the the first 32
Expand All @@ -455,14 +438,10 @@ impl Pair {

/// Sign a pre-hashed message
pub fn sign_prehashed(&self, message: &[u8; 32]) -> Signature {
let message = Message::from_digest_slice(message).expect("Message is 32 bytes; qed");

#[cfg(feature = "std")]
let context = SECP256K1;
#[cfg(not(feature = "std"))]
let context = Secp256k1::signing_only();

context.sign_ecdsa_recoverable(&message, &self.secret).into()
self.secret
.sign_prehash_recoverable(message)
.expect("signing may not fail (???). qed.")
Copy link
Contributor Author

@michalkucharczyk michalkucharczyk Feb 29, 2024

Choose a reason for hiding this comment

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

In our API (e.g. TraitPair) we assume signing cannot fail (return type is not Option or Result).
Is expect fine here? What would be condition for potential failure?

.into()
}

/// Verify a signature on a pre-hashed message. Return `true` if the signature is valid
Expand Down Expand Up @@ -498,18 +477,6 @@ impl Pair {
}
}

// The `secp256k1` backend doesn't implement cleanup for their private keys.
// Currently we should take care of wiping the secret from memory.
// NOTE: this solution is not effective when `Pair` is moved around memory.
// The very same problem affects other cryptographic backends that are just using
// `zeroize`for their secrets.
#[cfg(feature = "full_crypto")]
impl Drop for Pair {
fn drop(&mut self) {
self.secret.non_secure_erase()
}
}

michalkucharczyk marked this conversation as resolved.
Show resolved Hide resolved
impl CryptoType for Public {
#[cfg(feature = "full_crypto")]
type Pair = Pair;
Expand Down Expand Up @@ -770,8 +737,10 @@ mod test {
let msg = [0u8; 32];
let sig1 = pair.sign_prehashed(&msg);
let sig2: Signature = {
let message = Message::from_digest_slice(&msg).unwrap();
SECP256K1.sign_ecdsa_recoverable(&message, &pair.secret).into()
pair.secret
.sign_prehash_recoverable(&msg)
.expect("signing may not fail (???). qed.")
.into()
};
assert_eq!(sig1, sig2);

Expand Down
Loading