Skip to content

Commit

Permalink
fix(torii): offchain messages signature validation on first set (#2390)
Browse files Browse the repository at this point in the history
* Add verification of signature for on-chain message on first set of entity

* Address PR comments
  • Loading branch information
edisontim authored Sep 6, 2024
1 parent 72002a2 commit dd4cd5f
Showing 1 changed file with 40 additions and 38 deletions.
78 changes: 40 additions & 38 deletions crates/torii/libp2p/src/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,44 +267,29 @@ impl<P: Provider + Sync> Relay<P> {
}
};

if entity_identity.is_none() {
// we can set the entity without checking identity
if let Err(e) = self
.db
.set_entity(
ty,
&message_id.to_string(),
Utc::now().timestamp() as u64,
)
.await
{
info!(
target: LOG_TARGET,
error = %e,
"Setting message."
);
continue;
} else {
info!(
target: LOG_TARGET,
message_id = %message_id,
peer_id = %peer_id,
"Message set."
);
continue;
}
}

let entity_identity = match Felt::from_str(&entity_identity.unwrap()) {
Ok(identity) => identity,
Err(e) => {
warn!(
target: LOG_TARGET,
error = %e,
"Parsing identity."
);
continue;
}
let entity_identity = match entity_identity {
Some(identity) => match Felt::from_str(&identity) {
Ok(identity) => identity,
Err(e) => {
warn!(
target: LOG_TARGET,
error = %e,
"Parsing identity."
);
continue;
}
},
None => match get_identity_from_ty(&ty) {
Ok(identity) => identity,
Err(e) => {
warn!(
target: LOG_TARGET,
error = %e,
"Getting identity from message."
);
continue;
}
},
};

// TODO: have a nonce in model to check
Expand All @@ -324,6 +309,8 @@ impl<P: Provider + Sync> Relay<P> {
};

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

calldata.extend(data.signature);
if !match self
.provider
Expand Down Expand Up @@ -505,6 +492,21 @@ fn read_or_create_certificate(path: &Path) -> anyhow::Result<Certificate> {
Ok(cert)
}

fn get_identity_from_ty(ty: &Ty) -> Result<Felt, Error> {
let identity = ty
.as_struct()
.ok_or_else(|| Error::InvalidMessageError("Message is not a struct".to_string()))?
.get("identity")
.ok_or_else(|| Error::InvalidMessageError("No field identity".to_string()))?
.as_primitive()
.ok_or_else(|| Error::InvalidMessageError("Identity is not a primitive".to_string()))?
.as_contract_address()
.ok_or_else(|| {
Error::InvalidMessageError("Identity is not a contract address".to_string())
})?;
Ok(identity)
}

#[cfg(test)]
mod tests {
use tempfile::tempdir;
Expand Down

0 comments on commit dd4cd5f

Please sign in to comment.