Compare commits

...

4 Commits

8 changed files with 196 additions and 42 deletions

76
Cargo.lock generated
View File

@ -174,7 +174,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf4c2f4e1afd912bc40bfd6fed5d9dc1f288e0ba01bfcc835cc5bc3eb13efe15"
dependencies = [
"generic-array",
"rand_core",
"rand_core 0.6.4",
"subtle",
"zeroize",
]
@ -286,7 +286,7 @@ dependencies = [
"generic-array",
"group",
"pkcs8",
"rand_core",
"rand_core 0.6.4",
"sec1",
"subtle",
"zeroize",
@ -304,7 +304,7 @@ version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ded41244b729663b1e574f1b4fb731469f69f79c17667b5d776b16cda0479449"
dependencies = [
"rand_core",
"rand_core 0.6.4",
"subtle",
]
@ -314,6 +314,12 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d0870c84016d4b481be5c9f323c24f65e31e901ae618f0e80f4308fb00de1d2d"
[[package]]
name = "fuchsia-cprng"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a06f77d526c1a601b7c4cdd98f54b5eaabffc14d5f2f0296febdc7f357c6d3ba"
[[package]]
name = "futures-core"
version = "0.3.28"
@ -373,7 +379,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63"
dependencies = [
"ff",
"rand_core",
"rand_core 0.6.4",
"subtle",
]
@ -485,9 +491,13 @@ version = "0.1.0"
dependencies = [
"bincode",
"clap",
"hex-literal",
"keyfork-derive-util",
"keyfork-frame",
"keyforkd",
"tempdir",
"thiserror",
"tokio",
]
[[package]]
@ -674,6 +684,34 @@ dependencies = [
"proc-macro2",
]
[[package]]
name = "rand"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "552840b97013b1a26992c11eac34bdd778e464601a4c2054b5f0bff7c6761293"
dependencies = [
"fuchsia-cprng",
"libc",
"rand_core 0.3.1",
"rdrand",
"winapi",
]
[[package]]
name = "rand_core"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a6fdeb83b075e8266dcc8762c22776f6877a63111121f5f8c7411e5be7eed4b"
dependencies = [
"rand_core 0.4.2",
]
[[package]]
name = "rand_core"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c33a3c44ca05fa6f1807d8e6743f3824e8509beca625669633be0acbdf509dc"
[[package]]
name = "rand_core"
version = "0.6.4"
@ -683,6 +721,15 @@ dependencies = [
"getrandom",
]
[[package]]
name = "rdrand"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "678054eb77286b51581ba43620cc911abf02758c91f93f479767aed0f90458b2"
dependencies = [
"rand_core 0.3.1",
]
[[package]]
name = "regex"
version = "1.9.3"
@ -727,6 +774,15 @@ version = "0.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5ea92a5b6195c6ef2a0295ea818b312502c6fc94dde986c5553242e18fd4ce2"
[[package]]
name = "remove_dir_all"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7"
dependencies = [
"winapi",
]
[[package]]
name = "ripemd"
version = "0.1.3"
@ -843,7 +899,7 @@ version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e1788eed21689f9cf370582dfc467ef36ed9c707f073528ddafa8d83e3b8500"
dependencies = [
"rand_core",
"rand_core 0.6.4",
]
[[package]]
@ -895,6 +951,16 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "tempdir"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15f2b5fb00ccdf689e0149d1b1b3c03fead81c2b37735d812fa8bddbbf41b6d8"
dependencies = [
"rand",
"remove_dir_all",
]
[[package]]
name = "thiserror"
version = "1.0.48"

View File

@ -11,3 +11,9 @@ clap = { version = "4.4.2", default-features = false, features = ["std", "usage"
keyfork-derive-util = { version = "0.1.0", path = "../keyfork-derive-util" }
keyfork-frame = { version = "0.1.0", path = "../keyfork-frame", default-features = false }
thiserror = "1.0.48"
[dev-dependencies]
hex-literal = "0.4.1"
keyforkd = { path = "../keyforkd", default-features = false }
tempdir = "0.3.7"
tokio = { version = "1.32.0", features = ["rt", "rt-multi-thread"] }

View File

@ -0,0 +1,21 @@
use keyfork_frame::*;
use crate::Result;
use std::os::unix::net::UnixStream;
use keyfork_derive_util::request::*;
#[derive(Debug)]
pub struct Client {
socket: UnixStream,
}
impl Client {
pub fn new(socket: UnixStream) -> Self {
Self { socket }
}
pub fn request(&mut self, req: &DerivationRequest) -> Result<DerivationResponse> {
try_encode_to(&bincode::serialize(&req)?, &mut self.socket)?;
let resp = try_decode_from(&mut self.socket)?;
bincode::deserialize(&resp).map_err(From::from)
}
}

View File

@ -4,6 +4,10 @@ use std::path::PathBuf;
mod cli;
mod socket;
mod client;
#[cfg(test)]
mod tests;
#[derive(Debug, thiserror::Error)]
pub enum Error {
@ -32,18 +36,18 @@ pub enum Error {
FrameDec(#[from] DecodeError),
}
fn main() -> Result<(), Error> {
pub type Result<T, E = Error> = std::result::Result<T, E>;
fn main() -> Result<()> {
let args = cli::get_args();
let mut socket = socket::get_socket()?;
let socket = socket::get_socket()?;
let mut client = client::Client::new(socket);
let path = args.get_one::<DerivationPath>("path").expect("required");
let algo = args
.get_one::<DerivationAlgorithm>("algorithm")
.expect("required");
let req = DerivationRequest::new(algo.clone(), path.clone());
let ser_req = bincode::serialize(&req)?;
try_encode_to(&ser_req, &mut socket)?;
let ser_response = try_decode_from(&mut socket)?;
let response: DerivationResponse = bincode::deserialize(&ser_response)?;
let request = DerivationRequest::new(algo.clone(), path.clone());
let response = client.request(&request)?;
dbg!(&response);
Ok(())
}

47
keyfork-seed/src/tests.rs Normal file
View File

@ -0,0 +1,47 @@
use crate::client::Client;
use hex_literal::hex;
use keyfork_derive_util::{request::*, DerivationPath};
use std::{os::unix::net::UnixStream, str::FromStr};
use tempdir::TempDir;
use tokio::runtime::Builder;
use std::sync::mpsc::channel;
#[test]
fn it_works() {
// Test literals taken from keyfork-derive-util.
// Setup
let entropy = &hex!("000102030405060708090a0b0c0d0e0f")[..];
let mnemonic = keyforkd::Mnemonic::from_entropy(entropy, Default::default()).unwrap();
let rt = Builder::new_multi_thread().enable_io().build().unwrap();
let tempdir = TempDir::new("keyfork-seed").unwrap();
let socket_path = tempdir.path().join("keyforkd.sock");
let (tx, rx) = channel();
let handle = rt.spawn({
let socket_path = socket_path.clone();
async move {
let mut server = keyforkd::UnixServer::bind(&socket_path).unwrap();
// Connections can be pending for a few seconds, so signal to the main
// test we're ready to start accepting.
tx.send(()).unwrap();
let service = keyforkd::ServiceBuilder::new()
.layer(keyforkd::middleware::BincodeLayer::new())
.service(keyforkd::Keyforkd::new(mnemonic));
server.run(service).await.unwrap();
}
});
rx.recv().unwrap();
let socket = UnixStream::connect(&socket_path).unwrap();
let mut client = Client::new(socket);
let req = DerivationRequest::new(
DerivationAlgorithm::Ed25519,
DerivationPath::from_str("m/0'/1'/2'/2'/1000000000'").unwrap(),
);
let response = client.request(&req).unwrap();
assert_eq!(
response.data,
hex!("8f94d394a8e8fd6b1bc2f3f49f5c47e385281d5c17e65324b0f62483e37e8793")
);
handle.abort();
}

View File

@ -1,7 +1,7 @@
use thiserror::Error;
#[derive(Debug, Clone, Error)]
pub(crate) enum KeyforkdError {
pub enum KeyforkdError {
#[error("Neither KEYFORKD_SOCKET_PATH nor XDG_RUNTIME_DIR were set, nowhere to mount socket")]
NoSocketPath,
}

View File

@ -1,24 +1,50 @@
use std::{collections::HashMap, path::PathBuf};
use std::{
collections::HashMap,
path::{Path, PathBuf},
};
use keyfork_mnemonic_util::Mnemonic;
use tower::ServiceBuilder;
pub use keyfork_mnemonic_util::Mnemonic;
pub use tower::ServiceBuilder;
#[cfg(feature = "tracing")]
use tracing::debug;
mod error;
mod middleware;
mod server;
mod service;
use error::KeyforkdError;
use server::UnixServer;
use service::Keyforkd;
pub mod error;
pub mod middleware;
pub mod server;
pub mod service;
pub use error::KeyforkdError;
pub use server::UnixServer;
pub use service::Keyforkd;
pub async fn start_and_run_server(mnemonic: Mnemonic) -> Result<(), Box<dyn std::error::Error>> {
pub async fn start_and_run_server_on(
mnemonic: Mnemonic,
socket_path: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
let service = ServiceBuilder::new()
.layer(middleware::BincodeLayer::new())
.service(Keyforkd::new(mnemonic));
let mut server = match UnixServer::bind(socket_path) {
Ok(s) => s,
Err(e) => {
#[cfg(feature = "tracing")]
debug!(%e, "Encountered error attempting to bind socket: {}", socket_path.display());
return Err(e.into());
}
};
match server.run(service).await {
Ok(_) => (),
Err(e) => {
#[cfg(feature = "tracing")]
debug!(%e, "Encountered error while running");
}
}
Ok(())
}
pub async fn start_and_run_server(mnemonic: Mnemonic) -> Result<(), Box<dyn std::error::Error>> {
let runtime_vars = std::env::vars()
.filter(|(key, _)| ["XDG_RUNTIME_DIR", "KEYFORKD_SOCKET_PATH"].contains(&key.as_str()))
.collect::<HashMap<String, String>>();
@ -50,21 +76,5 @@ pub async fn start_and_run_server(mnemonic: Mnemonic) -> Result<(), Box<dyn std:
runtime_path.display()
);
let mut server = match UnixServer::bind(&runtime_path) {
Ok(s) => s,
Err(e) => {
#[cfg(feature = "tracing")]
debug!(%e, "Encountered error attempting to bind socket: {}", runtime_path.display());
return Err(e.into());
}
};
match server.run(service).await {
Ok(_) => (),
Err(e) => {
#[cfg(feature = "tracing")]
debug!(%e, "Encountered error while running");
}
}
Ok(())
start_and_run_server_on(mnemonic, &runtime_path).await
}

View File

@ -46,7 +46,7 @@ impl Service<DerivationRequest> for Keyforkd {
#[cfg_attr(feature = "tracing", tracing::instrument(skip(self)))]
fn call(&mut self, req: DerivationRequest) -> Self::Future {
let mnemonic = self.mnemonic.clone();
Box::pin(async {
Box::pin(async move {
let len = req.path().len();
if len < 2 {
return Err(KeyforkdRequestError::InvalidDerivationLength(len));