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
/*
 * ‌
 * Hedera Rust SDK
 * ​
 * Copyright (C) 2022 - 2023 Hedera Hashgraph, LLC
 * ​
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ‍
 */

use std::fmt;
use std::str::FromStr;

use hex::FromHexError;

use crate::{
    EntityId,
    Error,
};

/// An address as implemented in the Ethereum Virtual Machine.
#[derive(Copy, Clone, Eq, PartialEq, Hash)]
#[repr(transparent)]
pub struct EvmAddress(pub(crate) [u8; 20]);

impl EvmAddress {
    #[must_use]
    pub(crate) fn from_ref(bytes: &[u8; 20]) -> &Self {
        // safety: `self` is `#[repr(transpart)] over `[u8; 20]`
        unsafe { &*(bytes.as_ptr().cast::<EvmAddress>()) }
    }

    /// Gets the underlying bytes this EVM address is made from.
    #[must_use]
    pub fn to_bytes(self) -> [u8; 20] {
        self.0
    }
}

// potential point of confusion: This type is specifically for the `shard.realm.num` in 20 byte format.
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub(crate) struct SolidityAddress(pub(crate) EvmAddress);

impl SolidityAddress {
    #[must_use]
    pub(crate) fn from_ref(bytes: &[u8; 20]) -> &Self {
        // safety: `self` is `#[repr(transpart)] over `EvmAddress`, which is repr transparent over `[u8; 20]`.
        unsafe { &*(bytes.as_ptr().cast::<SolidityAddress>()) }
    }

    #[must_use]
    pub(crate) fn to_bytes(self) -> [u8; 20] {
        self.0.to_bytes()
    }
}

impl From<SolidityAddress> for EntityId {
    fn from(value: SolidityAddress) -> Self {
        let value = value.to_bytes();
        // todo: once split_array_ref is stable, all the unwraps and panics will go away.
        let (shard, value) = value.split_at(4);
        let (realm, num) = value.split_at(8);

        Self {
            shard: u64::from(u32::from_be_bytes(shard.try_into().unwrap())),
            realm: u64::from_be_bytes(realm.try_into().unwrap()),
            num: u64::from_be_bytes(num.try_into().unwrap()),
            checksum: None,
        }
    }
}

impl TryFrom<EntityId> for SolidityAddress {
    type Error = Error;

    fn try_from(value: EntityId) -> Result<Self, Self::Error> {
        // fixme: use the right error type
        let shard = u32::try_from(value.shard).map_err(Error::basic_parse)?.to_be_bytes();
        let realm = value.realm.to_be_bytes();
        let num = value.num.to_be_bytes();

        let mut buf = [0; 20];

        buf[0..][..shard.len()].copy_from_slice(&shard);
        buf[shard.len()..][..realm.len()].copy_from_slice(&realm);
        buf[(shard.len() + realm.len())..][..num.len()].copy_from_slice(&num);

        Ok(Self::from(buf))
    }
}

impl From<[u8; 20]> for SolidityAddress {
    fn from(value: [u8; 20]) -> Self {
        Self(EvmAddress(value))
    }
}

impl<'a> From<&'a [u8; 20]> for &'a SolidityAddress {
    fn from(value: &'a [u8; 20]) -> Self {
        SolidityAddress::from_ref(value)
    }
}

impl<'a> TryFrom<&'a [u8]> for &'a SolidityAddress {
    type Error = Error;

    fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> {
        value.try_into().map(SolidityAddress::from_ref).map_err(|_| error_len(value.len()))
    }
}

impl TryFrom<Vec<u8>> for SolidityAddress {
    type Error = Error;

    fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
        <&SolidityAddress>::try_from(value.as_slice()).copied()
    }
}

impl FromStr for SolidityAddress {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut buf = [0; 20];

        // note: *optional* 0x prefix.
        let address = s.strip_prefix("0x").unwrap_or(s);

        hex::decode_to_slice(address, &mut buf).map(|()| Self(EvmAddress(buf))).map_err(|err| {
            match err {
                FromHexError::InvalidStringLength => error_len(address.len() / 2),
                err => Error::basic_parse(err),
            }
        })
    }
}

fn error_len(bytes: usize) -> crate::Error {
    Error::basic_parse(format!("expected 20 byte (40 character) evm address, got: `{bytes}` bytes"))
}

impl fmt::Debug for SolidityAddress {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "\"{self}\"")
    }
}

impl fmt::Display for SolidityAddress {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:x}", self.0)
    }
}

impl From<[u8; 20]> for EvmAddress {
    fn from(value: [u8; 20]) -> Self {
        Self(value)
    }
}

impl<'a> From<&'a [u8; 20]> for &'a EvmAddress {
    fn from(value: &'a [u8; 20]) -> Self {
        EvmAddress::from_ref(value)
    }
}

impl<'a> TryFrom<&'a [u8]> for &'a EvmAddress {
    type Error = Error;

    fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> {
        value.try_into().map(EvmAddress::from_ref).map_err(|_| error_len(value.len()))
    }
}

impl TryFrom<Vec<u8>> for EvmAddress {
    type Error = Error;

    fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
        <&EvmAddress>::try_from(value.as_slice()).copied()
    }
}

// Note: *requires* 0x prefix.
impl FromStr for EvmAddress {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut buf = [0; 20];

        let address = s
            .strip_prefix("0x")
            .ok_or_else(|| Error::basic_parse("expected `0x` prefix in evm address"))?;

        hex::decode_to_slice(address, &mut buf).map(|()| Self(buf)).map_err(|err| match err {
            FromHexError::InvalidStringLength => error_len(address.len() / 2),
            err => Error::basic_parse(err),
        })
    }
}

impl fmt::Debug for EvmAddress {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "\"{self:#x}\"")
    }
}

impl fmt::Display for EvmAddress {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self:#x}")
    }
}

impl fmt::LowerHex for EvmAddress {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if f.alternate() {
            f.write_str("0x")?;
        }

        let mut output = [0; 40];

        // panic: would either never panic or always panic, it never panics.
        hex::encode_to_slice(self.0, &mut output).unwrap();
        // should never fail. But `unsafe` here when we *aren't* in that crate would be... not great.
        let output = std::str::from_utf8_mut(&mut output).unwrap();
        f.write_str(output)
    }
}

#[cfg(test)]
mod tests {
    use assert_matches::assert_matches;
    use expect_test::expect;

    use super::SolidityAddress;
    use crate::{
        EntityId,
        EvmAddress,
    };

    #[test]
    fn parse_solidity() {
        let addr: SolidityAddress = "131211100f0e0d0c0b0a09080706050403020100".parse().unwrap();

        assert_eq!(
            &addr,
            SolidityAddress::from_ref(&hex_literal::hex!(
                "131211100f0e0d0c0b0a09080706050403020100"
            ))
        );
    }

    #[test]
    fn parse_evm() {
        let addr: EvmAddress = "0x131211100f0e0d0c0b0a09080706050403020100".parse().unwrap();

        assert_eq!(
            &addr,
            EvmAddress::from_ref(&hex_literal::hex!("131211100f0e0d0c0b0a09080706050403020100"))
        );
    }

    #[test]
    fn evm_address_missing_0x_fails() {
        let res: Result<EvmAddress, _> = "131211100f0e0d0c0b0a09080706050403020100".parse();

        assert_matches!(res, Err(crate::Error::BasicParse(_)))
    }

    #[test]
    fn solidity_address_bad_length_fails() {
        let res: Result<EvmAddress, _> = "0x0f0e0d0c0b0a09080706050403020100".parse();

        assert_matches!(res, Err(crate::Error::BasicParse(_)))
    }

    #[test]
    fn evm_address_bad_length_fails() {
        let res: Result<EvmAddress, _> = "0x0f0e0d0c0b0a09080706050403020100".parse();

        assert_matches!(res, Err(crate::Error::BasicParse(_)))
    }

    #[test]
    fn display() {
        expect![[r#"
            "0x0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c"
        "#]]
        .assert_debug_eq(&EvmAddress([0x0c; 20]));
    }

    #[test]
    fn to_entity_id() {
        let solidity_address = SolidityAddress(EvmAddress([0x0c; 20]));
        assert_eq!(
            EntityId::from(solidity_address),
            EntityId {
                shard: 0x0c0c0c0c,
                realm: 0x0c0c0c0c0c0c0c0c,
                num: 0x0c0c0c0c0c0c0c0c,
                checksum: None
            }
        )
    }
}