1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
//! Defines identifier types
pub(crate) mod validate;
use validate::*;
use core::fmt::{Debug, Display, Error as FmtError, Formatter};
use core::str::FromStr;
use derive_more::Into;
use displaydoc::Display;
use crate::clients::ics07_tendermint::client_type as tm_client_type;
use crate::core::ics02_client::client_type::ClientType;
use crate::prelude::*;
const CONNECTION_ID_PREFIX: &str = "connection";
const CHANNEL_ID_PREFIX: &str = "channel";
const DEFAULT_PORT_ID: &str = "defaultPort";
const TRANSFER_PORT_ID: &str = "transfer";
/// Defines the domain type for chain identifiers.
///
/// A valid `ChainId` follows the format {chain name}-{revision number} where
/// the revision number indicates how many times the chain has been upgraded.
/// Creating `ChainId`s not in this format will result in an error.
///
/// It should be noted this format is not standardized yet, though it is widely
/// accepted and compatible with Cosmos SDK driven chains.
#[cfg_attr(
feature = "parity-scale-codec",
derive(
parity_scale_codec::Encode,
parity_scale_codec::Decode,
scale_info::TypeInfo
)
)]
#[cfg_attr(
feature = "borsh",
derive(borsh::BorshSerialize, borsh::BorshDeserialize)
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ChainId {
id: String,
revision_number: u64,
}
impl ChainId {
/// Creates a new `ChainId` with the given chain name and revision number.
///
/// It checks the chain name for valid characters according to `ICS-24`
/// specification and returns a `ChainId` in the the format of {chain
/// name}-{revision number}. Stricter checks beyond `ICS-24` rests with
/// the users, based on their requirements.
///
/// ```
/// use ibc::core::ics24_host::identifier::ChainId;
///
/// let revision_number = 10;
/// let id = ChainId::new("chainA", revision_number).unwrap();
/// assert_eq!(id.revision_number(), revision_number);
/// ```
pub fn new(name: &str, revision_number: u64) -> Result<Self, IdentifierError> {
let prefix = name.trim();
validate_identifier_chars(prefix)?;
validate_identifier_length(prefix, 1, 43)?;
let id = format!("{prefix}-{revision_number}");
Ok(Self {
id,
revision_number,
})
}
/// Get a reference to the underlying string.
pub fn as_str(&self) -> &str {
&self.id
}
pub fn split_chain_id(&self) -> (&str, u64) {
parse_chain_id_string(self.as_str())
.expect("never fails because a valid chain identifier is parsed")
}
/// Extract the chain name from the chain identifier
pub fn chain_name(&self) -> &str {
self.split_chain_id().0
}
/// Extract the revision number from the chain identifier
pub fn revision_number(&self) -> u64 {
self.revision_number
}
/// Swaps `ChainId`s revision number with the new specified revision number
/// ```
/// use ibc::core::ics24_host::identifier::ChainId;
/// let mut chain_id = ChainId::new("chainA", 1).unwrap();
/// chain_id.set_revision_number(2);
/// assert_eq!(chain_id.revision_number(), 2);
/// ```
pub fn set_revision_number(&mut self, revision_number: u64) {
let chain_name = self.chain_name();
self.id = format!("{}-{}", chain_name, revision_number);
self.revision_number = revision_number;
}
/// A convenient method to check if the `ChainId` forms a valid identifier
/// with the desired min/max length. However, ICS-24 does not specify a
/// certain min or max lengths for chain identifiers.
pub fn validate_length(
&self,
min_length: usize,
max_length: usize,
) -> Result<(), IdentifierError> {
validate_prefix_length(self.chain_name(), min_length, max_length)
}
}
/// Construct a `ChainId` from a string literal only if it forms a valid
/// identifier.
impl FromStr for ChainId {
type Err = IdentifierError;
fn from_str(id: &str) -> Result<Self, Self::Err> {
let (_, revision_number) = parse_chain_id_string(id)?;
Ok(Self {
id: id.to_string(),
revision_number,
})
}
}
impl Display for ChainId {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
write!(f, "{}", self.id)
}
}
/// Parses a string intended to represent a `ChainId` and, if successful,
/// returns a tuple containing the chain name and revision number.
fn parse_chain_id_string(chain_id_str: &str) -> Result<(&str, u64), IdentifierError> {
let (name, rev_number_str) = match chain_id_str.rsplit_once('-') {
Some((name, rev_number_str)) => (name, rev_number_str),
None => {
return Err(IdentifierError::InvalidCharacter {
id: chain_id_str.to_string(),
})
}
};
// Validates the chain name for allowed characters according to ICS-24.
validate_identifier_chars(name)?;
// Validates the revision number not to start with leading zeros, like "01".
if rev_number_str.as_bytes().first() == Some(&b'0') && rev_number_str.len() > 1 {
return Err(IdentifierError::InvalidCharacter {
id: chain_id_str.to_string(),
});
}
// Parses the revision number string into a `u64` and checks its validity.
let revision_number =
rev_number_str
.parse()
.map_err(|_| IdentifierError::InvalidCharacter {
id: chain_id_str.to_string(),
})?;
Ok((name, revision_number))
}
#[cfg_attr(
feature = "parity-scale-codec",
derive(
parity_scale_codec::Encode,
parity_scale_codec::Decode,
scale_info::TypeInfo
)
)]
#[cfg_attr(
feature = "borsh",
derive(borsh::BorshSerialize, borsh::BorshDeserialize)
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Into)]
pub struct ClientId(String);
impl ClientId {
/// Builds a new client identifier. Client identifiers are deterministically formed from two
/// elements: a prefix derived from the client type `ctype`, and a monotonically increasing
/// `counter`; these are separated by a dash "-".
///
/// ```
/// # use ibc::core::ics24_host::identifier::ClientId;
/// # use ibc::core::ics02_client::client_type::ClientType;
/// # use std::str::FromStr;
/// let tm_client_id = ClientId::new(ClientType::from_str("07-tendermint").unwrap(), 0);
/// assert!(tm_client_id.is_ok());
/// tm_client_id.map(|id| { assert_eq!(&id, "07-tendermint-0") });
/// ```
pub fn new(client_type: ClientType, counter: u64) -> Result<Self, IdentifierError> {
let prefix = client_type.as_str().trim();
validate_client_type(prefix)?;
let id = format!("{prefix}-{counter}");
Self::from_str(id.as_str())
}
/// Get this identifier as a borrowed `&str`
pub fn as_str(&self) -> &str {
&self.0
}
/// Get this identifier as a borrowed byte slice
pub fn as_bytes(&self) -> &[u8] {
self.0.as_bytes()
}
}
/// This implementation provides a `to_string` method.
impl Display for ClientId {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
write!(f, "{}", self.0)
}
}
impl FromStr for ClientId {
type Err = IdentifierError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
validate_client_identifier(s).map(|_| Self(s.to_string()))
}
}
impl Default for ClientId {
fn default() -> Self {
Self::new(tm_client_type(), 0).expect("Never fails because we use a valid client type")
}
}
/// Equality check against string literal (satisfies &ClientId == &str).
/// ```
/// use core::str::FromStr;
/// use ibc::core::ics24_host::identifier::ClientId;
/// let client_id = ClientId::from_str("clientidtwo");
/// assert!(client_id.is_ok());
/// client_id.map(|id| {assert_eq!(&id, "clientidtwo")});
/// ```
impl PartialEq<str> for ClientId {
fn eq(&self, other: &str) -> bool {
self.as_str().eq(other)
}
}
#[cfg_attr(
feature = "parity-scale-codec",
derive(
parity_scale_codec::Encode,
parity_scale_codec::Decode,
scale_info::TypeInfo
)
)]
#[cfg_attr(
feature = "borsh",
derive(borsh::BorshSerialize, borsh::BorshDeserialize)
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ConnectionId(String);
impl ConnectionId {
/// Builds a new connection identifier. Connection identifiers are deterministically formed from
/// two elements: a prefix `prefix`, and a monotonically increasing `counter`; these are
/// separated by a dash "-". The prefix is currently determined statically (see
/// `ConnectionId::prefix()`) so this method accepts a single argument, the `counter`.
///
/// ```
/// # use ibc::core::ics24_host::identifier::ConnectionId;
/// let conn_id = ConnectionId::new(11);
/// assert_eq!(&conn_id, "connection-11");
/// ```
pub fn new(identifier: u64) -> Self {
let id = format!("{}-{}", Self::prefix(), identifier);
Self(id)
}
/// Returns the static prefix to be used across all connection identifiers.
pub fn prefix() -> &'static str {
CONNECTION_ID_PREFIX
}
/// Get this identifier as a borrowed `&str`
pub fn as_str(&self) -> &str {
&self.0
}
/// Get this identifier as a borrowed byte slice
pub fn as_bytes(&self) -> &[u8] {
self.0.as_bytes()
}
}
/// This implementation provides a `to_string` method.
impl Display for ConnectionId {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
write!(f, "{}", self.0)
}
}
impl FromStr for ConnectionId {
type Err = IdentifierError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
validate_connection_identifier(s).map(|_| Self(s.to_string()))
}
}
impl Default for ConnectionId {
fn default() -> Self {
Self::new(0)
}
}
/// Equality check against string literal (satisfies &ConnectionId == &str).
/// ```
/// use core::str::FromStr;
/// use ibc::core::ics24_host::identifier::ConnectionId;
/// let conn_id = ConnectionId::from_str("connectionId-0");
/// assert!(conn_id.is_ok());
/// conn_id.map(|id| {assert_eq!(&id, "connectionId-0")});
/// ```
impl PartialEq<str> for ConnectionId {
fn eq(&self, other: &str) -> bool {
self.as_str().eq(other)
}
}
#[cfg_attr(
feature = "parity-scale-codec",
derive(
parity_scale_codec::Encode,
parity_scale_codec::Decode,
scale_info::TypeInfo
)
)]
#[cfg_attr(
feature = "borsh",
derive(borsh::BorshSerialize, borsh::BorshDeserialize)
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PortId(String);
impl PortId {
pub fn new(id: String) -> Result<Self, IdentifierError> {
Self::from_str(&id)
}
/// Infallible creation of the well-known transfer port
pub fn transfer() -> Self {
Self(TRANSFER_PORT_ID.to_string())
}
/// Get this identifier as a borrowed `&str`
pub fn as_str(&self) -> &str {
&self.0
}
/// Get this identifier as a borrowed byte slice
pub fn as_bytes(&self) -> &[u8] {
self.0.as_bytes()
}
pub fn validate(&self) -> Result<(), IdentifierError> {
validate_port_identifier(self.as_str())
}
}
/// This implementation provides a `to_string` method.
impl Display for PortId {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
write!(f, "{}", self.0)
}
}
impl FromStr for PortId {
type Err = IdentifierError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
validate_port_identifier(s).map(|_| Self(s.to_string()))
}
}
impl AsRef<str> for PortId {
fn as_ref(&self) -> &str {
self.0.as_str()
}
}
impl Default for PortId {
fn default() -> Self {
Self(DEFAULT_PORT_ID.to_string())
}
}
#[cfg_attr(
feature = "parity-scale-codec",
derive(
parity_scale_codec::Encode,
parity_scale_codec::Decode,
scale_info::TypeInfo
)
)]
#[cfg_attr(
feature = "borsh",
derive(borsh::BorshSerialize, borsh::BorshDeserialize)
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ChannelId(String);
impl ChannelId {
/// Builds a new channel identifier. Like client and connection identifiers, channel ids are
/// deterministically formed from two elements: a prefix `prefix`, and a monotonically
/// increasing `counter`, separated by a dash "-".
/// The prefix is currently determined statically (see `ChannelId::prefix()`) so this method
/// accepts a single argument, the `counter`.
///
/// ```
/// # use ibc::core::ics24_host::identifier::ChannelId;
/// let chan_id = ChannelId::new(27);
/// assert_eq!(chan_id.to_string(), "channel-27");
/// ```
pub fn new(identifier: u64) -> Self {
let id = format!("{}-{}", Self::prefix(), identifier);
Self(id)
}
/// Returns the static prefix to be used across all channel identifiers.
pub fn prefix() -> &'static str {
CHANNEL_ID_PREFIX
}
/// Get this identifier as a borrowed `&str`
pub fn as_str(&self) -> &str {
&self.0
}
/// Get this identifier as a borrowed byte slice
pub fn as_bytes(&self) -> &[u8] {
self.0.as_bytes()
}
}
/// This implementation provides a `to_string` method.
impl Display for ChannelId {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), FmtError> {
write!(f, "{}", self.0)
}
}
impl FromStr for ChannelId {
type Err = IdentifierError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
validate_channel_identifier(s).map(|_| Self(s.to_string()))
}
}
impl AsRef<str> for ChannelId {
fn as_ref(&self) -> &str {
&self.0
}
}
impl Default for ChannelId {
fn default() -> Self {
Self::new(0)
}
}
/// Equality check against string literal (satisfies &ChannelId == &str).
/// ```
/// use core::str::FromStr;
/// use ibc::core::ics24_host::identifier::ChannelId;
/// let channel_id = ChannelId::from_str("channelId-0");
/// assert!(channel_id.is_ok());
/// channel_id.map(|id| {assert_eq!(&id, "channelId-0")});
/// ```
impl PartialEq<str> for ChannelId {
fn eq(&self, other: &str) -> bool {
self.as_str().eq(other)
}
}
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[derive(Debug, Display)]
pub enum IdentifierError {
/// identifier `{id}` cannot contain separator '/'
ContainSeparator { id: String },
/// identifier `{id}` has invalid length `{length}` must be between `{min}`-`{max}` characters
InvalidLength {
id: String,
length: usize,
min: usize,
max: usize,
},
/// identifier `{id}` must only contain alphanumeric characters or `.`, `_`, `+`, `-`, `#`, - `[`, `]`, `<`, `>`
InvalidCharacter { id: String },
/// identifier prefix `{prefix}` is invalid
InvalidPrefix { prefix: String },
/// identifier cannot be empty
Empty,
}
#[cfg(feature = "std")]
impl std::error::Error for IdentifierError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_valid_chain_id() {
assert!(ChainId::from_str("chainA-0").is_ok());
assert!(ChainId::from_str("chainA-1").is_ok());
assert!(ChainId::from_str("chainA--1").is_ok());
assert!(ChainId::from_str("chainA-1-2").is_ok());
}
#[test]
fn test_invalid_chain_id() {
assert!(ChainId::from_str("1").is_err());
assert!(ChainId::from_str("-1").is_err());
assert!(ChainId::from_str(" -1").is_err());
assert!(ChainId::from_str("chainA").is_err());
assert!(ChainId::from_str("chainA-").is_err());
assert!(ChainId::from_str("chainA-a").is_err());
assert!(ChainId::from_str("chainA-01").is_err());
assert!(ChainId::from_str("/chainA-1").is_err());
assert!(ChainId::from_str("chainA-1-").is_err());
}
}