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
use ex3_node_error::{Error, OtherError};
use ex3_node_types::{chain::ChainType, PublicKey};
use ex3_serde::cbor;
use serde_bytes::ByteBuf;

use crate::{tx_type_dto::ApiKey, PayloadDecoder, Result};

impl PayloadDecoder {
    /// Decode the payload to reset main secret request
    /// The payload should be in the following format:
    /// `{chain}|{data.encrypted_pri_key}|{data.l2_pub_key}`
    pub fn decode_to_reset_main_secret(
        payload: &[u8],
    ) -> Result<(ChainType, ex3_node_types::transaction::ResetMainSecret)> {
        let payload_str = String::from_utf8(payload.as_ref().to_vec()).expect("should success");

        let hexes = payload_str.split('|').collect::<Vec<&str>>();

        let invalid_payload_error = OtherError::new("Invalid payload");

        if hexes.len() != 3 {
            return Err(invalid_payload_error.clone().into());
        }
        let chain =
            u128::from_str_radix(&hexes[0], 16).map_err(|_| invalid_payload_error.clone())?;
        let encrypted_pri_key = hex::decode(hexes[1]).map_err(|_| invalid_payload_error.clone())?;
        let l2_pub_key = hex::decode(hexes[2]).map_err(|_| invalid_payload_error)?;

        let encrypted_pri_key: ByteBuf = ByteBuf::from(encrypted_pri_key);
        let l2_pub_key: PublicKey = ByteBuf::from(l2_pub_key);

        let reset_main_secret_request = ex3_node_types::transaction::ResetMainSecret {
            encrypted_pri_key,
            l2_pub_key,
        };
        Ok((chain.into(), reset_main_secret_request))
    }

    /// Decode the payload to create api secret request
    pub fn decode_to_create_api_secret(
        payload: &[u8],
    ) -> Result<ex3_node_types::transaction::CreateApiSecret> {
        let api_key = cbor::deserialize::<ApiKey>(payload).map_err(|e| {
            <OtherError as Into<Error>>::into(OtherError::new(format!(
                "Failed to deserialize payload to Api key: {}",
                e
            )))
        })?;
        Ok(ex3_node_types::transaction::CreateApiSecret(
            api_key.pub_key,
        ))
    }

    /// Decode the payload to destroy api secret request
    pub fn decode_to_destroy_api_secret(
        payload: &[u8],
    ) -> Result<ex3_node_types::transaction::DestroyApiSecret> {
        let api_key = cbor::deserialize::<ApiKey>(payload).map_err(|e| {
            <OtherError as Into<Error>>::into(OtherError::new(format!(
                "Failed to deserialize payload to Api key: {}",
                e
            )))
        })?;
        Ok(ex3_node_types::transaction::DestroyApiSecret(
            api_key.pub_key,
        ))
    }
}