1use 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
17pub const LENGTH: usize = 20;
19
20#[derive(Copy, Clone, Eq, Hash, PartialEq, PartialOrd, Ord)]
22pub struct Id([u8; LENGTH]); impl 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 pub fn new(bytes: [u8; LENGTH]) -> Id {
67 Id(bytes)
68 }
69
70 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
104tendermint_pb_modules! {
105 use pb::{
106 crypto::{PublicKey, public_key::Sum},
107 };
108 use super::{Id, LENGTH};
109 use digest::Digest;
110 use crate::{prelude::*, Error};
111 use sha2::Sha256;
112
113 impl TryFrom<PublicKey> for Id {
114 type Error = Error;
115
116 fn try_from(value: PublicKey) -> Result<Self, Self::Error> {
117 let sum = &value
118 .sum
119 .ok_or_else(|| Error::invalid_key("empty sum".to_string()))?;
120 if let Sum::Ed25519(b) = sum {
121 let digest = Sha256::digest(b);
122 return Ok(Id(digest[..LENGTH].try_into().unwrap()))
123 }
124 #[cfg(feature = "secp256k1")]
125 if let Sum::Secp256k1(b) = sum {
126 use ripemd::Ripemd160;
127
128 let sha_digest = Sha256::digest(b);
129 let ripemd_digest = Ripemd160::digest(&sha_digest[..]);
130 let mut bytes = [0u8; LENGTH];
131 bytes.copy_from_slice(&ripemd_digest[..LENGTH]);
132 return Ok(Id(bytes))
133 }
134 Err(Error::invalid_key("not an ed25519 key".to_string()))
135 }
136 }
137}
138
139#[cfg(feature = "rust-crypto")]
140mod key_conversions {
141 use super::{Id, LENGTH};
142 use crate::crypto::default::Sha256;
143 #[cfg(feature = "secp256k1")]
144 use crate::public_key::Secp256k1;
145 use crate::public_key::{Ed25519, PublicKey};
146 use digest::Digest;
147
148 #[cfg(feature = "secp256k1")]
150 impl From<Secp256k1> for Id {
151 fn from(pk: Secp256k1) -> Id {
152 use ripemd::Ripemd160;
153
154 let sha_digest = Sha256::digest(pk.to_sec1_bytes());
155 let ripemd_digest = Ripemd160::digest(&sha_digest[..]);
156 let mut bytes = [0u8; LENGTH];
157 bytes.copy_from_slice(&ripemd_digest[..LENGTH]);
158 Id(bytes)
159 }
160 }
161
162 impl From<Ed25519> for Id {
164 fn from(pk: Ed25519) -> Id {
165 let digest = Sha256::digest(pk.as_bytes());
166 Id(digest[..LENGTH].try_into().unwrap())
167 }
168 }
169
170 impl From<PublicKey> for Id {
171 fn from(pub_key: PublicKey) -> Id {
172 match pub_key {
173 PublicKey::Ed25519(pk) => Id::from(pk),
174 #[cfg(feature = "secp256k1")]
175 PublicKey::Secp256k1(pk) => Id::from(pk),
176 }
177 }
178 }
179}
180
181impl FromStr for Id {
183 type Err = Error;
184
185 fn from_str(s: &str) -> Result<Self, Self::Err> {
186 let bytes = hex::decode_upper(s)
188 .or_else(|_| hex::decode(s))
189 .map_err(Error::subtle_encoding)?;
190
191 bytes.try_into()
192 }
193}
194
195impl<'de> Deserialize<'de> for Id {
197 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
198 where
199 D: Deserializer<'de>,
200 {
201 let s = String::deserialize(deserializer)?;
202 Self::from_str(&s).map_err(|_| {
203 de::Error::custom(format!(
204 "expected {}-character hex string, got {:?}",
205 LENGTH * 2,
206 s
207 ))
208 })
209 }
210}
211
212impl Serialize for Id {
213 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
214 serializer.serialize_str(
215 &String::from_utf8(hex::encode_upper(Vec::<u8>::from(*self)))
216 .map_err(serde::ser::Error::custom)?,
217 )
218 }
219}
220
221#[cfg(all(test, feature = "rust-crypto"))]
222mod tests {
223 use super::*;
224 use crate::public_key::Ed25519;
225
226 #[test]
227 fn test_ed25519_id() {
228 let pubkey_hex = "14253D61EF42D166D02E68D540D07FDF8D65A9AF0ACAA46302688E788A8521E2";
230 let id_hex = "0CDA3F47EF3C4906693B170EF650EB968C5F4B2C";
231
232 let pubkey_bytes = &hex::decode_upper(pubkey_hex).unwrap();
234 let id_bytes = Id::from_str(id_hex).expect("expected id_hex to decode properly");
235
236 let pubkey = Ed25519::try_from(&pubkey_bytes[..]).unwrap();
238 let id = Id::from(pubkey);
239
240 assert_eq!(id_bytes.ct_eq(&id).unwrap_u8(), 1);
241 }
242
243 #[test]
244 #[cfg(feature = "secp256k1")]
245 fn test_secp_id() {
246 use crate::public_key::Secp256k1;
247
248 let pubkey_hex = "02950E1CDFCB133D6024109FD489F734EEB4502418E538C28481F22BCE276F248C";
250 let id_hex = "7C2BB42A8BE69791EC763E51F5A49BCD41E82237";
252
253 let pubkey_bytes = &hex::decode_upper(pubkey_hex).unwrap();
255 let id_bytes = Id::from_str(id_hex).expect("expected id_hex to decode properly");
256
257 let pubkey = Secp256k1::from_sec1_bytes(pubkey_bytes).unwrap();
259 let id = Id::from(pubkey);
260
261 assert_eq!(id_bytes.ct_eq(&id).unwrap_u8(), 1);
262 }
263}