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
use bc_ur::UREncodable;
use dcbor::{Tag, CBORTagged, CBOREncodable, CBOR, CBORTaggedEncodable, Map};

use crate::{ECKeyBase, ECKey, tags, ECPublicKeyBase, ECPublicKey};

/// A compressed elliptic curve digital signature algorithm (ECDSA) uncompressed public key.
///
/// This is considered a "legacy" key type, and is not recommended for use.
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct ECUncompressedPublicKey([u8; Self::KEY_SIZE]);

impl ECUncompressedPublicKey {
    pub const fn from_data(data: [u8; Self::KEY_SIZE]) -> Self {
        Self(data)
    }
}

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

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

impl ECKeyBase for ECUncompressedPublicKey {
    const KEY_SIZE: usize = bc_crypto::ECDSA_UNCOMPRESSED_PUBLIC_KEY_SIZE;

    fn from_data_ref<T>(data: &T) -> Option<Self> where T: AsRef<[u8]>, Self: Sized {
        let data = data.as_ref();
        if data.len() != Self::KEY_SIZE {
            return None;
        }
        let mut key = [0u8; Self::KEY_SIZE];
        key.copy_from_slice(data);
        Some(Self(key))
    }

    fn data(&self) -> &[u8] {
        &self.0
    }
}

impl ECKey for ECUncompressedPublicKey {
    fn public_key(&self) -> ECPublicKey {
        bc_crypto::ecdsa_compress_public_key(&self.0).into()
    }
}

impl ECPublicKeyBase for ECUncompressedPublicKey {
    fn uncompressed_public_key(&self) -> ECUncompressedPublicKey {
        self.clone()
    }
}

impl From<[u8; Self::KEY_SIZE]> for ECUncompressedPublicKey {
    fn from(value: [u8; Self::KEY_SIZE]) -> Self {
        Self::from_data(value)
    }
}

impl AsRef<[u8]> for ECUncompressedPublicKey {
    fn as_ref(&self) -> &[u8] {
        self.data()
    }
}

impl CBORTagged for ECUncompressedPublicKey {
    const CBOR_TAG: Tag = tags::EC_KEY;
}

impl CBOREncodable for ECUncompressedPublicKey {
    fn cbor(&self) -> CBOR {
        self.tagged_cbor()
    }
}

impl CBORTaggedEncodable for ECUncompressedPublicKey {
    fn untagged_cbor(&self) -> CBOR {
        let mut m = Map::new();
        m.insert_into(3, CBOR::byte_string(self.0));
        m.cbor()
    }
}

impl UREncodable for ECUncompressedPublicKey { }