aboutsummaryrefslogtreecommitdiff
path: root/src/account
diff options
context:
space:
mode:
authorNicholas Rodrigues Lordello <[email protected]>2022-05-03 07:59:24 +0200
committerNicholas Rodrigues Lordello <[email protected]>2022-05-03 07:59:24 +0200
commit2cf5f650b8fdbd1992f3d65ad6e102087e74f896 (patch)
tree7c501fcd82b33a6203cb6b55c4820d698c1d83e5 /src/account
parent1c13a451bc2e56ce8531d5da683a3c7aa6d4d887 (diff)
Use Rust Secp256k1 implementation from RustCrypto project (#92)
This PR ports `hdwallet` to use the `k256` crate - a native Rust implementation of secp256k1 elliptic curve and ECDSA signing. The motivation for this change is that we can just use the `wasm32-wasi` Rust target without requiring a WASI C toolchain! Notice that the CI no longer requires installing the WASI SDK in order to build the WASI target.
Diffstat (limited to 'src/account')
-rw-r--r--src/account/prehashed.rs61
-rw-r--r--src/account/public.rs17
-rw-r--r--src/account/signature.rs91
3 files changed, 124 insertions, 45 deletions
diff --git a/src/account/prehashed.rs b/src/account/prehashed.rs
new file mode 100644
index 0000000..5952164
--- /dev/null
+++ b/src/account/prehashed.rs
@@ -0,0 +1,61 @@
+//! The `k256` crate only supports signing messages by passing message bytes and
+//! specifying a hasher, or specifying an already partially updated hasher.
+//!
+//! This module provides a `Digest` implementation that can be used as an
+//! allowing `k256` signing to be done on a prehashed messsage.
+
+use k256::ecdsa::digest::{
+ consts::U32, generic_array::GenericArray, BlockInput, FixedOutput, Reset, Update,
+};
+use sha2::{digest::core_api::BlockSizeUser, Digest as _, Sha256};
+use std::mem;
+
+/// A pre-hashed meessage.
+#[derive(Clone)]
+pub enum Prehashed {
+ /// The pre-hashed message to use for signing.
+ Message([u8; 32]),
+ /// The hasher used for rfc-6979 nonce generation for deterministic ECDSA
+ /// signature computation.
+ Rfc6979(Sha256),
+}
+
+impl Default for Prehashed {
+ fn default() -> Self {
+ Self::Rfc6979(Sha256::default())
+ }
+}
+
+impl BlockInput for Prehashed {
+ type BlockSize = <Sha256 as BlockSizeUser>::BlockSize;
+}
+
+impl FixedOutput for Prehashed {
+ type OutputSize = U32;
+
+ fn finalize_into(self, out: &mut GenericArray<u8, Self::OutputSize>) {
+ match self {
+ Self::Message(message) => *out = message.into(),
+ Self::Rfc6979(hasher) => hasher.finalize_into(out),
+ }
+ }
+
+ fn finalize_into_reset(&mut self, out: &mut GenericArray<u8, Self::OutputSize>) {
+ mem::take(self).finalize_into(out)
+ }
+}
+
+impl Reset for Prehashed {
+ fn reset(&mut self) {
+ *self = Default::default();
+ }
+}
+
+impl Update for Prehashed {
+ fn update(&mut self, data: impl AsRef<[u8]>) {
+ match self {
+ Prehashed::Message(_) => unimplemented!(),
+ Prehashed::Rfc6979(hasher) => hasher.update(data),
+ }
+ }
+}
diff --git a/src/account/public.rs b/src/account/public.rs
new file mode 100644
index 0000000..c5d0aec
--- /dev/null
+++ b/src/account/public.rs
@@ -0,0 +1,17 @@
+//! Module implementing public key operations.
+
+use k256::elliptic_curve::sec1::ToEncodedPoint as _;
+
+/// A public key.
+pub struct PublicKey(pub k256::PublicKey);
+
+impl PublicKey {
+ /// Returns an uncompressed encoded bytes for the public key.
+ pub fn encode_uncompressed(&self) -> [u8; 65] {
+ self.0
+ .to_encoded_point(false)
+ .as_bytes()
+ .try_into()
+ .expect("unexpected uncompressed private key length")
+ }
+}
diff --git a/src/account/signature.rs b/src/account/signature.rs
index f017756..5afa0ca 100644
--- a/src/account/signature.rs
+++ b/src/account/signature.rs
@@ -1,44 +1,37 @@
//! Module containing signature data model.
-use ethnum::{AsU256, U256};
+use ethnum::{AsU256 as _, U256};
+use k256::ecdsa::recoverable;
use std::fmt::{self, Display, Formatter};
-/// The parity of the y-value of a secp256k1 signature.
-#[derive(Clone, Copy, Debug, Eq, PartialEq)]
-#[repr(u8)]
-pub enum YParity {
- /// Even parity.
- Even = 0,
- /// Odd parity.
- Odd = 1,
-}
-
-impl AsU256 for YParity {
- fn as_u256(self) -> U256 {
- U256::new(self as _)
- }
-}
-
/// A secp256k1 signature.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
-pub struct Signature {
- /// Signature V value in Electrum notation.
- pub y_parity: YParity,
- /// Signature R value.
- pub r: [u8; 32],
- /// Signature S value.
- pub s: [u8; 32],
-}
+pub struct Signature(pub recoverable::Signature);
impl Signature {
- /// Returns the signature's V value in Electrum notation.
- pub fn v(&self) -> u8 {
- 27 + (self.y_parity as u8)
+ /// Returns the y-parity in its 256-bit integer representation.
+ ///
+ /// Return 0 for even parity, and 1 for odd parity.
+ pub fn y_parity(&self) -> U256 {
+ u8::from(self.0.recovery_id()).as_u256()
}
/// Returns the signature's V value with EIP-155 chain replay protection.
- pub fn v_replay_protected(&self, chain_id: U256) -> U256 {
- self.y_parity.as_u256() + chain_id * 2 + 35
+ pub fn v(&self, chain_id: Option<U256>) -> U256 {
+ match chain_id {
+ Some(chain_id) => self.y_parity() + chain_id * 2 + 35,
+ None => self.y_parity() + 27,
+ }
+ }
+
+ /// Returns the signature's 32-byte R-value in big-endian representation.
+ pub fn r(&self) -> U256 {
+ U256::from_be_bytes(self.0.r().to_bytes().into())
+ }
+
+ /// Returns the signature's 32-byte S-value in big-endian representation.
+ pub fn s(&self) -> U256 {
+ U256::from_be_bytes(self.0.s().to_bytes().into())
}
}
@@ -46,10 +39,10 @@ impl Display for Signature {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(
f,
- "0x{}{}{:02x}",
- hex::encode(&self.r),
- hex::encode(&self.s),
- self.v(),
+ "0x{:064x}{:064x}{:02x}",
+ self.r(),
+ self.s(),
+ self.v(None),
)
}
}
@@ -57,24 +50,32 @@ impl Display for Signature {
#[cfg(test)]
mod tests {
use super::*;
+ use k256::ecdsa::{self, recoverable::Id};
+
+ impl Signature {
+ /// Creates a signature from its raw parts.
+ ///
+ /// Convinience method used for testing.
+ pub fn from_parts(y_parity: u8, r: [u8; 32], s: [u8; 32]) -> Self {
+ Self(
+ recoverable::Signature::new(
+ &ecdsa::Signature::from_scalars(r, s).unwrap(),
+ Id::new(y_parity).unwrap(),
+ )
+ .unwrap(),
+ )
+ }
+ }
#[test]
fn replay_protection() {
- let signature = Signature {
- y_parity: YParity::Even,
- r: [1; 32],
- s: [2; 32],
- };
- assert_eq!(signature.v_replay_protected(U256::new(1)), U256::new(37));
+ let signature = Signature::from_parts(0, [1; 32], [2; 32]);
+ assert_eq!(signature.v(Some(U256::new(1))), U256::new(37));
}
#[test]
fn signature_to_string() {
- let signature = Signature {
- y_parity: YParity::Even,
- r: [1; 32],
- s: [2; 32],
- };
+ let signature = Signature::from_parts(0, [1; 32], [2; 32]);
assert_eq!(
signature.to_string(),
"0x0101010101010101010101010101010101010101010101010101010101010101\