Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
66 changes: 48 additions & 18 deletions bip0032/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ repository.workspace = true
description = "Another Rust implementation of BIP-0032 standard"
readme = "README.md"
documentation = "https://docs.rs/bip0032"
keywords = ["bip32", "bitcoin", "crypto"]
keywords = ["bip32", "slip10", "bitcoin", "crypto"]
categories = ["cryptography", "no-std"]

[package.metadata.docs.rs]
Expand All @@ -41,11 +41,20 @@ std = [
"k256?/std",
"secp256k1?/std",
"libsecp256k1?/std",
"p256?/std",
"ed25519-dalek?/std",
]

# BIP-0032 (secp256k1)
k256 = ["k256/arithmetic"]
secp256k1 = ["dep:secp256k1"]
libsecp256k1 = ["dep:libsecp256k1"]

# Optional SLIP-0010 extension (support secp256k1/nist256p1/ed25519 curve)
slip10 = []
p256 = ["slip10", "p256/arithmetic"]
ed25519-dalek = ["slip10", "dep:ed25519-dalek"]

[dependencies]
anyhow = { version = "1.0", default-features = false }
bs58 = { version = "0.5", default-features = false, features = ["alloc", "check"] }
Expand All @@ -54,27 +63,48 @@ ripemd = { version = "0.1", default-features = false }
sha2 = { version = "0.10", default-features = false }
zeroize = { version = "1.8", default-features = false }

# Different secp256k1 libraries
###############################################################################
# secp256k1 libraries
###############################################################################
# https://github.com/RustCrypto/elliptic-curves/tree/master/k256
[dependencies.k256]
default-features = false
optional = true
version = "0.13"

k256 = { version = "0.13", default-features = false, features = ["alloc"], optional = true }
# https://github.com/bitcoin-core/secp256k1
[dependencies.secp256k1]
default-features = false
features = ["alloc"]
optional = true
version = "0.31"

secp256k1 = { version = "0.31", default-features = false, features = ["alloc"], optional = true }
# https://github.com/paritytech/libsecp256k1
# NOTE: libsecp256k1 crate is no longer maintained
[dependencies.libsecp256k1]
default-features = false
features = ["static-context"]
optional = true
version = "0.7"
libsecp256k1 = { version = "0.7", default-features = false, features = ["static-context"], optional = true }

###############################################################################
# nist256p1 libraries (SLIP-0010 extension)
###############################################################################
# https://github.com/RustCrypto/elliptic-curves/tree/master/p256
p256 = { version = "0.13", default-features = false, features = ["alloc"], optional = true }

###############################################################################
# ed25519 libraries (SLIP-0010 extension)
###############################################################################
# https://github.com/dalek-cryptography/curve25519-dalek/tree/main/ed25519-dalek
ed25519-dalek = { version = "2.2.0", default-features = false, features = ["alloc"], optional = true }

[dev-dependencies]
const-hex = "1.12.0"

[[test]]
name = "bip32"
path = "tests/bip32.rs"
required-features = ["k256"]

[[test]]
name = "slip10-secp256k1"
path = "tests/slip10/secp256k1.rs"
required-features = ["slip10", "k256"]

[[test]]
name = "slip10-nist256p1"
path = "tests/slip10/nist256p1.rs"
required-features = ["slip10", "p256"]

[[test]]
name = "slip10-ed25519"
path = "tests/slip10/ed25519.rs"
required-features = ["slip10", "ed25519-dalek"]
19 changes: 17 additions & 2 deletions bip0032/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,16 @@

Another Rust implementation of [BIP-0032](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki) standard.

## Support curves and features

| Curve | Feature | Backends | Hardened | Non-hardened (private) | Non-hardened (public) | Serialization |
| --------- | --------------------------------------- | ----------------------------- | -------- | ---------------------- | --------------------- | ------------- |
| secp256k1 | `k256` \| `secp256k1` \| `libsecp256k1` | k256, secp256k1, libsecp256k1 | yes | yes | yes | yes |

## Usage

Seed material is typically derived from a BIP-0039 mnemonic (for example, via
[bip0039](https://crates.io/crates/bip0039)).
Seed material is typically derived from a [BIP-0039](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) mnemonic
(for example, via [bip0039](https://crates.io/crates/bip0039)).

```rust
use bip0039::{Count, English, Mnemonic};
Expand Down Expand Up @@ -74,6 +80,11 @@ let xpub = child

4. Public parent key -> private child key: impossible (BIP-0032 does not allow it).

## SLIP-0010 (optional)

[SLIP-0010](https://github.com/satoshilabs/slips/blob/master/slip-0010.md) support is available behind the `slip10` feature.
See [SLIP-0010.md](SLIP-0010.md) for details, examples, and the feature matrix.

## Documentation

See documentation and examples at https://docs.rs/bip0032.
Expand All @@ -86,6 +97,10 @@ See documentation and examples at https://docs.rs/bip0032.
- [`k256`](https://github.com/RustCrypto/elliptic-curves/tree/master/k256) (by default)
- [`secp256k1`](https://github.com/rust-bitcoin/rust-secp256k1)
- [`libsecp256k1`](https://github.com/paritytech/libsecp256k1)
- [x] Optional SLIP-0010 support
- secp256k1 ([compatible with BIP32](https://github.com/satoshilabs/slips/blob/master/slip-0010.md#compatibility-with-bip-0032))
- NIST P-256 (a.k.a. secp256r1, prime256v1) ([`p256`](https://github.com/RustCrypto/elliptic-curves/tree/master/p256))
- ed25519 ([`ed25519-dalek`](https://github.com/dalek-cryptography/curve25519-dalek/tree/main/ed25519-dalek))
- [x] Support `no_std` environment

## Performance
Expand Down
75 changes: 75 additions & 0 deletions bip0032/SLIP-0010.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# SLIP-0010

This crate provides optional [SLIP-0010](https://github.com/satoshilabs/slips/blob/master/slip-0010.md) support behind the `slip10` feature.
It shares the same [`ExtendedPrivateKey`]/[`ExtendedPublicKey`] structure as [BIP-0032](https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki),
but the derivation rules and supported curves differ.

## Supported curves and features

| Curve | Feature | Backends | Hardened | Non-hardened (private) | Non-hardened (public) | Serialization |
| --------- | ---------------------------------------------------- | ----------------------------- | -------- | ---------------------- | --------------------- | ------------- |
| secp256k1 | `slip10` + (`k256` \| `secp256k1` \| `libsecp256k1`) | k256, secp256k1, libsecp256k1 | yes | yes | yes | no |
| nist256p1 | `slip10` + `p256` | p256 | yes | yes | yes | no |
| ed25519 | `slip10` + `ed25519-dalek` | ed25519-dalek | yes | no | no | no |

Note: SLIP-0010 does not define a standardized extended key serialization.
Only the BIP32 secp256k1 encoding (xpub/xprv) is supported for serialization.

## Usage

Seed material is typically derived from a [BIP-0039](https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki) mnemonic
(for example, via [bip0039](https://crates.io/crates/bip0039)).

```rust
use bip0039::{Count, English, Mnemonic};

let mnemonic = <Mnemonic<English>>::generate(Count::Words12);
let seed = mnemonic.to_seed("");
```

The examples below assume the `seed` from above.

### secp256k1 (non-hardened supported)

```rust
use bip0032::{DerivationPath, ExtendedPrivateKey, curve::secp256k1::*};
use bip0032::slip10::{Slip10MasterKey, Slip10NonHardenedDerivation};

# let seed = [0u8; 64];
let master = ExtendedPrivateKey::<Secp256k1Curve<K256Backend>>::new_slip10(&seed).unwrap();
let path: DerivationPath = "m/0H/1".parse().unwrap();
let child = Slip10NonHardenedDerivation::derive_slip10_path(&master, &path).unwrap();
let public = child.public_key().to_bytes();
```

### nist256p1 (non-hardened supported)

```rust
use bip0032::{DerivationPath, ExtendedPrivateKey, curve::nist256p1::*};
use bip0032::slip10::{Slip10MasterKey, Slip10NonHardenedDerivation};

# let seed = [0u8; 64];
let master = ExtendedPrivateKey::<Nist256p1Curve<P256Backend>>::new_slip10(&seed).unwrap();
let path: DerivationPath = "m/0H/1".parse().unwrap();
let child = Slip10NonHardenedDerivation::derive_slip10_path(&master, &path).unwrap();
let public = child.public_key().to_bytes();
```

### ed25519 (hardened only)

```rust
use bip0032::{ExtendedPrivateKey, HardenedDerivationPath, curve::ed25519::*};
use bip0032::slip10::{Slip10HardenedOnlyDerivation, Slip10MasterKey};

# let seed = [0u8; 64];
let master = ExtendedPrivateKey::<Ed25519Curve<Ed25519DalekBackend>>::new_slip10(&seed).unwrap();
let path: HardenedDerivationPath = "m/0H/1H".parse().unwrap();
let child = Slip10HardenedOnlyDerivation::derive_slip10_path(&master, &path).unwrap();
let public = child.public_key().to_bytes();
```

## Notes

- `Slip10NonHardenedDerivation` is implemented for both extended private and
extended public keys; hardened derivation is only available for private keys.
- Fingerprints are computed using Hash160 over the serialized public key bytes.
51 changes: 51 additions & 0 deletions bip0032/src/curve/ed25519/backends/ed25519_dalek.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use ed25519_dalek::{SigningKey, VerifyingKey};

use crate::curve::{CurveError, CurvePrivateKey, CurvePublicKey, ed25519::Ed25519Backend};

/// Ed25519 backend powered by the [`ed25519-dalek`](https://github.com/dalek-cryptography/curve25519-dalek/tree/main/ed25519-dalek) crate.
pub struct Ed25519DalekBackend;

impl CurvePublicKey for VerifyingKey {
type Error = CurveError;
type Bytes = [u8; 33];

fn from_bytes(bytes: &Self::Bytes) -> Result<Self, Self::Error> {
if bytes[0] != 0 {
return Err(CurveError::from("invalid ed25519 public key prefix"));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Use 32-byte Ed25519 public keys for SLIP-0010

SLIP-0010 defines Ed25519 public keys as 32 raw bytes; introducing a 33-byte encoding with a 0x00 prefix changes the public key serialization and therefore the parent fingerprint (hash160 over the serialized key) used throughout SLIP-0010 metadata. This will make derived fingerprints and public key bytes incompatible with standard SLIP-0010 vectors/implementations when users compare or interoperate across libraries.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

From https://github.com/satoshilabs/slips/blob/master/slip-0010.md#test-vector-1-for-ed25519, it is known that the calculation of the parent key fingerprint uses a 0x00 prefix plus a 32-byte ed25519 public key as input.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

add ed25519_pubkey_from_slip10_bytes/ed25519_pubkey_to_slip10_bytes and update docs about it

}

let mut raw = [0u8; 32];
raw.copy_from_slice(&bytes[1..]);
VerifyingKey::from_bytes(&raw).map_err(CurveError::new)
}

fn to_bytes(&self) -> Self::Bytes {
let raw = self.to_bytes();
let mut out = [0u8; 33];
out[1..].copy_from_slice(&raw);
out
}
}

impl CurvePrivateKey for SigningKey {
type Error = CurveError;
type PublicKey = VerifyingKey;
type Bytes = [u8; 32];

fn from_bytes(bytes: &Self::Bytes) -> Result<Self, Self::Error> {
Ok(SigningKey::from_bytes(bytes))
}

fn to_bytes(&self) -> Self::Bytes {
self.to_bytes()
}

fn to_public(&self) -> Self::PublicKey {
self.verifying_key()
}
}

impl Ed25519Backend for Ed25519DalekBackend {
type PublicKey = VerifyingKey;
type PrivateKey = SigningKey;
}
17 changes: 17 additions & 0 deletions bip0032/src/curve/ed25519/backends/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
//! Backend implementations for Ed25519.

use crate::curve::{CurvePrivateKey, CurvePublicKey};

/// Ed25519 backend interface.
pub trait Ed25519Backend {
/// Backend-specific public key type.
type PublicKey: CurvePublicKey<Bytes = [u8; 33]>;
/// Backend-specific private key type.
type PrivateKey: CurvePrivateKey<Bytes = [u8; 32], PublicKey = Self::PublicKey>;
}

#[cfg(feature = "ed25519-dalek")]
mod ed25519_dalek;

#[cfg(feature = "ed25519-dalek")]
pub use self::ed25519_dalek::Ed25519DalekBackend;
22 changes: 22 additions & 0 deletions bip0032/src/curve/ed25519/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
//! Ed25519 curve implementation.

use core::marker::PhantomData;

use super::*;

mod backends;
pub use self::backends::*;

/// An Ed25519 curve parameterization for a specific backend.
pub struct Ed25519Curve<B>(PhantomData<B>);

impl<B: Ed25519Backend> Curve for Ed25519Curve<B> {
const HMAC_KEY: &'static [u8] = b"ed25519 seed";

type PublicKey = <B as Ed25519Backend>::PublicKey;
type PrivateKey = <B as Ed25519Backend>::PrivateKey;
}

impl<B: Ed25519Backend> Slip10Curve for Ed25519Curve<B> {}

impl<B: Ed25519Backend> Slip10HardenedOnlyCurve for Ed25519Curve<B> {}
67 changes: 67 additions & 0 deletions bip0032/src/curve/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
//! Curve-related error helpers.

#[cfg(not(feature = "std"))]
use alloc::string::String;
use core::{error, fmt};

use crate::error::{ErrorSource, IntoErrorSource};

/// Common curve error type.
pub struct CurveError(ErrorSource);

impl CurveError {
/// Creates a curve error from a source error.
#[cfg(feature = "std")]
pub fn new<E>(error: E) -> Self
where
E: IntoErrorSource,
{
Self(error.into_error_source())
}

/// Creates a curve error from a source error.
#[cfg(not(feature = "std"))]
pub fn new<E>(error: E) -> Self
where
E: fmt::Display + fmt::Debug + Send + Sync + 'static,
{
let error = anyhow::Error::msg(error);
Self(error.into_error_source())
}
}

impl fmt::Debug for CurveError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}

impl fmt::Display for CurveError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}

impl From<ErrorSource> for CurveError {
fn from(error: ErrorSource) -> Self {
Self(error)
}
}

impl From<String> for CurveError {
fn from(message: String) -> Self {
Self(ErrorSource::from(message))
}
}

impl From<&'static str> for CurveError {
fn from(message: &'static str) -> Self {
Self(ErrorSource::from(message))
}
}

impl error::Error for CurveError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
Some(self.0.as_error())
}
}
16 changes: 14 additions & 2 deletions bip0032/src/curve/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,19 @@ pub trait TweakableKey: Sized {
fn add_tweak(&self, tweak: &[u8; 32]) -> Result<Self, Self::Error>;
}

pub mod secp256k1;

/// Marker trait for BIP32-encodable curves.
pub trait Bip32Curve: Curve {}

mod error;
#[cfg(feature = "slip10")]
mod slip10;

pub use self::error::CurveError;
#[cfg(feature = "slip10")]
pub use self::slip10::*;

#[cfg(feature = "slip10")]
pub mod ed25519;
#[cfg(feature = "slip10")]
pub mod nist256p1;
pub mod secp256k1;
Loading
Loading