celestia_tendermint/
account.rs

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