Skip to content

Commit

Permalink
chore: rename signer to key provider
Browse files Browse the repository at this point in the history
  • Loading branch information
driftluo committed Apr 25, 2023
1 parent 0791074 commit 6586f3a
Show file tree
Hide file tree
Showing 28 changed files with 121 additions and 126 deletions.
2 changes: 1 addition & 1 deletion bench/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ where

if secio {
builder
.key_pair(SecioKeyPair::secp256k1_generated())
.key_provider(SecioKeyPair::secp256k1_generated())
.build(shandle)
} else {
builder.build(shandle)
Expand Down
12 changes: 6 additions & 6 deletions secio/src/handshake/handshake_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use crate::{
handshake_struct::{Propose, PublicKey},
Config,
},
support, Digest, Pubkey, Signer,
support, Digest, KeyProvider, Pubkey,
};

use bytes::{Bytes, BytesMut};
Expand Down Expand Up @@ -77,7 +77,7 @@ pub struct PubEphemeral {

impl<K> HandshakeContext<(), K>
where
K: Signer,
K: KeyProvider,
{
pub fn new(config: Config<K>) -> Self {
HandshakeContext { config, state: () }
Expand All @@ -89,7 +89,7 @@ where
rand::thread_rng().fill_bytes(&mut nonce);

let public_key = PublicKey {
key: self.config.key.pubkey().serialize(),
key: self.config.key_provider.pubkey().serialize(),
};

// Send our proposition with our nonce, public key and supported protocols.
Expand Down Expand Up @@ -134,7 +134,7 @@ where

impl<K> HandshakeContext<Local, K>
where
K: Signer,
K: KeyProvider,
{
// Process remote proposition.
pub fn with_remote(
Expand Down Expand Up @@ -262,7 +262,7 @@ where

impl<K> HandshakeContext<Remote, K>
where
K: Signer,
K: KeyProvider,
{
pub fn with_ephemeral(
self,
Expand All @@ -282,7 +282,7 @@ where

impl<K> HandshakeContext<Ephemeral, K>
where
K: Signer,
K: KeyProvider,
{
pub fn take_private_key(
self,
Expand Down
6 changes: 3 additions & 3 deletions secio/src/handshake/handshake_struct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ impl fmt::Debug for PublicKey {
#[cfg(test)]
mod tests {
use super::{Exchange, Propose, PublicKey};
use crate::{SecioKeyPair, Signer};
use crate::{KeyProvider, SecioKeyPair};
use bytes::Bytes;

#[test]
Expand Down Expand Up @@ -216,13 +216,13 @@ mod tests {
let raw = privkey.public_key();
let inner = raw.inner_ref();

let other = SecioKeyPair::pubkey_from_slice(inner).unwrap();
let other = <SecioKeyPair as KeyProvider>::Pubkey::from_slice(inner).unwrap();
assert_eq!(raw.inner_ref(), other.serialize());
let uncompressed = crate::secp256k1_compat::pubkey_from_slice(inner)
.map(|key| key.serialize_uncompressed().to_vec())
.unwrap();

let other_1 = SecioKeyPair::pubkey_from_slice(&uncompressed).unwrap();
let other_1 = <SecioKeyPair as KeyProvider>::Pubkey::from_slice(&uncompressed).unwrap();
assert_eq!(raw.inner_ref(), other_1.serialize());
}
}
10 changes: 4 additions & 6 deletions secio/src/handshake/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ use crate::{
use crate::codec::secure_stream::SecureStream;
use tokio::io::{AsyncRead, AsyncWrite};

use std::sync::Arc;

#[rustfmt::skip]
#[allow(clippy::all)]
#[allow(dead_code)]
Expand All @@ -23,7 +21,7 @@ const MAX_FRAME_SIZE: usize = 1024 * 1024 * 8;
/// Config for Secio
#[derive(Debug, Clone)]
pub struct Config<K> {
pub(crate) key: Arc<K>,
pub(crate) key_provider: K,
pub(crate) agreements_proposal: Option<String>,
pub(crate) ciphers_proposal: Option<String>,
pub(crate) digests_proposal: Option<String>,
Expand All @@ -32,12 +30,12 @@ pub struct Config<K> {

impl<K> Config<K>
where
K: crate::Signer,
K: crate::KeyProvider,
{
/// Create config
pub fn new(key_pair: K) -> Self {
pub fn new(key_provider: K) -> Self {
Config {
key: Arc::new(key_pair),
key_provider,
agreements_proposal: None,
ciphers_proposal: None,
digests_proposal: None,
Expand Down
19 changes: 10 additions & 9 deletions secio/src/handshake/procedure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use crate::{
handshake_context::HandshakeContext,
handshake_struct::{Exchange, PublicKey},
},
EphemeralPublicKey, Pubkey, Signer,
EphemeralPublicKey, KeyProvider, Pubkey,
};
use bytes::BytesMut;
use tokio::io::AsyncWriteExt;
Expand All @@ -37,7 +37,7 @@ pub(in crate::handshake) async fn handshake<T, K>(
) -> Result<(SecureStream<T>, PublicKey, EphemeralPublicKey), SecioError>
where
T: AsyncRead + AsyncWrite + Send + 'static + Unpin,
K: Signer,
K: KeyProvider,
{
// The handshake messages all start with a 4-bytes message length prefix.
let mut socket = Builder::new()
Expand Down Expand Up @@ -104,13 +104,13 @@ where
#[cfg(not(feature = "async-trait"))]
let signature = ephemeral_context
.config
.key
.key_provider
.sign_ecdsa(AsRef::<[u8]>::as_ref(&data_to_sign))
.map_err(Into::into)?;
#[cfg(feature = "async-trait")]
let signature = ephemeral_context
.config
.key
.key_provider
.sign_ecdsa_async(AsRef::<[u8]>::as_ref(&data_to_sign))
.await
.map_err(Into::into)?;
Expand Down Expand Up @@ -156,9 +156,10 @@ where

let data_to_verify = crate::sha256_compat::sha256(&data_to_verify);

let remote_public_key =
<K as Signer>::pubkey_from_slice(ephemeral_context.state.remote.public_key.inner_ref())
.map_err(Into::into)?;
let remote_public_key = <K as KeyProvider>::Pubkey::from_slice(
ephemeral_context.state.remote.public_key.inner_ref(),
)
.map_err(Into::into)?;

if !remote_public_key.verify_ecdsa(&data_to_verify, &remote_exchanges.signature) {
debug!("failed to verify the remote's signature");
Expand Down Expand Up @@ -290,7 +291,7 @@ fn generate_stream_cipher_and_hmac(
#[cfg(test)]
mod tests {
use super::stretch_key;
use crate::{codec::hmac_compat::Hmac, handshake::Config, Digest, SecioKeyPair, Signer};
use crate::{codec::hmac_compat::Hmac, handshake::Config, Digest, KeyProvider, SecioKeyPair};

use bytes::BytesMut;
use futures::channel;
Expand All @@ -299,7 +300,7 @@ mod tests {
net::{TcpListener, TcpStream},
};

fn handshake_with_self_success<K: Signer>(
fn handshake_with_self_success<K: KeyProvider>(
config_1: Config<K>,
config_2: Config<K>,
data: &'static [u8],
Expand Down
62 changes: 24 additions & 38 deletions secio/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ impl Digest {
all(not(target_arch = "wasm32"), feature = "async-trait"),
async_trait::async_trait
)]
pub trait Signer: std::fmt::Debug + Send + Sync + 'static {
pub trait KeyProvider: std::clone::Clone + Send + Sync + 'static {
/// Error
type Error: Into<crate::error::SecioError>;
/// Public key
Expand All @@ -131,30 +131,34 @@ pub trait Signer: std::fmt::Debug + Send + Sync + 'static {
}

/// Constructs a signature for `msg` using the secret key `sk`
fn sign_ecdsa<T: AsRef<[u8]> + Send>(&self, message: T) -> Result<Vec<u8>, Self::Error>;
fn sign_ecdsa<T: AsRef<[u8]>>(&self, message: T) -> Result<Vec<u8>, Self::Error>;

/// Creates a new public key from a [`Signer`].
/// Creates a new public key from the [`Signer`].
fn pubkey(&self) -> Self::Pubkey;

/// Recover public key from slice
fn pubkey_from_slice<T: AsRef<[u8]>>(key: T) -> Result<Self::Pubkey, Self::Error>;
}

/// Public key for Signer
pub trait Pubkey: std::fmt::Debug + Send + Sync + 'static {
pub trait Pubkey: Send + Sync + 'static {
/// Error
type Error: Into<crate::error::SecioError>;
/// Checks that `sig` is a valid ECDSA signature for `msg` using the public
/// key `pubkey`.
fn verify_ecdsa<T: AsRef<[u8]>, F: AsRef<[u8]>>(&self, message: T, signature: F) -> bool;

/// serialized key into a bytes
fn serialize(&self) -> Vec<u8>;

/// Recover public key from slice
fn from_slice<T: AsRef<[u8]>>(key: T) -> Result<Self, Self::Error>
where
Self: Sized;
}

impl Signer for SecioKeyPair {
impl KeyProvider for SecioKeyPair {
type Error = error::SecioError;
type Pubkey = secp256k1_compat::PublicKey;

fn sign_ecdsa<T: AsRef<[u8]> + Send>(&self, message: T) -> Result<Vec<u8>, Self::Error> {
fn sign_ecdsa<T: AsRef<[u8]>>(&self, message: T) -> Result<Vec<u8>, Self::Error> {
let msg = match crate::secp256k1_compat::message_from_slice(message.as_ref()) {
Ok(m) => m,
Err(_) => {
Expand All @@ -176,14 +180,10 @@ impl Signer for SecioKeyPair {
}
}
}

fn pubkey_from_slice<T: AsRef<[u8]>>(key: T) -> Result<Self::Pubkey, Self::Error> {
crate::secp256k1_compat::pubkey_from_slice(key.as_ref())
.map_err(|_| crate::error::SecioError::SecretGenerationFailed)
}
}

impl Pubkey for secp256k1_compat::PublicKey {
type Error = error::SecioError;
fn verify_ecdsa<T: AsRef<[u8]>, F: AsRef<[u8]>>(&self, message: T, signature: F) -> bool {
let signature = crate::secp256k1_compat::signature_from_der(signature.as_ref());
let msg = crate::secp256k1_compat::message_from_slice(message.as_ref());
Expand All @@ -203,51 +203,37 @@ impl Pubkey for secp256k1_compat::PublicKey {
fn serialize(&self) -> Vec<u8> {
crate::secp256k1_compat::serialize_pubkey(self)
}
}

impl<T> Signer for std::sync::Arc<T>
where
T: Signer,
{
type Error = <T as Signer>::Error;
type Pubkey = <T as Signer>::Pubkey;

fn sign_ecdsa<F: AsRef<[u8]> + Send>(&self, message: F) -> Result<Vec<u8>, Self::Error> {
self.as_ref().sign_ecdsa(message)
}

fn pubkey(&self) -> Self::Pubkey {
self.as_ref().pubkey()
}

fn pubkey_from_slice<F: AsRef<[u8]>>(key: F) -> Result<Self::Pubkey, Self::Error> {
<T as Signer>::pubkey_from_slice(key)
fn from_slice<T: AsRef<[u8]>>(key: T) -> Result<Self, Self::Error> {
crate::secp256k1_compat::pubkey_from_slice(key.as_ref())
.map_err(|_| crate::error::SecioError::SecretGenerationFailed)
}
}

impl Signer for () {
impl KeyProvider for () {
type Error = error::SecioError;
type Pubkey = ();

fn sign_ecdsa<T: AsRef<[u8]> + Send>(&self, _message: T) -> Result<Vec<u8>, Self::Error> {
fn sign_ecdsa<T: AsRef<[u8]>>(&self, _message: T) -> Result<Vec<u8>, Self::Error> {
Err(error::SecioError::NotSupportSigner)
}

fn pubkey(&self) -> Self::Pubkey {
()
}

fn pubkey_from_slice<T: AsRef<[u8]>>(_key: T) -> Result<Self::Pubkey, Self::Error> {
Ok(())
}
}

impl Pubkey for () {
type Error = error::SecioError;
fn verify_ecdsa<T: AsRef<[u8]>, F: AsRef<[u8]>>(&self, _message: T, _signature: F) -> bool {
false
}

fn serialize(&self) -> Vec<u8> {
Vec::new()
}

fn from_slice<T: AsRef<[u8]>>(_key: T) -> Result<Self, Self::Error> {
Ok(())
}
}
2 changes: 1 addition & 1 deletion tentacle/examples/block_send.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ where

if secio {
builder
.key_pair(SecioKeyPair::secp256k1_generated())
.key_provider(SecioKeyPair::secp256k1_generated())
.build(shandle)
} else {
builder.build(shandle)
Expand Down
2 changes: 1 addition & 1 deletion tentacle/examples/heavy_task_schedule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ where

if secio {
builder
.key_pair(SecioKeyPair::secp256k1_generated())
.key_provider(SecioKeyPair::secp256k1_generated())
.build(shandle)
} else {
builder.build(shandle)
Expand Down
4 changes: 2 additions & 2 deletions tentacle/examples/simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ fn create_server() -> Service<SHandle, SecioKeyPair> {
ServiceBuilder::default()
.insert_protocol(create_meta(0.into()))
.insert_protocol(create_meta(1.into()))
.key_pair(SecioKeyPair::secp256k1_generated())
.key_provider(SecioKeyPair::secp256k1_generated())
.build(SHandle)
}

Expand All @@ -200,7 +200,7 @@ fn create_client() -> Service<SHandle, SecioKeyPair> {
.insert_protocol(create_meta(0.into()))
.insert_protocol(create_meta(1.into()))
.insert_protocol(create_meta(2.into()))
.key_pair(SecioKeyPair::secp256k1_generated())
.key_provider(SecioKeyPair::secp256k1_generated())
.build(SHandle)
}

Expand Down
4 changes: 2 additions & 2 deletions tentacle/examples/simple_using_spawn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ fn create_server() -> Service<SHandle, SecioKeyPair> {
ServiceBuilder::default()
.insert_protocol(create_meta(0.into()))
.insert_protocol(create_meta(1.into()))
.key_pair(SecioKeyPair::secp256k1_generated())
.key_provider(SecioKeyPair::secp256k1_generated())
.build(SHandle)
}

Expand All @@ -144,7 +144,7 @@ fn create_client() -> Service<SHandle, SecioKeyPair> {
.insert_protocol(create_meta(0.into()))
.insert_protocol(create_meta(1.into()))
.insert_protocol(create_meta(2.into()))
.key_pair(SecioKeyPair::secp256k1_generated())
.key_provider(SecioKeyPair::secp256k1_generated())
.build(SHandle)
}

Expand Down
2 changes: 1 addition & 1 deletion tentacle/examples/use_poll.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ fn create_meta(id: ProtocolId, recv: Receiver<()>) -> ProtocolMeta {
fn create_server(recv: Receiver<()>) -> Service<SHandle, SecioKeyPair> {
ServiceBuilder::default()
.insert_protocol(create_meta(0.into(), recv))
.key_pair(SecioKeyPair::secp256k1_generated())
.key_provider(SecioKeyPair::secp256k1_generated())
.build(SHandle)
}

Expand Down
Loading

0 comments on commit 6586f3a

Please sign in to comment.