Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(libp2p): multi signature schemes & session signing #2599

Merged
merged 6 commits into from
Oct 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
4 changes: 4 additions & 0 deletions crates/torii/libp2p/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::io;
use libp2p::gossipsub::{PublishError, SubscriptionError};
#[cfg(not(target_arch = "wasm32"))]
use libp2p::noise;
use starknet::providers::ProviderError;
use thiserror::Error;

#[derive(Error, Debug)]
Expand Down Expand Up @@ -45,4 +46,7 @@ pub enum Error {

#[error("Invalid type provided: {0}")]
InvalidTypeError(String),

#[error(transparent)]
ProviderError(#[from] ProviderError),
}
93 changes: 61 additions & 32 deletions crates/torii/libp2p/src/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@
mod events;

use crate::server::events::ServerEvent;
use crate::typed_data::{parse_value_to_ty, PrimitiveType, TypedData};
use crate::types::Message;
use crate::typed_data::{encode_type, parse_value_to_ty, PrimitiveType, TypedData};
use crate::types::{Message, Signature};

pub(crate) const LOG_TARGET: &str = "torii::relay::server";

Expand Down Expand Up @@ -302,37 +302,15 @@
// to prevent replay attacks.

// Verify the signature
let message_hash =
if let Ok(message) = data.message.encode(entity_identity) {
message
} else {
info!(
target: LOG_TARGET,
"Encoding message."
);
continue;
};

let mut calldata = vec![message_hash];
calldata.push(Felt::from(data.signature.len()));

calldata.extend(data.signature);
if !match self
.provider
.call(
FunctionCall {
contract_address: entity_identity,
entry_point_selector: get_selector_from_name(
"is_valid_signature",
)
.unwrap(),
calldata,
},
BlockId::Tag(BlockTag::Pending),
)
.await
if !match validate_signature(
&self.provider,
entity_identity,
&data.message,
&data.signature,
)
.await
Comment on lines +305 to +311
Copy link
Collaborator

Choose a reason for hiding this comment

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

Since the function returns a bool, the construction of this and arms below may be much simpler:

if !validate_signature(...)? {
    error!(..);
    continue
}

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

this wouldn't work though since we don't want to propagate the error. we should just log it and not exit. since we're taking in user input

{
Ok(res) => res[0] != Felt::ZERO,
Ok(res) => res,
Larkooo marked this conversation as resolved.
Show resolved Hide resolved
Err(e) => {
warn!(
target: LOG_TARGET,
Expand Down Expand Up @@ -432,6 +410,57 @@
}
}

async fn validate_signature<P: Provider + Sync>(
provider: &P,
entity_identity: Felt,
message: &TypedData,
signature: &Signature,
) -> Result<bool, Error> {
let message_hash = message.encode(entity_identity)?;

match signature {
Signature::Account(signature) => {
let mut calldata = vec![message_hash, Felt::from(signature.len())];
calldata.extend(signature);
provider
.call(
FunctionCall {
contract_address: entity_identity,
entry_point_selector: get_selector_from_name("is_valid_signature").unwrap(),
calldata,
Larkooo marked this conversation as resolved.
Show resolved Hide resolved
},
BlockId::Tag(BlockTag::Pending),
)
.await
.map_err(Error::ProviderError)
.map(|res| res[0] != Felt::ZERO)
}
Signature::Session(signature) => {
let mut calldata = vec![
Felt::ONE,
get_selector_from_name(&encode_type(&message.primary_type, &message.types)?)
.map_err(|e| Error::InvalidMessageError(e.to_string()))?,
message_hash,
signature.len().into(),
];
calldata.extend(signature);
provider
.call(
FunctionCall {
contract_address: entity_identity,
entry_point_selector: get_selector_from_name("is_session_sigature_valid")
.unwrap(),
Larkooo marked this conversation as resolved.
Show resolved Hide resolved
calldata,
},
BlockId::Tag(BlockTag::Pending),
)
.await
.map_err(Error::ProviderError)
.map(|res| res[0] != Felt::ZERO)

Check warning on line 459 in crates/torii/libp2p/src/server/mod.rs

View check run for this annotation

Codecov / codecov/patch

crates/torii/libp2p/src/server/mod.rs#L438-L459

Added lines #L438 - L459 were not covered by tests
}
}
}
Larkooo marked this conversation as resolved.
Show resolved Hide resolved

fn ty_keys(ty: &Ty) -> Result<Vec<Felt>, Error> {
if let Ty::Struct(s) = &ty {
let mut keys = Vec::new();
Expand Down
7 changes: 5 additions & 2 deletions crates/torii/libp2p/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -545,7 +545,7 @@ mod test {

use crate::server::Relay;
use crate::typed_data::{Domain, Field, SimpleField, TypedData};
use crate::types::Message;
use crate::types::{Message, Signature};

let _ = tracing_subscriber::fmt()
.with_env_filter("torii::relay::client=debug,torii::relay::server=debug")
Expand Down Expand Up @@ -683,7 +683,10 @@ mod test {

client
.command_sender
.publish(Message { message: typed_data, signature: vec![signature.r, signature.s] })
.publish(Message {
message: typed_data,
signature: Signature::Account(vec![signature.r, signature.s]),
})
.await?;

sleep(std::time::Duration::from_secs(2)).await;
Expand Down
8 changes: 7 additions & 1 deletion crates/torii/libp2p/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,14 @@ use starknet::core::types::Felt;

use crate::typed_data::TypedData;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Signature {
Account(Vec<Felt>),
Session(Vec<Felt>),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Message {
pub message: TypedData,
pub signature: Vec<Felt>,
pub signature: Signature,
}
Loading