tendermint/
account.rs

1//! Tendermint accounts
2
3use core::{
4    fmt::{self, Debug, Display},
5    str::FromStr,
6};
7
8use bytes::Bytes;
9use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
10use subtle::ConstantTimeEq;
11use subtle_encoding::hex;
12
13use tendermint_proto::Protobuf;
14
15use crate::{error::Error, prelude::*};
16
17/// Size of an  account ID in bytes
18pub const LENGTH: usize = 20;
19
20/// Account IDs
21#[derive(Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord)]
22pub struct Id([u8; LENGTH]); // JSON custom serialization for priv_validator_key.json
23
24impl Protobuf<Vec<u8>> for Id {}
25
26impl TryFrom<Vec<u8>> for Id {
27    type Error = Error;
28
29    fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
30        if value.len() != LENGTH {
31            return Err(Error::invalid_account_id_length());
32        }
33        let mut slice: [u8; LENGTH] = [0; LENGTH];
34        slice.copy_from_slice(&value[..]);
35        Ok(Id(slice))
36    }
37}
38
39impl From<Id> for Vec<u8> {
40    fn from(value: Id) -> Self {
41        value.as_bytes().to_vec()
42    }
43}
44
45impl TryFrom<Bytes> for Id {
46    type Error = Error;
47
48    fn try_from(value: Bytes) -> Result<Self, Self::Error> {
49        if value.len() != LENGTH {
50            return Err(Error::invalid_account_id_length());
51        }
52        let mut slice: [u8; LENGTH] = [0; LENGTH];
53        slice.copy_from_slice(&value[..]);
54        Ok(Id(slice))
55    }
56}
57
58impl From<Id> for Bytes {
59    fn from(value: Id) -> Self {
60        Bytes::copy_from_slice(value.as_bytes())
61    }
62}
63
64impl Id {
65    /// Create a new account ID from raw bytes
66    pub fn new(bytes: [u8; LENGTH]) -> Id {
67        Id(bytes)
68    }
69
70    /// Borrow the account ID as a byte slice
71    pub fn as_bytes(&self) -> &[u8] {
72        &self.0[..]
73    }
74}
75
76impl AsRef<[u8]> for Id {
77    fn as_ref(&self) -> &[u8] {
78        self.as_bytes()
79    }
80}
81
82impl ConstantTimeEq for Id {
83    #[inline]
84    fn ct_eq(&self, other: &Id) -> subtle::Choice {
85        self.as_bytes().ct_eq(other.as_bytes())
86    }
87}
88
89impl Display for Id {
90    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91        for byte in &self.0 {
92            write!(f, "{byte:02X}")?;
93        }
94        Ok(())
95    }
96}
97
98impl Debug for Id {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        write!(f, "account::Id({self})")
101    }
102}
103
104#[cfg(feature = "rust-crypto")]
105mod key_conversions {
106    use super::{Id, LENGTH};
107    use crate::crypto::default::Sha256;
108    #[cfg(feature = "secp256k1")]
109    use crate::public_key::Secp256k1;
110    use crate::public_key::{Ed25519, PublicKey};
111    use digest::Digest;
112
113    // RIPEMD160(SHA256(pk))
114    #[cfg(feature = "secp256k1")]
115    impl From<Secp256k1> for Id {
116        fn from(pk: Secp256k1) -> Id {
117            use ripemd::Ripemd160;
118
119            let sha_digest = Sha256::digest(pk.to_sec1_bytes());
120            let ripemd_digest = Ripemd160::digest(&sha_digest[..]);
121            let mut bytes = [0u8; LENGTH];
122            bytes.copy_from_slice(&ripemd_digest[..LENGTH]);
123            Id(bytes)
124        }
125    }
126
127    // SHA256(pk)[:20]
128    impl From<Ed25519> for Id {
129        fn from(pk: Ed25519) -> Id {
130            let digest = Sha256::digest(pk.as_bytes());
131            Id(digest[..LENGTH].try_into().unwrap())
132        }
133    }
134
135    impl From<PublicKey> for Id {
136        fn from(pub_key: PublicKey) -> Id {
137            match pub_key {
138                PublicKey::Ed25519(pk) => Id::from(pk),
139                #[cfg(feature = "secp256k1")]
140                PublicKey::Secp256k1(pk) => Id::from(pk),
141            }
142        }
143    }
144}
145
146/// Decode account ID from hex
147impl FromStr for Id {
148    type Err = Error;
149
150    fn from_str(s: &str) -> Result<Self, Self::Err> {
151        // Accept either upper or lower case hex
152        let bytes = hex::decode_upper(s)
153            .or_else(|_| hex::decode(s))
154            .map_err(Error::subtle_encoding)?;
155
156        bytes.try_into()
157    }
158}
159
160// Todo: Can I remove custom serialization?
161impl<'de> Deserialize<'de> for Id {
162    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
163    where
164        D: Deserializer<'de>,
165    {
166        let s = String::deserialize(deserializer)?;
167        Self::from_str(&s).map_err(|_| {
168            de::Error::custom(format!(
169                "expected {}-character hex string, got {:?}",
170                LENGTH * 2,
171                s
172            ))
173        })
174    }
175}
176
177impl Serialize for Id {
178    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
179        serializer.serialize_str(
180            &String::from_utf8(hex::encode_upper(Vec::<u8>::from(*self)))
181                .map_err(serde::ser::Error::custom)?,
182        )
183    }
184}
185
186#[cfg(all(test, feature = "rust-crypto"))]
187mod tests {
188    use super::*;
189    use crate::public_key::Ed25519;
190
191    #[test]
192    fn test_ed25519_id() {
193        // test vector for pubkey and id (address)
194        let pubkey_hex = "14253D61EF42D166D02E68D540D07FDF8D65A9AF0ACAA46302688E788A8521E2";
195        let id_hex = "0CDA3F47EF3C4906693B170EF650EB968C5F4B2C";
196
197        // decode pubkey and address
198        let pubkey_bytes = &hex::decode_upper(pubkey_hex).unwrap();
199        let id_bytes = Id::from_str(id_hex).expect("expected id_hex to decode properly");
200
201        // get id for pubkey
202        let pubkey = Ed25519::try_from(&pubkey_bytes[..]).unwrap();
203        let id = Id::from(pubkey);
204
205        assert_eq!(id_bytes.ct_eq(&id).unwrap_u8(), 1);
206    }
207
208    #[test]
209    #[cfg(feature = "secp256k1")]
210    fn test_secp_id() {
211        use crate::public_key::Secp256k1;
212
213        // test vector for pubkey and id (address)
214        let pubkey_hex = "02950E1CDFCB133D6024109FD489F734EEB4502418E538C28481F22BCE276F248C";
215        // SHA256: 034f706ac824dbb0d227c2ca30439e5be3766cfddc90f00bd530951d638b43a4
216        let id_hex = "7C2BB42A8BE69791EC763E51F5A49BCD41E82237";
217
218        // decode pubkey and address
219        let pubkey_bytes = &hex::decode_upper(pubkey_hex).unwrap();
220        let id_bytes = Id::from_str(id_hex).expect("expected id_hex to decode properly");
221
222        // get id for pubkey
223        let pubkey = Secp256k1::from_sec1_bytes(pubkey_bytes).unwrap();
224        let id = Id::from(pubkey);
225
226        assert_eq!(id_bytes.ct_eq(&id).unwrap_u8(), 1);
227    }
228}