Skip to content

Commit

Permalink
fix: bump contract and permissioned integration (#87)
Browse files Browse the repository at this point in the history
Accompanying with babylonlabs-io/babylon#291

This PR

- bumps contract against the latest Babylon base branch
- fixes all failed tests due to the bump
- implements the consumer side logic of permissioned integration, mostly
removing auto consumer registration
  • Loading branch information
SebastianElvis authored Nov 28, 2024
1 parent 5fcde96 commit 16f6154
Show file tree
Hide file tree
Showing 67 changed files with 1,013 additions and 812 deletions.
6 changes: 3 additions & 3 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
[submodule "packages/proto/babylon"]
path = packages/proto/babylon
url = [email protected]:babylonlabs-io/babylon.git
branch = base/consumer-chain-support
path = packages/proto/babylon
url = [email protected]:babylonlabs-io/babylon.git
branch = base/consumer-chain-support
1 change: 1 addition & 0 deletions Cargo.lock

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

8 changes: 4 additions & 4 deletions contracts/babylon/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ pub enum BTCLightclientError {
#[error("The given headers during initialization cannot be verified")]
InitError {},
#[error("The given headers during initialization cannot be verified. Less than {0} headers")]
InitErrorLength(u64),
InitErrorLength(u32),
#[error("The bytes cannot be decoded")]
DecodeError(#[from] DecodeError),
#[error("{0}")]
Expand All @@ -85,15 +85,15 @@ pub enum BTCLightclientError {
#[error("The BTC header does not satisfy the difficulty requirement or is not consecutive")]
BTCHeaderError {},
#[error("The BTC header with height {height} is not found in the storage")]
BTCHeaderNotFoundError { height: u64 },
BTCHeaderNotFoundError { height: u32 },
#[error("The BTC height with hash {hash} is not found in the storage")]
BTCHeightNotFoundError { hash: String },
#[error("The BTC header info cumulative work encoding is wrong")]
BTCWrongCumulativeWorkEncoding {},
#[error("The BTC header info {0} cumulative work is wrong. Expected {1}, got {2}")]
BTCWrongCumulativeWork(usize, Work, Work),
#[error("The BTC header info {0} height is wrong. Expected {1}, got {2}")]
BTCWrongHeight(usize, u64, u64),
BTCWrongHeight(usize, u32, u32),
#[error("The new chain's work ({0}), is not better than the current chain's work ({1})")]
BTCChainWithNotEnoughWork(Work, Work),
}
Expand Down Expand Up @@ -122,7 +122,7 @@ pub enum BabylonEpochChainError {
#[error("The BTC header with hash {hash} is not found in the storage")]
BTCHeaderNotFoundError { hash: String },
#[error("The BTC headers are not {w}-deep")]
BTCHeaderNotDeepEnough { w: u64 },
BTCHeaderNotDeepEnough { w: u32 },
#[error("The checkpoint is not in the given BTC headers: {err_msg}")]
CheckpointNotSubmitted { err_msg: String },
#[error("The epoch is not sealed by the epoch's validator set: {err_msg}")]
Expand Down
108 changes: 5 additions & 103 deletions contracts/babylon/src/ibc.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use crate::error::ContractError;
use babylon_bindings::BabylonMsg;
use babylon_proto::babylon::zoneconcierge::v1::{
zoneconcierge_packet_data::Packet, BtcTimestamp, ConsumerRegisterIbcPacket,
ZoneconciergePacketData,
zoneconcierge_packet_data::Packet, BtcTimestamp, ZoneconciergePacketData,
};

use crate::state::config::CONFIG;
Expand Down Expand Up @@ -81,25 +80,9 @@ pub fn ibc_channel_connect(
.add_attribute("channel_id", chan_id)
.add_event(Event::new("ibc").add_attribute("channel", "connect"));

// If the consumer name and description are set, create and send a ConsumerRegister packet
// If the consumer name and description are set, emit an event
if let (Some(name), Some(description)) = (&cfg.consumer_name, &cfg.consumer_description) {
let consumer_register_packet = ConsumerRegisterIbcPacket {
consumer_name: name.clone(),
consumer_description: description.clone(),
};

let packet_data = ZoneconciergePacketData {
packet: Some(Packet::ConsumerRegister(consumer_register_packet)),
};

let ibc_msg = IbcMsg::SendPacket {
channel_id: channel.endpoint.channel_id.clone(),
data: Binary::new(packet_data.encode_to_vec()),
timeout: packet_timeout(&env),
};

response = response
.add_message(ibc_msg)
.add_attribute("consumer_name", name)
.add_attribute("consumer_description", description);
}
Expand Down Expand Up @@ -155,9 +138,6 @@ pub fn ibc_packet_receive(
Packet::BtcStaking(btc_staking) => {
ibc_packet::handle_btc_staking(deps, caller, &btc_staking)
}
Packet::ConsumerRegister(_) => Err(StdError::generic_err(
"ConsumerRegister packet should not be received",
)),
Packet::ConsumerSlashing(_) => Err(StdError::generic_err(
"ConsumerSlashing packet should not be received",
)),
Expand All @@ -177,12 +157,12 @@ pub fn ibc_packet_receive(
pub(crate) mod ibc_packet {
use super::*;
use crate::state::config::CONFIG;
use babylon_apis::btc_staking_api::SlashedBtcDelegation;
use babylon_apis::btc_staking_api::{
ActiveBtcDelegation, BtcUndelegationInfo, CovenantAdaptorSignatures,
FinalityProviderDescription, NewFinalityProvider, ProofOfPossessionBtc, SignatureInfo,
UnbondedBtcDelegation,
};
use babylon_apis::btc_staking_api::{DelegatorUnbondingInfo, SlashedBtcDelegation};
use babylon_apis::finality_api::Evidence;
use babylon_proto::babylon::btcstaking::v1::BtcStakingIbcPacket;
use babylon_proto::babylon::zoneconcierge::v1::zoneconcierge_packet_data::Packet::ConsumerSlashing;
Expand Down Expand Up @@ -237,90 +217,12 @@ pub(crate) mod ibc_packet {
new_fp: btc_staking
.new_fp
.iter()
.map(|fp| {
Ok(NewFinalityProvider {
description: fp
.description
.as_ref()
.map(|d| FinalityProviderDescription {
moniker: d.moniker.clone(),
identity: d.identity.clone(),
website: d.website.clone(),
security_contact: d.security_contact.clone(),
details: d.details.clone(),
}),
commission: Decimal::from_str(&fp.commission)?,
addr: fp.addr.clone(),
btc_pk_hex: fp.btc_pk_hex.clone(),
pop: fp.pop.as_ref().map(|pop| ProofOfPossessionBtc {
btc_sig_type: pop.btc_sig_type,
btc_sig: pop.btc_sig.to_vec().into(),
}),
consumer_id: fp.consumer_id.clone(),
})
})
.map(|fp| NewFinalityProvider::try_from(fp).map_err(StdError::generic_err))
.collect::<StdResult<_>>()?,
active_del: btc_staking
.active_del
.iter()
.map(|d| {
Ok(ActiveBtcDelegation {
staker_addr: d.staker_addr.clone(),
btc_pk_hex: d.btc_pk_hex.clone(),
fp_btc_pk_list: d.fp_btc_pk_list.clone(),
start_height: d.start_height,
end_height: d.end_height,
total_sat: d.total_sat,
staking_tx: d.staking_tx.to_vec().into(),
slashing_tx: d.slashing_tx.to_vec().into(),
delegator_slashing_sig: d.delegator_slashing_sig.to_vec().into(),
covenant_sigs: d
.covenant_sigs
.iter()
.map(|s| CovenantAdaptorSignatures {
cov_pk: s.cov_pk.to_vec().into(),
adaptor_sigs: s
.adaptor_sigs
.iter()
.map(|a| a.to_vec().into())
.collect(),
})
.collect(),
staking_output_idx: d.staking_output_idx,
unbonding_time: d.unbonding_time,
undelegation_info: d
.undelegation_info
.as_ref()
.map(|ui| BtcUndelegationInfo {
unbonding_tx: ui.unbonding_tx.to_vec().into(),
delegator_unbonding_sig: ui.delegator_unbonding_sig.to_vec().into(),
covenant_unbonding_sig_list: ui
.covenant_unbonding_sig_list
.iter()
.map(|s| SignatureInfo {
pk: s.pk.to_vec().into(),
sig: s.sig.to_vec().into(),
})
.collect(),
slashing_tx: ui.slashing_tx.to_vec().into(),
delegator_slashing_sig: ui.delegator_slashing_sig.to_vec().into(),
covenant_slashing_sigs: ui
.covenant_slashing_sigs
.iter()
.map(|s| CovenantAdaptorSignatures {
cov_pk: s.cov_pk.to_vec().into(),
adaptor_sigs: s
.adaptor_sigs
.iter()
.map(|a| a.to_vec().into())
.collect(),
})
.collect(),
})
.ok_or(StdError::generic_err("undelegation info not set"))?,
params_version: d.params_version,
})
})
.map(|d| ActiveBtcDelegation::try_from(d).map_err(StdError::generic_err))
.collect::<StdResult<_>>()?,
slashed_del: btc_staking
.slashed_del
Expand Down
4 changes: 2 additions & 2 deletions contracts/babylon/src/msg/btc_header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub struct BtcHeader {
impl BtcHeader {
pub fn to_btc_header_info(
&self,
prev_height: u64,
prev_height: u32,
prev_work: babylon_bitcoin::Work,
) -> Result<BtcHeaderInfo, BTCLightclientError> {
let block_header: BlockHeader = self.try_into()?;
Expand Down Expand Up @@ -173,7 +173,7 @@ pub struct BtcHeaderResponse {
/// Encoded as a (byte-reversed) hex string.
pub hash: String,
/// The height of the block in the BTC blockchain.
pub height: u64,
pub height: u32,
/// The cumulative total work of this block and all of its ancestors.
pub cum_work: cosmwasm_std::Uint256,
}
Expand Down
8 changes: 4 additions & 4 deletions contracts/babylon/src/msg/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ pub struct InstantiateMsg {
/// babylon_tag is a string encoding four bytes used for identification / tagging of the Babylon zone.
/// NOTE: this is a hex string, not raw bytes
pub babylon_tag: String,
pub btc_confirmation_depth: u64,
pub checkpoint_finalization_timeout: u64,
pub btc_confirmation_depth: u32,
pub checkpoint_finalization_timeout: u32,
/// notify_cosmos_zone indicates whether to send Cosmos zone messages notifying BTC-finalised
/// headers.
/// NOTE: If set to true, then the Cosmos zone needs to integrate the corresponding message handler
Expand Down Expand Up @@ -124,7 +124,7 @@ pub enum QueryMsg {
BtcTipHeader {},
/// BtcHeader returns the BTC header information stored in the contract, by BTC height.
#[returns(BtcHeaderResponse)]
BtcHeader { height: u64 },
BtcHeader { height: u32 },
/// BtcHeaderByHash returns the BTC header information stored in the contract, by BTC hash.
///
/// `hash` is the (byte-reversed) hex-encoded hash of the BTC header
Expand All @@ -135,7 +135,7 @@ pub enum QueryMsg {
/// `start_after` is the height of the header to start after, or `None` to start from the base
#[returns(BtcHeadersResponse)]
BtcHeaders {
start_after: Option<u64>,
start_after: Option<u32>,
limit: Option<u32>,
reverse: Option<bool>,
},
Expand Down
10 changes: 5 additions & 5 deletions contracts/babylon/src/msg/cz_header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ use hex::ToHex;
/// Adapted from `IndexedHeader`.
#[cw_serde]
pub struct CzHeaderResponse {
/// chain_id is the unique ID of the chain
pub chain_id: String,
/// consumer_id is the unique ID of the consumer
pub consumer_id: String,
/// hash is the hash of this header.
/// Hex-encoded string of 32 bytes
pub hash: String,
Expand Down Expand Up @@ -43,7 +43,7 @@ pub struct CzHeaderResponse {
impl From<&IndexedHeader> for CzHeaderResponse {
fn from(header: &IndexedHeader) -> Self {
CzHeaderResponse {
chain_id: header.chain_id.clone(),
consumer_id: header.consumer_id.clone(),
hash: header.hash.encode_hex(),
height: header.height,
time: header
Expand Down Expand Up @@ -72,7 +72,7 @@ mod tests {
#[test]
fn indexed_header_to_indexed_header_response_works() {
let indexed_header = IndexedHeader {
chain_id: "chain_id".to_string(),
consumer_id: "consumer_id".to_string(),
hash: prost::bytes::Bytes::from("hash"),
height: 1,
time: Some(::pbjson_types::Timestamp {
Expand All @@ -87,7 +87,7 @@ mod tests {

let indexed_header_response = CzHeaderResponse::from(&indexed_header);

assert_eq!(indexed_header_response.chain_id, "chain_id");
assert_eq!(indexed_header_response.consumer_id, "consumer_id");
assert_eq!(indexed_header_response.hash, hex::encode("hash"));
assert_eq!(indexed_header_response.height, 1);
assert_eq!(
Expand Down
4 changes: 2 additions & 2 deletions contracts/babylon/src/queries/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ pub fn btc_tip_header(_deps: Deps) -> Result<BtcHeaderResponse, BTCLightclientEr
BtcHeaderResponse::try_from(&btc_header_info)
}

pub fn btc_header(deps: Deps, height: u64) -> Result<BtcHeaderResponse, BTCLightclientError> {
pub fn btc_header(deps: Deps, height: u32) -> Result<BtcHeaderResponse, BTCLightclientError> {
let btc_header_info = get_header(deps.storage, height)?;
BtcHeaderResponse::try_from(&btc_header_info)
}
Expand All @@ -44,7 +44,7 @@ pub fn btc_header_by_hash(

pub fn btc_headers(
deps: Deps,
start_after: Option<u64>,
start_after: Option<u32>,
limit: Option<u32>,
reverse: Option<bool>,
) -> Result<BtcHeadersResponse, BTCLightclientError> {
Expand Down
2 changes: 1 addition & 1 deletion contracts/babylon/src/state/babylon_epoch_chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ fn verify_epoch_and_checkpoint(
.map_err(|_| BabylonEpochChainError::BTCHeaderDecodeError {})?;

// this will be used for checking w-deep later
let mut min_height: u64 = u64::MAX;
let mut min_height: u32 = u32::MAX;

// ensure the given btc headers are in BTC light clients
for btc_header in btc_headers.iter() {
Expand Down
Loading

0 comments on commit 16f6154

Please sign in to comment.