aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.github/workflows/release.yml10
-rw-r--r--.github/workflows/rust.yml4
-rw-r--r--Cargo.lock273
-rw-r--r--Cargo.toml4
-rw-r--r--src/account.rs74
-rw-r--r--src/account/prehashed.rs61
-rw-r--r--src/account/public.rs17
-rw-r--r--src/account/signature.rs91
-rw-r--r--src/cmd/public_key.rs2
-rw-r--r--src/hdk.rs32
-rw-r--r--src/transaction/eip1559.rs12
-rw-r--r--src/transaction/eip2930.rs9
-rw-r--r--src/transaction/legacy.rs13
13 files changed, 430 insertions, 172 deletions
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index cd321bd..8462ede 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -13,16 +13,12 @@ jobs:
- name: Build
run: |
- curl -sL https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-14/wasi-sdk_14.0_amd64.deb -o /tmp/wasi-sdk.deb
- sudo dpkg -i /tmp/wasi-sdk.deb
rustup target add wasm32-wasi
- CC=/opt/wasi-sdk/bin/clang cargo build --release --target wasm32-wasi
+ cargo build --release --target wasm32-wasi
- name: Optimize
run: |
- sudo apt-get update && sudo apt-get install binaryen wabt
- wasm2wat target/wasm32-wasi/release/hdwallet.wasm | grep -v '^\s*(export "rustsecp256k1_' > target/wasm32-wasi/release/hdwallet.exp.wat
- wat2wasm target/wasm32-wasi/release/hdwallet.exp.wat -o target/wasm32-wasi/release/hdwallet.exp.wasm
- wasm-opt target/wasm32-wasi/release/hdwallet.exp.wasm -O4 -o target/wasm32-wasi/release/hdwallet.opt.wasm --strip-debug --strip-producers
+ sudo apt-get update && sudo apt-get install binaryen
+ wasm-opt target/wasm32-wasi/release/hdwallet.wasm -O4 -o target/wasm32-wasi/release/hdwallet.opt.wasm --strip-debug --strip-producers
- name: Release
id: create_release
diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml
index 8996ac4..b29cb3d 100644
--- a/.github/workflows/rust.yml
+++ b/.github/workflows/rust.yml
@@ -28,7 +28,5 @@ jobs:
- uses: actions/checkout@v2
- name: Build
run: |
- curl -sL https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-14/wasi-sdk_14.0_amd64.deb -o /tmp/wasi-sdk.deb
- sudo dpkg -i /tmp/wasi-sdk.deb
rustup target add wasm32-wasi
- CC=/opt/wasi-sdk/bin/clang cargo build --target wasm32-wasi
+ cargo build --target wasm32-wasi
diff --git a/Cargo.lock b/Cargo.lock
index d13dcb4..9e33a65 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -26,6 +26,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]]
+name = "base16ct"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "349a06037c7bf932dd7e7d1f653678b2038b9ad46a74102f1fc7bd7872678cce"
+
+[[package]]
+name = "base64ct"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dea908e7347a8c64e378c17e30ef880ad73e3b4498346b055c2c00ea342f3179"
+
+[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -33,18 +45,21 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "block-buffer"
-version = "0.10.2"
+version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0bf7fe51849ea569fd452f37822f606a5cabb684dc918707a0193fd4664ff324"
+checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4"
dependencies = [
"generic-array",
]
[[package]]
-name = "cc"
-version = "1.0.73"
+name = "block-buffer"
+version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11"
+checksum = "0bf7fe51849ea569fd452f37822f606a5cabb684dc918707a0193fd4664ff324"
+dependencies = [
+ "generic-array",
+]
[[package]]
name = "cfg-if"
@@ -92,6 +107,12 @@ dependencies = [
]
[[package]]
+name = "const-oid"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4c78c047431fee22c1a7bb92e00ad095a02a983affe4d8a72e2a2c62c1b94f3"
+
+[[package]]
name = "cpufeatures"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -101,6 +122,18 @@ dependencies = [
]
[[package]]
+name = "crypto-bigint"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "03c6a1d5fa1de37e071642dfa44ec552ca5b299adb128fab16138e24b548fd21"
+dependencies = [
+ "generic-array",
+ "rand_core",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
name = "crypto-common"
version = "0.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -111,23 +144,91 @@ dependencies = [
]
[[package]]
+name = "crypto-mac"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1d1a86f49236c215f271d40892d5fc950490551400b02ef360692c29815c714"
+dependencies = [
+ "generic-array",
+ "subtle",
+]
+
+[[package]]
+name = "der"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6919815d73839e7ad218de758883aae3a257ba6759ce7a9992501efbb53d705c"
+dependencies = [
+ "const-oid",
+]
+
+[[package]]
+name = "digest"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
name = "digest"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2fb860ca6fafa5552fb6d0e816a69c8e49f0908bf524e30a90d97c85892d506"
dependencies = [
- "block-buffer",
+ "block-buffer 0.10.2",
"crypto-common",
"subtle",
]
[[package]]
+name = "ecdsa"
+version = "0.13.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d0d69ae62e0ce582d56380743515fefaf1a8c70cec685d9677636d7e30ae9dc9"
+dependencies = [
+ "der",
+ "elliptic-curve",
+ "rfc6979",
+ "signature",
+]
+
+[[package]]
+name = "elliptic-curve"
+version = "0.11.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "25b477563c2bfed38a3b7a60964c49e058b2510ad3f12ba3483fd8f62c2306d6"
+dependencies = [
+ "base16ct",
+ "crypto-bigint",
+ "der",
+ "ff",
+ "generic-array",
+ "group",
+ "rand_core",
+ "sec1",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
name = "ethnum"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b40347dcad92b4dfeb9765c41c48503416daddf6dba55b74614dc035a43ed2"
[[package]]
+name = "ff"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2958d04124b9f27f175eaeb9a9f383d026098aa837eadd8ba22c11f13a05b9e"
+dependencies = [
+ "rand_core",
+ "subtle",
+]
+
+[[package]]
name = "generic-array"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -138,6 +239,28 @@ dependencies = [
]
[[package]]
+name = "getrandom"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "wasi",
+]
+
+[[package]]
+name = "group"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bc5ac374b108929de78460075f3dc439fa66df9d8fc77e8f12caa5165fcf0c89"
+dependencies = [
+ "ff",
+ "rand_core",
+ "subtle",
+]
+
+[[package]]
name = "hashbrown"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -145,20 +268,20 @@ checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e"
[[package]]
name = "hdwallet"
-version = "0.1.1"
+version = "0.2.0"
dependencies = [
"anyhow",
"clap",
"ethnum",
"hex",
"hex-literal",
- "hmac",
+ "hmac 0.12.1",
+ "k256",
"maplit",
"pbkdf2",
- "secp256k1",
"serde",
"serde_json",
- "sha2",
+ "sha2 0.10.2",
"sha3",
"unicode-normalization",
]
@@ -192,11 +315,21 @@ checksum = "7ebdb29d2ea9ed0083cd8cece49bbd968021bd99b0849edb4a9a7ee0fdf6a4e0"
[[package]]
name = "hmac"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a2a2320eb7ec0ebe8da8f744d7812d9fc4cb4d09344ac01898dbcb6a20ae69b"
+dependencies = [
+ "crypto-mac",
+ "digest 0.9.0",
+]
+
+[[package]]
+name = "hmac"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
- "digest",
+ "digest 0.10.3",
]
[[package]]
@@ -216,6 +349,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1aab8fc367588b89dcee83ab0fd66b72b50b72fa1904d7095045ace2b0c81c35"
[[package]]
+name = "k256"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "19c3a5e0a0b8450278feda242592512e09f61c72e018b8cd5c859482802daf2d"
+dependencies = [
+ "cfg-if",
+ "ecdsa",
+ "elliptic-curve",
+ "sec1",
+ "sha2 0.9.9",
+]
+
+[[package]]
name = "keccak"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -240,6 +386,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d"
[[package]]
+name = "opaque-debug"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5"
+
+[[package]]
name = "os_str_bytes"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -251,7 +403,18 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83a0692ec44e4cf1ef28ca317f14f8f07da2d95ec3fa01f86e4467b725e60917"
dependencies = [
- "digest",
+ "digest 0.10.3",
+]
+
+[[package]]
+name = "pkcs8"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7cabda3fb821068a9a4fab19a683eac3af12edf0f34b94a8be53c4972b8149d0"
+dependencies = [
+ "der",
+ "spki",
+ "zeroize",
]
[[package]]
@@ -297,27 +460,42 @@ dependencies = [
]
[[package]]
-name = "ryu"
-version = "1.0.9"
+name = "rand_core"
+version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f"
+checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7"
+dependencies = [
+ "getrandom",
+]
[[package]]
-name = "secp256k1"
-version = "0.22.1"
+name = "rfc6979"
+version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "26947345339603ae8395f68e2f3d85a6b0a8ddfe6315818e80b8504415099db0"
+checksum = "96ef608575f6392792f9ecf7890c00086591d29a83910939d430753f7c050525"
dependencies = [
- "secp256k1-sys",
+ "crypto-bigint",
+ "hmac 0.11.0",
+ "zeroize",
]
[[package]]
-name = "secp256k1-sys"
-version = "0.5.0"
+name = "ryu"
+version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "07b5b9d7322572e1f3aeed208668ce87789b3645dbb73082c5ce99a004103a35"
+checksum = "73b4b750c782965c211b42f022f59af1fbceabdd026623714f104152f1ec149f"
+
+[[package]]
+name = "sec1"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08da66b8b0965a5555b6bd6639e68ccba85e1e2506f5fbb089e93f8a04e1a2d1"
dependencies = [
- "cc",
+ "der",
+ "generic-array",
+ "pkcs8",
+ "subtle",
+ "zeroize",
]
[[package]]
@@ -353,13 +531,26 @@ dependencies = [
[[package]]
name = "sha2"
+version = "0.9.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4d58a1e1bf39749807d89cf2d98ac2dfa0ff1cb3faa38fbb64dd88ac8013d800"
+dependencies = [
+ "block-buffer 0.9.0",
+ "cfg-if",
+ "cpufeatures",
+ "digest 0.9.0",
+ "opaque-debug",
+]
+
+[[package]]
+name = "sha2"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55deaec60f81eefe3cce0dc50bda92d6d8e88f2a27df7c5033b42afeb1ed2676"
dependencies = [
"cfg-if",
"cpufeatures",
- "digest",
+ "digest 0.10.3",
]
[[package]]
@@ -368,11 +559,31 @@ version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "881bf8156c87b6301fc5ca6b27f11eeb2761224c7081e69b409d5a1951a70c86"
dependencies = [
- "digest",
+ "digest 0.10.3",
"keccak",
]
[[package]]
+name = "signature"
+version = "1.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "02658e48d89f2bec991f9a78e69cfa4c316f8d6a6c4ec12fae1aeb263d486788"
+dependencies = [
+ "digest 0.9.0",
+ "rand_core",
+]
+
+[[package]]
+name = "spki"
+version = "0.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "44d01ac02a6ccf3e07db148d2be087da624fea0221a16152ed01f0496a6b0a27"
+dependencies = [
+ "base64ct",
+ "der",
+]
+
+[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -453,6 +664,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
[[package]]
+name = "wasi"
+version = "0.10.2+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6"
+
+[[package]]
name = "winapi"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -482,3 +699,9 @@ name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
+[[package]]
+name = "zeroize"
+version = "1.5.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94693807d016b2f2d2e14420eb3bfcca689311ff775dcf113d74ea624b7cdf07"
diff --git a/Cargo.toml b/Cargo.toml
index e2eb52e..45dbbf5 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "hdwallet"
-version = "0.1.1"
+version = "0.2.0"
authors = ["Nicholas Rodrigues Lordello <[email protected]>"]
edition = "2021"
description = "Ethereum hierarchical deterministic wallet implementation"
@@ -15,8 +15,8 @@ clap = { version = "3", features = ["derive", "env"] }
ethnum = "1"
hex = "0.4"
hmac = { version = "0.12", features = ["std"] }
+k256 = "0.10"
pbkdf2 = { version = "0.11", default-features = false }
-secp256k1 = { version = "0.22", features = ["recovery"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
diff --git a/src/account.rs b/src/account.rs
index 375afd4..7cf21bb 100644
--- a/src/account.rs
+++ b/src/account.rs
@@ -1,20 +1,19 @@
//! Module implementing `secp256k1` private key.
mod address;
+mod prehashed;
+mod public;
mod signature;
-pub use self::{
- address::Address,
- signature::{Signature, YParity},
-};
+use self::prehashed::Prehashed;
+pub use self::{address::Address, public::PublicKey, signature::Signature};
use crate::hash;
use anyhow::Result;
-pub use secp256k1::PublicKey;
-use secp256k1::{Message, Secp256k1, SecretKey, ONE_KEY};
-use std::{
- convert::TryInto,
- fmt::{self, Debug, Formatter},
+use k256::{
+ ecdsa::{signature::DigestSigner as _, SigningKey},
+ SecretKey,
};
+use std::fmt::{self, Debug, Formatter};
/// A struct representing an Ethereum private key.
pub struct PrivateKey(SecretKey);
@@ -22,54 +21,39 @@ pub struct PrivateKey(SecretKey);
impl PrivateKey {
/// Creates a private key from a secret.
pub fn new(secret: impl AsRef<[u8]>) -> Result<Self> {
- let key = SecretKey::from_slice(secret.as_ref())?;
+ let key = SecretKey::from_be_bytes(secret.as_ref())?;
Ok(PrivateKey(key))
}
/// Returns the public key for the private key.
pub fn public(&self) -> PublicKey {
- let secp = Secp256k1::signing_only();
- PublicKey::from_secret_key(&secp, &self.0)
+ PublicKey(self.0.public_key())
}
/// Returns the public address for the private key.
pub fn address(&self) -> Address {
- let public_key = self.public().serialize_uncompressed();
+ let encoded = self.public().encode_uncompressed();
// NOTE: An ethereum address is the last 20 bytes of the keccak hash of
- // the public key. Note that `libsecp256k1` public key is serialized
- // into 65 bytes as the first byte is always 0x04 as a tag to mark a
- // uncompressed public key. Discard it for the public address
- // calculation.
- debug_assert_eq!(public_key[0], 0x04);
- let hash = hash::keccak256(&public_key[1..]);
+ // the concatenated elliptic curve coordinates of the public key. Note
+ // that an encoded uncompressed public key is serialized into 65 bytes
+ // where the first byte is a SEC1 tag that is always 0x04 (representing
+ // an uncompressed point) and the subsequent bytes are the coordinates
+ // we want. So discard the first byte for the address calculation.
+ debug_assert_eq!(encoded[0], 0x04);
+ let hash = hash::keccak256(&encoded[1..]);
+
Address::from_slice(&hash[12..])
}
/// Returns the private key's 32 byte secret.
pub fn secret(&self) -> [u8; 32] {
- *self.0.as_ref()
+ self.0.to_be_bytes().into()
}
/// Generate a signature for the specified message.
pub fn sign(&self, message: [u8; 32]) -> Signature {
- let message = Message::from_slice(&message).expect("invalid message");
-
- let (recovery_id, raw_signature) = Secp256k1::signing_only()
- .sign_ecdsa_recoverable(&message, &self.0)
- .serialize_compact();
- debug_assert!(matches!(recovery_id.to_i32(), 0 | 1));
- debug_assert_eq!(raw_signature.len(), 64);
-
- Signature {
- y_parity: match recovery_id.to_i32() {
- 0 => YParity::Even,
- 1 => YParity::Odd,
- n => unreachable!("non 0 or 1 signature y-parity bit {}", n),
- },
- r: raw_signature[..32].try_into().unwrap(),
- s: raw_signature[32..].try_into().unwrap(),
- }
+ Signature(SigningKey::from(&self.0).sign_digest(Prehashed::Message(message)))
}
}
@@ -79,12 +63,6 @@ impl Debug for PrivateKey {
}
}
-impl Drop for PrivateKey {
- fn drop(&mut self) {
- self.0 = ONE_KEY;
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -106,11 +84,11 @@ mod tests {
let message = hash::keccak256(b"\x19Ethereum Signed Message:\n12Hello World!");
assert_eq!(
key.sign(message),
- Signature {
- y_parity: YParity::Odd,
- r: hex!("408790f153cbfa2722fc708a57d97a43b24429724cf060df7c915d468c43bd84"),
- s: hex!("61c96aac95ce37d7a31087b6634f4a3ea439a9f704b5c818584fa2a32fa83859"),
- },
+ Signature::from_parts(
+ 1,
+ hex!("408790f153cbfa2722fc708a57d97a43b24429724cf060df7c915d468c43bd84"),
+ hex!("61c96aac95ce37d7a31087b6634f4a3ea439a9f704b5c818584fa2a32fa83859"),
+ ),
);
}
}
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\
diff --git a/src/cmd/public_key.rs b/src/cmd/public_key.rs
index 360255b..1f724ba 100644
--- a/src/cmd/public_key.rs
+++ b/src/cmd/public_key.rs
@@ -19,7 +19,7 @@ pub fn run(options: Options) -> Result<()> {
.account
.private_key()?
.public()
- .serialize_uncompressed()
+ .encode_uncompressed()
)
);
Ok(())
diff --git a/src/hdk.rs b/src/hdk.rs
index 830b7c3..daf4a9d 100644
--- a/src/hdk.rs
+++ b/src/hdk.rs
@@ -6,7 +6,7 @@ pub use self::path::{Component, Path};
use crate::account::PrivateKey;
use anyhow::{Context as _, Result};
use hmac::{Hmac, Mac as _};
-use secp256k1::{PublicKey, Secp256k1, SecretKey, Signing};
+use k256::{elliptic_curve::sec1::ToEncodedPoint as _, SecretKey};
use sha2::Sha512;
/// A value indicating a path component is hardened.
@@ -30,34 +30,31 @@ fn derive_slice(seed: &[u8], path: &Path) -> Result<PrivateKey> {
hmac.finalize().into_bytes()
};
- let secp = Secp256k1::signing_only();
for (i, component) in path.components().enumerate() {
let (secret, chain_code) = extended_key.split_at(32);
+ let secret = SecretKey::from_be_bytes(secret)?;
let mut hmac: Hmac<Sha512> = Hmac::<Sha512>::new_from_slice(chain_code)?;
let value = match component {
Component::Hardened(value) => {
hmac.update(&[0]);
- hmac.update(secret);
+ hmac.update(&secret.to_be_bytes());
value | HARDENED
}
Component::Normal(value) => {
- hmac.update(&public_key(&secp, secret)?);
+ hmac.update(secret.public_key().to_encoded_point(true).as_bytes());
value
}
};
hmac.update(&value.to_be_bytes());
let mut child_key = hmac.finalize().into_bytes();
- let child_secret = SecretKey::from_slice(&child_key[..32])
- .and_then(|mut key| {
- key.add_assign(secret)?;
- Ok(key)
- })
- .with_context(|| {
- format!("path '{}' component #{} yields invalid child key", path, i)
- })?;
- child_key[..32].copy_from_slice(child_secret.as_ref());
+
+ let child_secret = SecretKey::from_be_bytes(&child_key[..32]).with_context(|| {
+ format!("path '{}' component #{} yields invalid child key", path, i)
+ })?;
+ let next_secret = SecretKey::new(*child_secret.as_scalar_core() + *secret.as_scalar_core());
+ child_key[..32].copy_from_slice(&next_secret.to_be_bytes());
extended_key = child_key
}
@@ -65,15 +62,6 @@ fn derive_slice(seed: &[u8], path: &Path) -> Result<PrivateKey> {
PrivateKey::new(&extended_key[..32])
}
-fn public_key<C>(secp: &Secp256k1<C>, secret: &[u8]) -> Result<[u8; 33]>
-where
- C: Signing,
-{
- let secret_key = SecretKey::from_slice(secret)?;
- let public_key = PublicKey::from_secret_key(secp, &secret_key);
- Ok(public_key.serialize())
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src/transaction/eip1559.rs b/src/transaction/eip1559.rs
index c6acf8b..765ce97 100644
--- a/src/transaction/eip1559.rs
+++ b/src/transaction/eip1559.rs
@@ -6,7 +6,7 @@ use crate::{
transaction::accesslist::AccessList,
transaction::rlp,
};
-use ethnum::{AsU256 as _, U256};
+use ethnum::U256;
use serde::Deserialize;
/// An EIP-1559 Ethereum transaction.
@@ -19,10 +19,11 @@ pub struct Eip1559Transaction {
/// The nonce for the transaction.
#[serde(with = "serialization::u256")]
pub nonce: U256,
- /// The gas price in Wei for the transaction.
+ /// The maximum priority fee in Wei for the transaction.
#[serde(rename = "maxPriorityFeePerGas")]
#[serde(with = "serialization::u256")]
pub max_priority_fee_per_gas: U256,
+ /// The maximum gas price in Wei for the transaction.
#[serde(rename = "maxFeePerGas")]
#[serde(with = "serialization::u256")]
pub max_fee_per_gas: U256,
@@ -62,9 +63,9 @@ impl Eip1559Transaction {
let tail = signature.map(|signature| {
[
- rlp::uint(signature.y_parity.as_u256()),
- rlp::uint(U256::from_be_bytes(signature.r)),
- rlp::uint(U256::from_be_bytes(signature.s)),
+ rlp::uint(signature.y_parity()),
+ rlp::uint(signature.r()),
+ rlp::uint(signature.s()),
]
});
@@ -80,6 +81,7 @@ impl Eip1559Transaction {
mod tests {
use super::*;
use crate::transaction::accesslist::StorageSlot;
+ use ethnum::AsU256 as _;
use hex_literal::hex;
use serde_json::json;
diff --git a/src/transaction/eip2930.rs b/src/transaction/eip2930.rs
index 9de2d2c..4a8bcf8 100644
--- a/src/transaction/eip2930.rs
+++ b/src/transaction/eip2930.rs
@@ -6,7 +6,7 @@ use crate::{
transaction::accesslist::AccessList,
transaction::rlp,
};
-use ethnum::{AsU256 as _, U256};
+use ethnum::U256;
use serde::Deserialize;
/// An EIP-2930 Ethereum transaction.
@@ -57,9 +57,9 @@ impl Eip2930Transaction {
let tail = signature.map(|signature| {
[
- rlp::uint(signature.y_parity.as_u256()),
- rlp::uint(U256::from_be_bytes(signature.r)),
- rlp::uint(U256::from_be_bytes(signature.s)),
+ rlp::uint(signature.y_parity()),
+ rlp::uint(signature.r()),
+ rlp::uint(signature.s()),
]
});
@@ -75,6 +75,7 @@ impl Eip2930Transaction {
mod tests {
use super::*;
use crate::transaction::accesslist::StorageSlot;
+ use ethnum::AsU256 as _;
use hex_literal::hex;
use serde_json::json;
diff --git a/src/transaction/legacy.rs b/src/transaction/legacy.rs
index 6680c74..9e0f9bc 100644
--- a/src/transaction/legacy.rs
+++ b/src/transaction/legacy.rs
@@ -5,7 +5,7 @@ use crate::{
serialization,
transaction::rlp,
};
-use ethnum::{AsU256 as _, U256};
+use ethnum::U256;
use serde::Deserialize;
/// A Legacy Ethereum transaction.
@@ -48,15 +48,7 @@ impl LegacyTransaction {
];
let tail = signature
- .map(|signature| {
- (
- self.chain_id.map_or(signature.v().as_u256(), |chain_id| {
- signature.v_replay_protected(chain_id)
- }),
- U256::from_be_bytes(signature.r),
- U256::from_be_bytes(signature.s),
- )
- })
+ .map(|signature| (signature.v(self.chain_id), signature.r(), signature.s()))
.or_else(|| Some((self.chain_id?, U256::ZERO, U256::ZERO)))
.map(|(v, r, s)| [rlp::uint(v), rlp::uint(r), rlp::uint(s)]);
@@ -67,6 +59,7 @@ impl LegacyTransaction {
#[cfg(test)]
mod tests {
use super::*;
+ use ethnum::AsU256 as _;
use hex_literal::hex;
use serde_json::json;