Compare commits
2 Commits
4354be4304
...
1209549532
Author | SHA1 | Date |
---|---|---|
Ryan Heywood | 1209549532 | |
Ryan Heywood | 053902bf43 |
|
@ -244,7 +244,7 @@ dependencies = [
|
|||
"futures-lite 2.2.0",
|
||||
"parking",
|
||||
"polling 3.3.2",
|
||||
"rustix 0.38.30",
|
||||
"rustix 0.38.31",
|
||||
"slab",
|
||||
"tracing",
|
||||
"windows-sys 0.52.0",
|
||||
|
@ -1610,7 +1610,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||
checksum = "0bad00257d07be169d870ab665980b06cdb366d792ad690bf2e76876dc503455"
|
||||
dependencies = [
|
||||
"hermit-abi",
|
||||
"rustix 0.38.30",
|
||||
"rustix 0.38.31",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
|
@ -1870,6 +1870,7 @@ dependencies = [
|
|||
"keyfork-slip10-test-data",
|
||||
"keyforkd-models",
|
||||
"serde",
|
||||
"tempfile",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tower",
|
||||
|
@ -2533,7 +2534,7 @@ dependencies = [
|
|||
"cfg-if",
|
||||
"concurrent-queue",
|
||||
"pin-project-lite",
|
||||
"rustix 0.38.30",
|
||||
"rustix 0.38.31",
|
||||
"tracing",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
@ -2806,9 +2807,9 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "rustix"
|
||||
version = "0.38.30"
|
||||
version = "0.38.31"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "322394588aaf33c24007e8bb3238ee3e4c5c09c084ab32bc73890b99ff326bca"
|
||||
checksum = "6ea3e1a662af26cd7a3ba09c0297a31af215563ecf42817c98df621387f4e949"
|
||||
dependencies = [
|
||||
"bitflags 2.4.2",
|
||||
"errno",
|
||||
|
@ -3184,14 +3185,13 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "tempfile"
|
||||
version = "3.9.0"
|
||||
version = "3.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "01ce4141aa927a6d1bd34a041795abd0db1cccba5d5f24b009f694bdf3a1f3fa"
|
||||
checksum = "a365e8cd18e44762ef95d87f284f4b5cd04107fec2ff3052bd6a3e6069669e67"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"fastrand 2.0.1",
|
||||
"redox_syscall",
|
||||
"rustix 0.38.30",
|
||||
"rustix 0.38.31",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
|
@ -3212,7 +3212,7 @@ version = "0.3.0"
|
|||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "21bebf2b7c9e0a515f6e0f8c51dc0f8e4696391e6f1ff30379559f8365fb0df7"
|
||||
dependencies = [
|
||||
"rustix 0.38.30",
|
||||
"rustix 0.38.31",
|
||||
"windows-sys 0.48.0",
|
||||
]
|
||||
|
||||
|
@ -3606,7 +3606,7 @@ dependencies = [
|
|||
"either",
|
||||
"home",
|
||||
"once_cell",
|
||||
"rustix 0.38.30",
|
||||
"rustix 0.38.31",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
|
|
@ -1,100 +1,65 @@
|
|||
use crate::Client;
|
||||
use keyforkd::test_util::{run_test, Infallible};
|
||||
use keyfork_derive_util::{request::*, DerivationPath};
|
||||
use keyfork_slip10_test_data::test_data;
|
||||
use std::sync::mpsc::channel;
|
||||
use std::{os::unix::net::UnixStream, str::FromStr};
|
||||
use tokio::runtime::Builder;
|
||||
|
||||
#[test]
|
||||
fn secp256k1() {
|
||||
fn secp256k1_test_suite() {
|
||||
let tests = test_data()
|
||||
.unwrap()
|
||||
.remove(&"secp256k1".to_string())
|
||||
.unwrap();
|
||||
|
||||
// note: since client is non async, can't be single threaded
|
||||
let rt = Builder::new_multi_thread().enable_io().build().unwrap();
|
||||
let tempdir = tempfile::tempdir().unwrap();
|
||||
for (i, per_seed) in tests.into_iter().enumerate() {
|
||||
let mut socket_name = i.to_string();
|
||||
socket_name.push_str("-keyforkd.sock");
|
||||
let socket_path = tempdir.path().join(socket_name);
|
||||
let (tx, rx) = channel();
|
||||
let handle = rt.spawn({
|
||||
let socket_path = socket_path.clone();
|
||||
async move {
|
||||
let seed = per_seed.seed.clone();
|
||||
let mut server = keyforkd::UnixServer::bind(&socket_path).unwrap();
|
||||
tx.send(()).unwrap();
|
||||
let service = keyforkd::ServiceBuilder::new()
|
||||
.layer(keyforkd::middleware::BincodeLayer::new())
|
||||
.service(keyforkd::Keyforkd::new(seed));
|
||||
server.run(service).await.unwrap();
|
||||
for seed_test in tests {
|
||||
let seed = seed_test.seed;
|
||||
run_test(&seed, move |socket_path| {
|
||||
for test in seed_test.tests {
|
||||
let socket = UnixStream::connect(&socket_path).unwrap();
|
||||
let mut client = Client::new(socket);
|
||||
let chain = DerivationPath::from_str(test.chain).unwrap();
|
||||
if chain.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let req = DerivationRequest::new(
|
||||
DerivationAlgorithm::Secp256k1,
|
||||
&DerivationPath::from_str(test.chain).unwrap(),
|
||||
);
|
||||
let response =
|
||||
DerivationResponse::try_from(client.request(&req.into()).unwrap()).unwrap();
|
||||
assert_eq!(&response.data, test.private_key.as_slice());
|
||||
}
|
||||
});
|
||||
rx.recv().unwrap();
|
||||
|
||||
for test in &per_seed.tests {
|
||||
let socket = UnixStream::connect(&socket_path).unwrap();
|
||||
let mut client = Client::new(socket);
|
||||
let chain = DerivationPath::from_str(test.chain).unwrap();
|
||||
if chain.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let req = DerivationRequest::new(
|
||||
DerivationAlgorithm::Secp256k1,
|
||||
&DerivationPath::from_str(test.chain).unwrap(),
|
||||
);
|
||||
let response =
|
||||
DerivationResponse::try_from(client.request(&req.into()).unwrap()).unwrap();
|
||||
assert_eq!(response.data, test.private_key);
|
||||
}
|
||||
|
||||
handle.abort();
|
||||
Infallible::Ok(())
|
||||
}).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ed25519() {
|
||||
let tests = test_data().unwrap().remove(&"ed25519".to_string()).unwrap();
|
||||
fn ed25519_test_suite() {
|
||||
let tests = test_data()
|
||||
.unwrap()
|
||||
.remove(&"ed25519".to_string())
|
||||
.unwrap();
|
||||
|
||||
let rt = Builder::new_multi_thread().enable_io().build().unwrap();
|
||||
let tempdir = tempfile::tempdir().unwrap();
|
||||
for (i, per_seed) in tests.into_iter().enumerate() {
|
||||
let mut socket_name = i.to_string();
|
||||
socket_name.push_str("-keyforkd.sock");
|
||||
let socket_path = tempdir.path().join(socket_name);
|
||||
let (tx, rx) = channel();
|
||||
let handle = rt.spawn({
|
||||
let socket_path = socket_path.clone();
|
||||
async move {
|
||||
let seed = per_seed.seed.clone();
|
||||
let mut server = keyforkd::UnixServer::bind(&socket_path).unwrap();
|
||||
tx.send(()).unwrap();
|
||||
let service = keyforkd::ServiceBuilder::new()
|
||||
.layer(keyforkd::middleware::BincodeLayer::new())
|
||||
.service(keyforkd::Keyforkd::new(seed));
|
||||
server.run(service).await.unwrap();
|
||||
for seed_test in tests {
|
||||
let seed = seed_test.seed;
|
||||
run_test(&seed, move |socket_path| {
|
||||
for test in seed_test.tests {
|
||||
let socket = UnixStream::connect(&socket_path).unwrap();
|
||||
let mut client = Client::new(socket);
|
||||
let chain = DerivationPath::from_str(test.chain).unwrap();
|
||||
if chain.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let req = DerivationRequest::new(
|
||||
DerivationAlgorithm::Ed25519,
|
||||
&DerivationPath::from_str(test.chain).unwrap(),
|
||||
);
|
||||
let response =
|
||||
DerivationResponse::try_from(client.request(&req.into()).unwrap()).unwrap();
|
||||
assert_eq!(&response.data, test.private_key.as_slice());
|
||||
}
|
||||
});
|
||||
rx.recv().unwrap();
|
||||
|
||||
for test in &per_seed.tests {
|
||||
let socket = UnixStream::connect(&socket_path).unwrap();
|
||||
let mut client = Client::new(socket);
|
||||
let chain = DerivationPath::from_str(test.chain).unwrap();
|
||||
if chain.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
let req = DerivationRequest::new(
|
||||
DerivationAlgorithm::Ed25519,
|
||||
&DerivationPath::from_str(test.chain).unwrap(),
|
||||
);
|
||||
let response =
|
||||
DerivationResponse::try_from(client.request(&req.into()).unwrap()).unwrap();
|
||||
assert_eq!(response.data, test.private_key);
|
||||
}
|
||||
|
||||
handle.abort();
|
||||
Infallible::Ok(())
|
||||
}).unwrap();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -31,6 +31,7 @@ tower = { version = "0.4.13", features = ["tokio", "util"] }
|
|||
# Personally audited
|
||||
thiserror = "1.0.47"
|
||||
serde = { version = "1.0.186", features = ["derive"] }
|
||||
tempfile = { version = "3.10.0", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
hex-literal = "0.4.1"
|
||||
|
|
|
@ -30,6 +30,8 @@ pub use error::Keyforkd as KeyforkdError;
|
|||
pub use server::UnixServer;
|
||||
pub use service::Keyforkd;
|
||||
|
||||
pub mod test_util;
|
||||
|
||||
/// Set up a Tracing subscriber, defaulting to debug mode.
|
||||
#[cfg(feature = "tracing")]
|
||||
pub fn setup_registry() {
|
||||
|
|
|
@ -76,7 +76,7 @@ impl Service<Request> for Keyforkd {
|
|||
info!("Deriving path: {}", req.path());
|
||||
}
|
||||
|
||||
req.derive_with_master_seed((*seed).clone())
|
||||
req.derive_with_master_seed(seed.as_ref())
|
||||
.map(Response::Derivation)
|
||||
.map_err(|e| DerivationError::Derivation(e.to_string()).into())
|
||||
}),
|
||||
|
@ -120,7 +120,7 @@ mod tests {
|
|||
.unwrap()
|
||||
.try_into()
|
||||
.unwrap();
|
||||
assert_eq!(response.data, test.private_key);
|
||||
assert_eq!(&response.data, test.private_key.as_slice());
|
||||
assert_eq!(response.chain_code.as_slice(), test.chain_code);
|
||||
}
|
||||
}
|
||||
|
@ -150,7 +150,7 @@ mod tests {
|
|||
.unwrap()
|
||||
.try_into()
|
||||
.unwrap();
|
||||
assert_eq!(response.data, test.private_key);
|
||||
assert_eq!(&response.data, test.private_key.as_slice());
|
||||
assert_eq!(response.chain_code.as_slice(), test.chain_code);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,85 @@
|
|||
//! # Keyforkd Test Utilities
|
||||
//!
|
||||
//! This module adds a helper to set up a Tokio runtime, start a Tokio runtime with a given seed,
|
||||
//! start a Keyfork server on that runtime, and run a given test closure.
|
||||
|
||||
use crate::{middleware, Keyforkd, ServiceBuilder, UnixServer};
|
||||
|
||||
use tokio::runtime::Builder;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("This error can never be instantiated")]
|
||||
#[doc(hidden)]
|
||||
pub struct InfallibleError {
|
||||
protected: (),
|
||||
}
|
||||
|
||||
/// An infallible result. This type can be used to represent a function that should never error.
|
||||
///
|
||||
/// ```rust
|
||||
/// use keyforkd::test_util::Infallible;
|
||||
/// let closure = || {
|
||||
/// Infallible::Ok(())
|
||||
/// };
|
||||
/// assert!(closure().is_ok());
|
||||
/// ```
|
||||
pub type Infallible<T> = std::result::Result<T, InfallibleError>;
|
||||
|
||||
/// Run a test making use of a Keyforkd server. The path to the socket of the Keyforkd server is
|
||||
/// provided as the only argument to the closure. The closure is expected to return a Result; the
|
||||
/// Error field of the Result may be an error returned by a test.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// The function is not expected to run in production; therefore, the function plays "fast and
|
||||
/// loose" wih the usage of [`Result::expect`]. In normal usage, these should never be an issue.
|
||||
#[allow(clippy::missing_errors_doc)]
|
||||
pub fn run_test<F, E>(seed: &[u8], closure: F) -> Result<(), E>
|
||||
where
|
||||
F: FnOnce(&std::path::Path) -> Result<(), E> + Send + 'static,
|
||||
E: Send + 'static,
|
||||
{
|
||||
let rt = Builder::new_multi_thread()
|
||||
.worker_threads(2)
|
||||
.enable_io()
|
||||
.build()
|
||||
.expect("tokio threaded IO runtime");
|
||||
let socket_dir = tempfile::tempdir().expect("can't create tempdir");
|
||||
let socket_path = socket_dir.path().join("keyforkd.sock");
|
||||
rt.block_on(async move {
|
||||
let (tx, mut rx) = tokio::sync::mpsc::channel(1);
|
||||
let server_handle = tokio::spawn({
|
||||
let socket_path = socket_path.clone();
|
||||
let seed = seed.to_vec();
|
||||
async move {
|
||||
let mut server = UnixServer::bind(&socket_path).expect("can't bind unix socket");
|
||||
tx.send(()).await.expect("couldn't send server start signal");
|
||||
let service = ServiceBuilder::new()
|
||||
.layer(middleware::BincodeLayer::new())
|
||||
.service(Keyforkd::new(seed.to_vec()));
|
||||
server.run(service).await.unwrap();
|
||||
}
|
||||
});
|
||||
|
||||
rx.recv()
|
||||
.await
|
||||
.expect("can't receive server start signal from channel");
|
||||
let test_handle = tokio::task::spawn_blocking(move || closure(&socket_path));
|
||||
|
||||
let result = test_handle.await;
|
||||
server_handle.abort();
|
||||
result
|
||||
})
|
||||
.expect("runtime could not join all threads")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_run_test() {
|
||||
let seed = b"beefbeef";
|
||||
run_test(seed, |_path| Infallible::Ok(())).expect("infallible");
|
||||
}
|
||||
}
|
|
@ -40,7 +40,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
let key1 = request.derive_with_mnemonic(&mnemonic)?;
|
||||
|
||||
let seed = mnemonic.seed(None)?;
|
||||
let key2 = request.derive_with_master_seed(seed)?;
|
||||
let key2 = request.derive_with_master_seed(&seed)?;
|
||||
|
||||
assert_eq!(key1, key2);
|
||||
|
||||
|
|
|
@ -31,6 +31,68 @@ type Result<T, E = Error> = std::result::Result<T, E>;
|
|||
type ChainCode = [u8; 32];
|
||||
type HmacSha512 = Hmac<Sha512>;
|
||||
|
||||
/// A reference to a variable-length seed. Keyfork automatically supports a seed of 128 bits,
|
||||
/// 256 bits, or 512 bits, but because the master key is derived from a hashed seed, in theory
|
||||
/// any amount of bytes could be used. It is not advised to use a variable-length seed longer
|
||||
/// than 256 bits, as a brute-force attack on the master key could be performed in 2^256
|
||||
/// attempts.
|
||||
///
|
||||
/// Mnemonics use a 512 bit seed, as knowledge of the mnemonics' words (such as through a side
|
||||
/// channel attack) could leak which individual word is used, but not the order the words are
|
||||
/// used in. Using a 512 bit hash to generate the seed results in a more computationally
|
||||
/// expensive brute-force requirement.
|
||||
pub struct VariableLengthSeed<'a> {
|
||||
seed: &'a [u8],
|
||||
}
|
||||
|
||||
impl<'a> VariableLengthSeed<'a> {
|
||||
/// Create a new VariableLengthSeed.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```rust
|
||||
/// use sha2::{Sha256, Digest};
|
||||
/// use keyfork_derive_util::VariableLengthSeed;
|
||||
///
|
||||
/// let data = b"the missile is very eepy and wants to take a small sleeb";
|
||||
/// let seed = VariableLengthSeed::new(data);
|
||||
/// ```
|
||||
pub fn new(seed: &'a [u8]) -> Self {
|
||||
Self { seed }
|
||||
}
|
||||
}
|
||||
|
||||
mod as_private_key {
|
||||
use super::VariableLengthSeed;
|
||||
|
||||
pub trait AsPrivateKey {
|
||||
fn as_private_key(&self) -> &[u8];
|
||||
}
|
||||
|
||||
impl AsPrivateKey for [u8; 16] {
|
||||
fn as_private_key(&self) -> &[u8] {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl AsPrivateKey for [u8; 32] {
|
||||
fn as_private_key(&self) -> &[u8] {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl AsPrivateKey for [u8; 64] {
|
||||
fn as_private_key(&self) -> &[u8] {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl AsPrivateKey for VariableLengthSeed<'_> {
|
||||
fn as_private_key(&self) -> &[u8] {
|
||||
self.seed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Extended private keys derived using BIP-0032.
|
||||
///
|
||||
/// Generic over types implementing [`PrivateKey`].
|
||||
|
@ -101,10 +163,10 @@ where
|
|||
/// # };
|
||||
/// let seed: &[u8; 64] = //
|
||||
/// # b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
|
||||
/// let xprv = ExtendedPrivateKey::<PrivateKey>::new(seed);
|
||||
/// let xprv = ExtendedPrivateKey::<PrivateKey>::new(*seed);
|
||||
/// ```
|
||||
pub fn new(seed: impl AsRef<[u8]>) -> Self {
|
||||
Self::new_internal(seed.as_ref())
|
||||
pub fn new(seed: impl as_private_key::AsPrivateKey) -> Self {
|
||||
Self::new_internal(seed.as_private_key())
|
||||
}
|
||||
|
||||
fn new_internal(seed: &[u8]) -> Self {
|
||||
|
@ -191,7 +253,7 @@ where
|
|||
/// # 102, 201, 210, 159, 219, 222, 42, 201, 44, 196, 27,
|
||||
/// # 90, 221, 80, 85, 135, 79, 39, 253, 223, 35, 251
|
||||
/// # ];
|
||||
/// let xprv = ExtendedPrivateKey::<PrivateKey>::new(seed);
|
||||
/// let xprv = ExtendedPrivateKey::<PrivateKey>::new(*seed);
|
||||
/// let xpub = xprv.extended_public_key();
|
||||
/// assert_eq!(known_key, xpub.public_key().to_bytes());
|
||||
/// # Ok(())
|
||||
|
@ -215,7 +277,7 @@ where
|
|||
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
/// let seed: &[u8; 64] = //
|
||||
/// # b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
|
||||
/// let xprv = ExtendedPrivateKey::<PrivateKey>::new(seed);
|
||||
/// let xprv = ExtendedPrivateKey::<PrivateKey>::new(*seed);
|
||||
/// let pubkey = xprv.public_key();
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
|
@ -280,7 +342,7 @@ where
|
|||
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
/// let seed: &[u8; 64] = //
|
||||
/// # b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
|
||||
/// let root_xprv = ExtendedPrivateKey::<PrivateKey>::new(seed);
|
||||
/// let root_xprv = ExtendedPrivateKey::<PrivateKey>::new(*seed);
|
||||
/// let path = DerivationPath::default()
|
||||
/// .chain_push(DerivationIndex::new(44, true)?)
|
||||
/// .chain_push(DerivationIndex::new(0, true)?)
|
||||
|
@ -326,7 +388,7 @@ where
|
|||
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
/// let seed: &[u8; 64] = //
|
||||
/// # b"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
|
||||
/// let root_xprv = ExtendedPrivateKey::<PrivateKey>::new(seed);
|
||||
/// let root_xprv = ExtendedPrivateKey::<PrivateKey>::new(*seed);
|
||||
/// let bip44_wallet = DerivationPath::default()
|
||||
/// .chain_push(DerivationIndex::new(44, true)?)
|
||||
/// .chain_push(DerivationIndex::new(0, true)?)
|
||||
|
|
|
@ -17,7 +17,7 @@ pub mod public_key;
|
|||
mod tests;
|
||||
|
||||
#[doc(inline)]
|
||||
pub use crate::extended_key::{private_key::ExtendedPrivateKey, public_key::ExtendedPublicKey};
|
||||
pub use crate::extended_key::{private_key::{ExtendedPrivateKey, Error as XPrvError, VariableLengthSeed}, public_key::{ExtendedPublicKey, Error as XPubError}};
|
||||
|
||||
pub use crate::{
|
||||
index::{DerivationIndex, Error as IndexError},
|
||||
|
|
|
@ -19,10 +19,11 @@
|
|||
//! ```
|
||||
|
||||
use crate::{
|
||||
extended_key::private_key::Error as XPrvError,
|
||||
extended_key::private_key::{Error as XPrvError, VariableLengthSeed},
|
||||
private_key::{PrivateKey, TestPrivateKey},
|
||||
DerivationPath, ExtendedPrivateKey,
|
||||
};
|
||||
|
||||
use keyfork_mnemonic_util::{Mnemonic, MnemonicGenerationError};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
|
@ -64,7 +65,8 @@ impl DerivationAlgorithm {
|
|||
///
|
||||
/// # Errors
|
||||
/// The method may error if the derivation fails or if the algorithm is not supported.
|
||||
fn derive(&self, seed: Vec<u8>, path: &DerivationPath) -> Result<DerivationResponse> {
|
||||
fn derive(&self, seed: &[u8], path: &DerivationPath) -> Result<DerivationResponse> {
|
||||
let seed = VariableLengthSeed::new(seed);
|
||||
match self {
|
||||
#[cfg(feature = "ed25519")]
|
||||
Self::Ed25519 => {
|
||||
|
@ -207,7 +209,7 @@ impl DerivationRequest {
|
|||
/// # }
|
||||
pub fn derive_with_mnemonic(&self, mnemonic: &Mnemonic) -> Result<DerivationResponse> {
|
||||
// TODO: passphrase support and/or store passphrase within mnemonic
|
||||
self.derive_with_master_seed(mnemonic.seed(None)?)
|
||||
self.derive_with_master_seed(&mnemonic.seed(None)?)
|
||||
}
|
||||
|
||||
/// Derive an [`ExtendedPrivateKey`] using the given seed.
|
||||
|
@ -231,10 +233,10 @@ impl DerivationRequest {
|
|||
/// let path: DerivationPath = //
|
||||
/// # DerivationPath::default();
|
||||
/// let request = DerivationRequest::new(algo, &path);
|
||||
/// let response = request.derive_with_master_seed(seed.to_vec())?;
|
||||
/// let response = request.derive_with_master_seed(seed)?;
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
pub fn derive_with_master_seed(&self, seed: Vec<u8>) -> Result<DerivationResponse> {
|
||||
pub fn derive_with_master_seed(&self, seed: &[u8]) -> Result<DerivationResponse> {
|
||||
self.algorithm.derive(seed, &self.path)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -30,7 +30,8 @@ fn secp256k1() {
|
|||
} = test;
|
||||
|
||||
// Tests for ExtendedPrivateKey
|
||||
let xkey = ExtendedPrivateKey::<SecretKey>::new(seed);
|
||||
let varlen_seed = VariableLengthSeed::new(&seed);
|
||||
let xkey = ExtendedPrivateKey::<SecretKey>::new(varlen_seed);
|
||||
let derived_key = xkey.derive_path(&chain).unwrap();
|
||||
assert_eq!(
|
||||
derived_key.chain_code().as_slice(),
|
||||
|
@ -50,7 +51,7 @@ fn secp256k1() {
|
|||
|
||||
// Tests for DerivationRequest
|
||||
let request = DerivationRequest::new(DerivationAlgorithm::Secp256k1, &chain);
|
||||
let response = request.derive_with_master_seed(seed.clone()).unwrap();
|
||||
let response = request.derive_with_master_seed(&seed).unwrap();
|
||||
assert_eq!(&response.data, private_key.as_slice(), "test: {chain}");
|
||||
}
|
||||
}
|
||||
|
@ -75,7 +76,8 @@ fn ed25519() {
|
|||
} = test;
|
||||
|
||||
// Tests for ExtendedPrivateKey
|
||||
let xkey = ExtendedPrivateKey::<SigningKey>::new(seed);
|
||||
let varlen_seed = VariableLengthSeed::new(&seed);
|
||||
let xkey = ExtendedPrivateKey::<SigningKey>::new(varlen_seed);
|
||||
let derived_key = xkey.derive_path(&chain).unwrap();
|
||||
assert_eq!(
|
||||
derived_key.chain_code().as_slice(),
|
||||
|
@ -95,7 +97,7 @@ fn ed25519() {
|
|||
|
||||
// Tests for DerivationRequest
|
||||
let request = DerivationRequest::new(DerivationAlgorithm::Ed25519, &chain);
|
||||
let response = request.derive_with_master_seed(seed.to_vec()).unwrap();
|
||||
let response = request.derive_with_master_seed(&seed).unwrap();
|
||||
assert_eq!(&response.data, private_key.as_slice(), "test: {chain}");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,11 +7,10 @@ license = "AGPL-3.0-only"
|
|||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[features]
|
||||
default = ["openpgp", "openpgp-card", "qrcode"]
|
||||
default = ["openpgp", "openpgp-card", "qrcode", "sequoia-openpgp/crypto-nettle", "keyfork-qrcode/decode-backend-rqrr"]
|
||||
openpgp = ["sequoia-openpgp", "anyhow"]
|
||||
openpgp-card = ["openpgp-card-sequoia", "card-backend-pcsc", "card-backend", "dep:openpgp-card"]
|
||||
qrcode = ["keyfork-qrcode"]
|
||||
bin = ["sequoia-openpgp/crypto-nettle", "keyfork-qrcode/decode-backend-rqrr"]
|
||||
|
||||
[dependencies]
|
||||
keyfork-prompt = { version = "0.1.0", path = "../util/keyfork-prompt", default-features = false, features = ["mnemonic"] }
|
||||
|
|
|
@ -14,7 +14,7 @@ use aes_gcm::{
|
|||
};
|
||||
use hkdf::{Hkdf, InvalidLength as HkdfInvalidLength};
|
||||
use keyfork_derive_openpgp::{
|
||||
derive_util::{DerivationPath, PathError},
|
||||
derive_util::{DerivationPath, PathError, VariableLengthSeed},
|
||||
XPrv,
|
||||
};
|
||||
use keyfork_mnemonic_util::{Mnemonic, MnemonicFromStrError, MnemonicGenerationError, Wordlist};
|
||||
|
@ -648,7 +648,8 @@ pub fn combine(
|
|||
// TODO: extract as function
|
||||
let userid = UserID::from("keyfork-sss");
|
||||
let path = DerivationPath::from_str("m/7366512'/0'")?;
|
||||
let xprv = XPrv::new(&secret).derive_path(&path)?;
|
||||
let seed = VariableLengthSeed::new(&secret);
|
||||
let xprv = XPrv::new(seed).derive_path(&path)?;
|
||||
let derived_cert = keyfork_derive_openpgp::derive(
|
||||
xprv,
|
||||
&[KeyFlags::empty().set_certification().set_signing()],
|
||||
|
@ -679,10 +680,11 @@ pub fn combine(
|
|||
/// The function may panic if the metadata can't properly store the certificates used to generate
|
||||
/// the encrypted shares.
|
||||
pub fn split(threshold: u8, certs: Vec<Cert>, secret: &[u8], output: impl Write) -> Result<()> {
|
||||
let seed = VariableLengthSeed::new(secret);
|
||||
// build cert to sign encrypted shares
|
||||
let userid = UserID::from("keyfork-sss");
|
||||
let path = DerivationPath::from_str("m/7366512'/0'")?;
|
||||
let xprv = XPrv::new(&secret).derive_path(&path)?;
|
||||
let xprv = XPrv::new(seed).derive_path(&path)?;
|
||||
let derived_cert = keyfork_derive_openpgp::derive(
|
||||
xprv,
|
||||
&[KeyFlags::empty().set_certification().set_signing()],
|
||||
|
|
|
@ -21,7 +21,7 @@ pub struct PinLength(usize);
|
|||
|
||||
type Result<T, E = Box<dyn std::error::Error>> = std::result::Result<T, E>;
|
||||
|
||||
fn derive_key(seed: &[u8], index: u8) -> Result<Cert> {
|
||||
fn derive_key(seed: [u8; 32], index: u8) -> Result<Cert> {
|
||||
let subkeys = vec![
|
||||
KeyFlags::empty().set_certification(),
|
||||
KeyFlags::empty().set_signing(),
|
||||
|
@ -102,7 +102,7 @@ fn generate_shard_secret(
|
|||
keys_per_shard: u8,
|
||||
output_file: &Option<PathBuf>,
|
||||
) -> Result<()> {
|
||||
let seed = keyfork_entropy::generate_entropy_of_size(256 / 8)?;
|
||||
let seed = keyfork_entropy::generate_entropy_of_const_size::<{256 / 8}>()?;
|
||||
let mut pm = Terminal::new(std::io::stdin(), std::io::stderr())?;
|
||||
let mut certs = vec![];
|
||||
let mut seen_cards: HashSet<String> = HashSet::new();
|
||||
|
@ -126,7 +126,7 @@ fn generate_shard_secret(
|
|||
.to_fn();
|
||||
|
||||
for index in 0..max {
|
||||
let cert = derive_key(&seed, index)?;
|
||||
let cert = derive_key(seed, index)?;
|
||||
for i in 0..keys_per_shard {
|
||||
pm.prompt_message(Message::Text(format!(
|
||||
"Please remove all keys and insert key #{} for user #{}",
|
||||
|
|
|
@ -7,7 +7,7 @@ license = "MIT"
|
|||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[features]
|
||||
default = []
|
||||
default = ["bin"]
|
||||
bin = ["smex"]
|
||||
|
||||
[dependencies]
|
||||
|
|
|
@ -1,6 +1,9 @@
|
|||
//! Utilities for reading entropy from secure sources.
|
||||
|
||||
use std::{fs::{read_dir, read_to_string, File}, io::Read};
|
||||
use std::{
|
||||
fs::{read_dir, read_to_string, File},
|
||||
io::Read,
|
||||
};
|
||||
|
||||
static WARNING_LINKS: [&str; 1] =
|
||||
["https://lore.kernel.org/lkml/20211223141113.1240679-2-Jason@zx2c4.com/"];
|
||||
|
@ -84,3 +87,24 @@ pub fn generate_entropy_of_size(byte_count: usize) -> Result<Vec<u8>, std::io::E
|
|||
entropy_file.read_exact(&mut vec[..])?;
|
||||
Ok(vec)
|
||||
}
|
||||
|
||||
/// Read system entropy of a constant size.
|
||||
///
|
||||
/// # Errors
|
||||
/// An error may be returned if an error occurred while reading from the random source.
|
||||
///
|
||||
/// # Examples
|
||||
/// ```rust,no_run
|
||||
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
/// # std::env::set_var("SHOOT_SELF_IN_FOOT", "1");
|
||||
/// let entropy = keyfork_entropy::generate_entropy_of_const_size::<64>()?;
|
||||
/// assert_eq!(entropy.len(), 64);
|
||||
/// # Ok(())
|
||||
/// # }
|
||||
/// ```
|
||||
pub fn generate_entropy_of_const_size<const N: usize>() -> Result<[u8; N], std::io::Error> {
|
||||
let mut output = [0u8; N];
|
||||
let mut entropy_file = File::open("/dev/urandom")?;
|
||||
entropy_file.read_exact(&mut output[..])?;
|
||||
Ok(output)
|
||||
}
|
||||
|
|
|
@ -7,7 +7,7 @@ edition = "2021"
|
|||
license = "MIT"
|
||||
|
||||
[features]
|
||||
default = []
|
||||
default = ["bin"]
|
||||
bin = ["smex"]
|
||||
|
||||
[dependencies]
|
||||
|
|
|
@ -276,7 +276,7 @@ impl Mnemonic {
|
|||
}
|
||||
|
||||
/// Clone the existing entropy.
|
||||
#[deprecated]
|
||||
#[deprecated = "Use as_bytes(), to_bytes(), or into_bytes() instead"]
|
||||
pub fn entropy(&self) -> Vec<u8> {
|
||||
self.entropy.clone()
|
||||
}
|
||||
|
@ -353,8 +353,8 @@ mod tests {
|
|||
random_handle.read_exact(&mut entropy[..]).unwrap();
|
||||
let wordlist = Wordlist::default().arc();
|
||||
let mnemonic = super::Mnemonic::from_entropy(&entropy[..256 / 8], wordlist).unwrap();
|
||||
let new_entropy = mnemonic.entropy();
|
||||
assert_eq!(&new_entropy, entropy);
|
||||
let new_entropy = mnemonic.as_bytes();
|
||||
assert_eq!(new_entropy, entropy);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
@ -22,8 +22,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
3,
|
||||
transport_validator.to_fn(),
|
||||
)?;
|
||||
assert_eq!(mnemonics[0].entropy().len(), 12);
|
||||
assert_eq!(mnemonics[1].entropy().len(), 32);
|
||||
assert_eq!(mnemonics[0].as_bytes().len(), 12);
|
||||
assert_eq!(mnemonics[1].as_bytes().len(), 32);
|
||||
|
||||
let mnemonics = mgr.prompt_validated_wordlist(
|
||||
"Enter a 24 and 48-word mnemonic: ",
|
||||
|
@ -31,8 +31,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||
3,
|
||||
combine_validator.to_fn(),
|
||||
)?;
|
||||
assert_eq!(mnemonics[0].entropy().len(), 32);
|
||||
assert_eq!(mnemonics[1].entropy().len(), 64);
|
||||
assert_eq!(mnemonics[0].as_bytes().len(), 32);
|
||||
assert_eq!(mnemonics[1].as_bytes().len(), 64);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue