ibc_core_host_cosmos/
utils.rs

1use ibc_app_transfer_types::VERSION;
2use ibc_core_host_types::identifiers::{ChannelId, PortId};
3use ibc_primitives::prelude::*;
4use sha2::{Digest, Sha256};
5
6/// Helper function to generate an escrow address for a given port and channel
7/// ids according to the format specified in the Cosmos SDK
8/// [`ADR-028`](https://github.com/cosmos/cosmos-sdk/blob/master/docs/architecture/adr-028-public-key-addresses.md)
9pub fn cosmos_adr028_escrow_address(port_id: &PortId, channel_id: &ChannelId) -> Vec<u8> {
10    let contents = format!("{port_id}/{channel_id}");
11
12    let mut hasher = Sha256::new();
13    hasher.update(VERSION.as_bytes());
14    hasher.update([0]);
15    hasher.update(contents.as_bytes());
16
17    let mut hash = hasher.finalize().to_vec();
18    hash.truncate(20);
19    hash
20}
21
22#[cfg(test)]
23mod tests {
24    use subtle_encoding::bech32;
25
26    use super::*;
27
28    #[test]
29    fn test_cosmos_escrow_address() {
30        fn assert_eq_escrow_address(port_id: &str, channel_id: &str, address: &str) {
31            let port_id = port_id.parse().unwrap();
32            let channel_id = channel_id.parse().unwrap();
33            let gen_address = {
34                let addr = cosmos_adr028_escrow_address(&port_id, &channel_id);
35                bech32::encode("cosmos", addr)
36            };
37            assert_eq!(gen_address, address.to_owned())
38        }
39
40        // addresses obtained using `gaiad query ibc-transfer escrow-address [port-id] [channel-id]`
41        assert_eq_escrow_address(
42            "transfer",
43            "channel-141",
44            "cosmos1x54ltnyg88k0ejmk8ytwrhd3ltm84xehrnlslf",
45        );
46        assert_eq_escrow_address(
47            "transfer",
48            "channel-207",
49            "cosmos1ju6tlfclulxumtt2kglvnxduj5d93a64r5czge",
50        );
51        assert_eq_escrow_address(
52            "transfer",
53            "channel-187",
54            "cosmos177x69sver58mcfs74x6dg0tv6ls4s3xmmcaw53",
55        );
56    }
57}