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
use candid::{CandidType, Deserialize};
use ex3_serde::bincode::{deserialize, serialize};
use serde::Serialize;
use serde_bytes::ByteBuf;

use ex3_node_error::OtherError;

use crate::PublicKey;

#[derive(CandidType, Clone, Deserialize, Serialize, Debug, Eq, PartialEq)]
pub struct SecretPublicKeyPocket {
    pub main_secret_pub_key: ByteBuf,
    pub api_secret_pub_keys: Vec<ByteBuf>,
}

impl SecretPublicKeyPocket {
    pub fn encode(&self) -> Vec<u8> {
        serialize(&(&self.main_secret_pub_key, &self.api_secret_pub_keys)).unwrap()
    }

    pub fn decode(bytes: &[u8]) -> Result<Self, String> {
        let (main_secret_pub_key, api_secret_pub_keys) = deserialize(bytes).map_err(|e| {
            format!(
                "Failed to deserialize SecretPublicKeyPocket: {}",
                e.to_string()
            )
        })?;
        Ok(Self {
            main_secret_pub_key,
            api_secret_pub_keys,
        })
    }

    pub fn exists(&self, secret_pub_key: PublicKey) -> bool {
        self.main_secret_pub_key == secret_pub_key
            || self
                .api_secret_pub_keys
                .iter()
                .any(|key| key == &secret_pub_key)
    }
}

impl TryFrom<&[u8]> for SecretPublicKeyPocket {
    type Error = OtherError;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        let (main_secret_pub_key, api_secret_pub_keys) = deserialize(value).map_err(|e| {
            OtherError::new(format!(
                "Failed to deserialize SecretPublicKeyPocket: {}",
                e
            ))
        })?;
        Ok(Self {
            main_secret_pub_key,
            api_secret_pub_keys,
        })
    }
}