Skip to content

Commit

Permalink
feat(lc/starknet): verify signed commitment proofs from starknet (#242)
Browse files Browse the repository at this point in the history
* update ibc-client-cw patch branch

* fix cw context methods

* impl cw client state execution for starknet

* add membership proof signer

* sign connection open try message

* ignore client and consensus proof

* open ack proof

* todo comment

* generate membership proof message at starknet payload

* membership proof msg for channel end

* membership proof msg for packet commitment

* membership proof msg for packet ack

* membership proof msg for packet receipt

* rename field in StarknetCommitmentProof

* rm redundant todos

* sign self client and consensus state proofs

* use chain_status height as proof height

* add tiny-bip39 dep

* proof_signer components

* add proof_signer field to StarknetChain

* generate secp256k1 keypair from felt signing key

* sign with starknet proof signer

* nits

* rm redundant endpoint

* use packet_receipt endpoint

* ibc-go compatible packet commitment

* test consistent packet commitment in cairo and rust

* happy clippy

* rm test steps with dummy proofs

* cargo fmt

* cargo clippy

* update expected commitment hash after fix
  • Loading branch information
rnbguy authored Feb 5, 2025
1 parent 51c9b8d commit 7025c5a
Show file tree
Hide file tree
Showing 42 changed files with 547 additions and 225 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -174,15 +174,6 @@ pub mod ChannelHandlerComponent {
self.read_packet_ack(@port_id, @channel_id, @sequence)
}

fn is_packet_received(
self: @ComponentState<TContractState>,
port_id: PortId,
channel_id: ChannelId,
sequence: Sequence
) -> bool {
self.packet_ack_exists(@port_id, @channel_id, @sequence)
}

fn unreceived_packet_sequences(
self: @ComponentState<TContractState>,
port_id: PortId,
Expand Down
3 changes: 0 additions & 3 deletions cairo-contracts/packages/core/src/channel/interface.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,6 @@ pub trait IChannelQuery<TContractState> {
fn packet_acknowledgement(
self: @TContractState, port_id: PortId, channel_id: ChannelId, sequence: Sequence
) -> Commitment;
fn is_packet_received(
self: @TContractState, port_id: PortId, channel_id: ChannelId, sequence: Sequence
) -> bool;
fn unreceived_packet_sequences(
self: @TContractState, port_id: PortId, channel_id: ChannelId, sequences: Array<Sequence>
) -> Array<Sequence>;
Expand Down
4 changes: 3 additions & 1 deletion cairo-contracts/packages/core/src/commitment/types.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,9 @@ pub fn compute_packet_commitment(
json_packet_data: @ByteArray, timeout_height: Height, timeout_timestamp: Timestamp
) -> Commitment {
let mut coll = U32CollectorImpl::init();
coll.extend(timeout_timestamp);
// ibc-go uses nanosecs
// https://github.com/cosmos/ibc-go/blob/98d7e7550a23ecf8d96ce042ab11ef857b184f2a/proto/ibc/core/channel/v1/channel.proto#L179-L180
coll.extend(timeout_timestamp.timestamp * 1_000_000_000);
coll.extend(timeout_height);
coll.extend_from_chunk(compute_sha256_byte_array(json_packet_data));
compute_sha256_u32_array(coll.value(), 0, 0).into()
Expand Down
2 changes: 1 addition & 1 deletion cairo-contracts/packages/core/src/tests/commitment.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ fn test_array_u8_into_array_u32() {
fn test_compute_packet_commitment() {
let commitment = PACKET_COMMITMENT_ON_SN(ERC20());
let expected: [u32; 8] = [
3458244073, 1576048754, 4210798310, 1002247062, 2365181318, 2763927782, 545147151, 944653547
1561496803, 591083406, 1958596266, 2480824962, 846563094, 2634790765, 145282158, 2139799705
];
assert_eq!(commitment, expected.into());
}
Expand Down
3 changes: 2 additions & 1 deletion light-client/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion light-client/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ ibc-client-starknet = { path = "./ibc-client-starknet" }
ibc-client-starknet-cw = { path = "./ibc-client-starknet-cw" }
ibc-client-starknet-types = { path = "./ibc-client-starknet-types" }

ibc-client-cw = { git = "https://github.com/informalsystems/cosmwasm-ibc.git", branch = "luca_joss/add-cw-client-extension-trait" }
ibc-client-cw = { git = "https://github.com/informalsystems/cosmwasm-ibc.git", branch = "starknet/demo2" }

ibc = { git = "https://github.com/cosmos/ibc-rs", branch = "main" }
ibc-core = { git = "https://github.com/cosmos/ibc-rs", branch = "main" }
Expand Down
14 changes: 14 additions & 0 deletions light-client/ibc-client-starknet/src/client_state/cw.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
use ibc_client_cw::api::CwClientStateExecution;
use ibc_client_cw::context::client_ctx::CwClientExecution;

use super::ClientState;
use crate::ConsensusState;

impl<'a, E> CwClientStateExecution<'a, E> for ClientState
where
E: CwClientExecution<'a, ClientStateMut = ClientState, ConsensusStateRef = ConsensusState>,
{
fn public_key(&self) -> Option<Vec<u8>> {
Some(self.0.pub_key.clone())
}
}
10 changes: 4 additions & 6 deletions light-client/ibc-client-starknet/src/client_state/execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,11 @@ where

let raw_header = signed_header.header;

let header_digest = ctx.generate_sha256_digest(&raw_header);
let header_digest = ctx.checksum(&raw_header);

let deps = ctx
.cosmwasm_execute_context()
.ok_or_else(|| ClientError::ClientSpecific {
description: "missing Deps from context".to_owned(),
})?;
let deps = ctx.deps_mut().ok_or_else(|| ClientError::ClientSpecific {
description: "missing Deps from context".to_owned(),
})?;

match deps.api.secp256k1_verify(
header_digest.as_slice(),
Expand Down
1 change: 1 addition & 0 deletions light-client/ibc-client-starknet/src/client_state/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
pub mod common;
pub mod cw;
pub mod execution;
pub mod validation;

Expand Down
2 changes: 1 addition & 1 deletion nix/ibc-starknet-cw.nix
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ let
outputHashes = {
"hermes-cosmos-encoding-components-0.1.0" = "sha256-uxXpzxVc89DkAC4VqC/Au3cpBzUbxiSS2KiFKZ+rqdg=";
"cgp-0.3.1" = "sha256-AOQ+WVQWPlF2ZfYYc5Eq3t7XAljd5P2qExWLYZWNnd8=";
"ibc-client-cw-0.56.0" = "sha256-EkLxuJfr3vf0busmSZD7DwOS9GfgfhT+sdopi1nNiCs=";
"ibc-client-cw-0.56.0" = "sha256-DA3AB8ejUrx4ksBtN/vaOznjpKE0+0F6vGA7JmWyHWA=";
"ibc-0.56.0" = "sha256-7DPIqu/zs0szjmtJTfXI2eQ0HEkRyvGjArcMZsFWMT4=";
};
};
Expand Down
2 changes: 2 additions & 0 deletions relayer/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions relayer/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ tracing-subscriber = { version = "0.3.18" }
flate2 = { version = "1.0" }
http = { version = "1.0.0" }
futures = { version = "0.3.30", default-features = false }
tiny-bip39 = { version = "1.0.0" }

ibc = { version = "0.56.0" }
ibc-proto = { version = "0.51.1" }
Expand Down
1 change: 1 addition & 0 deletions relayer/crates/starknet-chain-components/src/impls/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ pub mod messages;
pub mod packet_fields;
pub mod packet_filter;
pub mod payload_builders;
pub mod proof_signer;
pub mod provider;
pub mod queries;
pub mod send_message;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use cgp::prelude::CanRaiseAsyncError;
use hermes_chain_components::traits::types::chain_id::HasChainId;
use hermes_cosmos_chain_components::types::key_types::secp256k1::Secp256k1KeyPair;
use hermes_relayer_components::chain::traits::payload_builders::create_client::CreateClientPayloadBuilder;
use hermes_relayer_components::chain::traits::queries::chain_status::CanQueryChainStatus;
use hermes_relayer_components::chain::traits::types::create_client::{
Expand All @@ -10,6 +11,7 @@ use ibc::core::client::types::Height;
use ibc::core::host::types::identifiers::ChainId;
use ibc::primitives::Timestamp;

use crate::traits::proof_signer::HasStarknetProofSigner;
use crate::types::consensus_state::{StarknetConsensusState, WasmStarknetConsensusState};
use crate::types::payloads::client::{
StarknetCreateClientPayload, StarknetCreateClientPayloadOptions,
Expand All @@ -27,6 +29,7 @@ where
> + HasCreateClientPayloadType<Counterparty, CreateClientPayload = StarknetCreateClientPayload>
+ CanQueryChainStatus<ChainStatus = StarknetChainStatus>
+ HasChainId<ChainId = ChainId>
+ HasStarknetProofSigner<ProofSigner = Secp256k1KeyPair>
+ CanRaiseAsyncError<&'static str>
+ CanRaiseAsyncError<ClientError>,
{
Expand All @@ -53,6 +56,7 @@ where
chain_id: chain.chain_id().clone(),
client_state_wasm_code_hash: create_client_options.wasm_code_hash.into(),
consensus_state,
proof_signer_pub_key: chain.proof_signer().public_key.serialize().to_vec(),
})
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
use cgp::prelude::CanRaiseAsyncError;
use cgp::prelude::{Async, CanRaiseAsyncError};
use hermes_cosmos_chain_components::types::key_types::secp256k1::Secp256k1KeyPair;
use hermes_encoding_components::traits::encode::CanEncode;
use hermes_encoding_components::traits::has_encoding::HasDefaultEncoding;
use hermes_encoding_components::types::AsBytes;
use hermes_protobuf_encoding_components::types::strategy::ViaProtobuf;
use hermes_relayer_components::chain::traits::payload_builders::update_client::UpdateClientPayloadBuilder;
use hermes_relayer_components::chain::traits::queries::chain_status::CanQueryChainStatus;
use hermes_relayer_components::chain::traits::types::client_state::HasClientStateType;
Expand All @@ -10,14 +15,15 @@ use ibc_client_starknet_types::header::StarknetHeader;
use starknet::core::types::{BlockId, MaybePendingBlockWithTxHashes};
use starknet::providers::{Provider, ProviderError};

use crate::traits::proof_signer::HasStarknetProofSigner;
use crate::traits::provider::HasStarknetProvider;
use crate::types::consensus_state::StarknetConsensusState;
use crate::types::payloads::client::StarknetUpdateClientPayload;
use crate::types::status::StarknetChainStatus;

pub struct BuildStarknetUpdateClientPayload;

impl<Chain, Counterparty> UpdateClientPayloadBuilder<Chain, Counterparty>
impl<Chain, Counterparty, Encoding> UpdateClientPayloadBuilder<Chain, Counterparty>
for BuildStarknetUpdateClientPayload
where
Chain: HasHeightType<Height = u64>
Expand All @@ -26,7 +32,12 @@ where
+ CanQueryChainStatus<ChainStatus = StarknetChainStatus>
+ HasStarknetProvider
+ CanRaiseAsyncError<&'static str>
+ CanRaiseAsyncError<ProviderError>,
+ HasDefaultEncoding<AsBytes, Encoding = Encoding>
+ HasStarknetProofSigner<ProofSigner = Secp256k1KeyPair>
+ CanRaiseAsyncError<String>
+ CanRaiseAsyncError<ProviderError>
+ CanRaiseAsyncError<Encoding::Error>,
Encoding: Async + CanEncode<ViaProtobuf, StarknetHeader, Encoded = Vec<u8>>,
{
async fn build_update_client_payload(
chain: &Chain,
Expand Down Expand Up @@ -63,6 +74,15 @@ where
consensus_state,
};

Ok(StarknetUpdateClientPayload { header })
let encoded_header = Chain::default_encoding()
.encode(&header)
.map_err(Chain::raise_error)?;

let signature = chain
.proof_signer()
.sign(&encoded_header)
.map_err(Chain::raise_error)?;

Ok(StarknetUpdateClientPayload { header, signature })
}
}
28 changes: 28 additions & 0 deletions relayer/crates/starknet-chain-components/src/impls/proof_signer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
use core::marker::PhantomData;

use cgp::prelude::*;

use crate::traits::proof_signer::{
HasStarknetProofSignerType, ProvideStarknetProofSignerType, StarknetProofSignerGetter,
};

pub struct GetStarknetProofSignerField<Tag>(pub PhantomData<Tag>);

impl<Chain, Tag> ProvideStarknetProofSignerType<Chain> for GetStarknetProofSignerField<Tag>
where
Chain: Async + HasField<Tag>,
Tag: Async,
Chain::Value: Async,
{
type ProofSigner = Chain::Value;
}

impl<Chain, Tag> StarknetProofSignerGetter<Chain> for GetStarknetProofSignerField<Tag>
where
Chain: Async + HasStarknetProofSignerType + HasField<Tag, Value = Chain::ProofSigner>,
Tag: Async,
{
fn proof_signer(chain: &Chain) -> &Chain::ProofSigner {
chain.get_field(PhantomData)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,36 +3,45 @@ use core::marker::PhantomData;
use cgp::prelude::*;
use hermes_cairo_encoding_components::strategy::ViaCairo;
use hermes_cairo_encoding_components::types::as_felt::AsFelt;
use hermes_chain_components::traits::commitment_prefix::HasIbcCommitmentPrefix;
use hermes_chain_components::traits::queries::chain_status::CanQueryChainStatus;
use hermes_chain_components::traits::queries::packet_acknowledgement::PacketAcknowledgementQuerier;
use hermes_chain_components::traits::types::height::HasHeightType;
use hermes_chain_components::traits::types::ibc::{
HasChannelIdType, HasPortIdType, HasSequenceType,
};
use hermes_chain_components::traits::types::packets::ack::HasAcknowledgementType;
use hermes_chain_components::traits::types::proof::HasCommitmentProofType;
use hermes_cosmos_chain_components::types::key_types::secp256k1::Secp256k1KeyPair;
use hermes_encoding_components::traits::decode::CanDecode;
use hermes_encoding_components::traits::encode::CanEncode;
use hermes_encoding_components::traits::has_encoding::HasEncoding;
use hermes_encoding_components::traits::types::encoded::HasEncodedType;
use ibc::core::host::types::identifiers::{PortId as IbcPortId, Sequence as IbcSequence};
use ibc::core::host::types::path::{AckPath, Path};
use starknet::core::types::Felt;
use starknet::macros::selector;

use crate::traits::contract::call::CanCallContract;
use crate::traits::proof_signer::HasStarknetProofSigner;
use crate::traits::queries::address::CanQueryContractAddress;
use crate::traits::types::blob::HasBlobType;
use crate::traits::types::method::HasSelectorType;
use crate::types::channel_id::ChannelId;
use crate::types::commitment_proof::StarknetCommitmentProof;
use crate::types::membership_proof_signer::MembershipVerifierContainer;
use crate::types::messages::ibc::channel::PortId as CairoPortId;
use crate::types::messages::ibc::packet::Sequence;
use crate::types::status::StarknetChainStatus;

pub struct QueryStarknetAckCommitment;

impl<Chain, Counterparty, Encoding> PacketAcknowledgementQuerier<Chain, Counterparty>
for QueryStarknetAckCommitment
where
Chain: HasHeightType<Height = u64>
+ CanQueryChainStatus<ChainStatus = StarknetChainStatus>
+ HasIbcCommitmentPrefix<CommitmentPrefix = Vec<u8>>
+ HasChannelIdType<Counterparty, ChannelId = ChannelId>
+ HasPortIdType<Counterparty, PortId = IbcPortId>
+ HasAcknowledgementType<Counterparty, Acknowledgement = Vec<u8>>
Expand All @@ -42,6 +51,8 @@ where
+ CanQueryContractAddress<symbol!("ibc_core_contract_address")>
+ HasEncoding<AsFelt, Encoding = Encoding>
+ CanCallContract
+ HasStarknetProofSigner<ProofSigner = Secp256k1KeyPair>
+ CanRaiseAsyncError<String>
+ CanRaiseAsyncError<Encoding::Error>,
Counterparty: HasSequenceType<Chain, Sequence = IbcSequence>,

Expand All @@ -54,7 +65,7 @@ where
channel_id: &ChannelId,
port_id: &IbcPortId,
sequence: &IbcSequence,
height: &u64,
_height: &u64,
) -> Result<(Vec<u8>, StarknetCommitmentProof), Chain::Error> {
let encoding = chain.encoding();

Expand All @@ -80,12 +91,6 @@ where
)
.await?;

// TODO(rano): how to get the proof?
let dummy_proof = StarknetCommitmentProof {
proof_height: *height,
proof_bytes: vec![0x1],
};

let product![ack,] = encoding.decode(&output).map_err(Chain::raise_error)?;

let ack_bytes = ack
Expand All @@ -94,6 +99,29 @@ where
.flat_map(|felt| felt.to_be_bytes())
.collect::<Vec<_>>();

let chain_status = chain.query_chain_status().await?;

let unsigned_membership_proof_bytes = MembershipVerifierContainer {
state_root: chain_status.block_hash.to_bytes_be().to_vec(),
prefix: chain.ibc_commitment_prefix().clone(),
path: Path::Ack(AckPath::new(port_id, channel_id, *sequence))
.to_string()
.into(),
value: Some(ack_bytes.clone()),
}
.canonical_bytes();

let signed_bytes = chain
.proof_signer()
.sign(&unsigned_membership_proof_bytes)
.map_err(Chain::raise_error)?;

// TODO(rano): how to get the proof?
let dummy_proof = StarknetCommitmentProof {
proof_height: chain_status.height,
proof_bytes: signed_bytes,
};

Ok((ack_bytes, dummy_proof))
}
}
Loading

0 comments on commit 7025c5a

Please sign in to comment.