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(lc/starknet): verify signed commitment proofs from starknet #242

Merged
merged 33 commits into from
Feb 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
a5f39fd
update ibc-client-cw patch branch
rnbguy Jan 28, 2025
01290a9
fix cw context methods
rnbguy Jan 28, 2025
e3080cf
impl cw client state execution for starknet
rnbguy Jan 28, 2025
de53ed2
add membership proof signer
rnbguy Jan 31, 2025
07e36a1
sign connection open try message
rnbguy Jan 31, 2025
59ec68f
ignore client and consensus proof
rnbguy Jan 31, 2025
d71ba5d
open ack proof
rnbguy Jan 31, 2025
776aa81
todo comment
rnbguy Jan 31, 2025
311be49
generate membership proof message at starknet payload
rnbguy Jan 31, 2025
4c465ac
membership proof msg for channel end
rnbguy Jan 31, 2025
cbaf6be
membership proof msg for packet commitment
rnbguy Jan 31, 2025
02d4d6b
membership proof msg for packet ack
rnbguy Jan 31, 2025
7722d4d
membership proof msg for packet receipt
rnbguy Jan 31, 2025
cb4fa8d
rename field in StarknetCommitmentProof
rnbguy Feb 1, 2025
c14166f
rm redundant todos
rnbguy Feb 1, 2025
426a861
sign self client and consensus state proofs
rnbguy Feb 3, 2025
fd25041
use chain_status height as proof height
rnbguy Feb 3, 2025
043f2a1
add tiny-bip39 dep
rnbguy Feb 4, 2025
e233c3e
proof_signer components
rnbguy Feb 4, 2025
56b8427
add proof_signer field to StarknetChain
rnbguy Feb 4, 2025
0ad7614
generate secp256k1 keypair from felt signing key
rnbguy Feb 4, 2025
da71d3c
sign with starknet proof signer
rnbguy Feb 4, 2025
c6ba01e
Merge branch 'main' into rano/starknet-to-cosmos-commitment-proofs
rnbguy Feb 4, 2025
becea65
nits
rnbguy Feb 4, 2025
7644902
rm redundant endpoint
rnbguy Feb 4, 2025
46931e2
use packet_receipt endpoint
rnbguy Feb 4, 2025
e1e9c15
ibc-go compatible packet commitment
rnbguy Feb 4, 2025
aa5bc01
test consistent packet commitment in cairo and rust
rnbguy Feb 4, 2025
8f5ce48
happy clippy
rnbguy Feb 4, 2025
1db25f1
rm test steps with dummy proofs
rnbguy Feb 4, 2025
205756e
cargo fmt
rnbguy Feb 4, 2025
b84c5c4
cargo clippy
rnbguy Feb 4, 2025
b8f240b
update expected commitment hash after fix
rnbguy Feb 4, 2025
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
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);
Comment on lines +55 to +57
Copy link
Member Author

Choose a reason for hiding this comment

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

I fixed this as part of this PR.

cc @Farhad-Shabani

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
Loading