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
use ex3_node_error::OtherError;
use ex3_node_types::chain::ChainType;
use ex3_node_types::sign_schema::SignatureSchema;
use ex3_node_types::transaction::WalletRegistration;
use ex3_node_types::{wallet_identifier::WalletIdentifier, PublicKey};

use crate::{PayloadDecoder, Result};

impl PayloadDecoder {
    /// Decode the payload to a wallet identifier
    /// The payload should be in the following format:
    /// `{chain},{pub_key}`
    /// where pub_key are hex encoded
    /// Used for the following transactions:
    /// - [TransactionType::WalletRegistration]
    pub fn decode_to_wallet_registration(payload: &[u8]) -> Result<WalletRegistration> {
        let payload_str = String::from_utf8(payload.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 sign_schema = SignatureSchema::from(
            u8::from_str_radix(&hexes[1], 16).map_err(|_| invalid_payload_error.clone())?,
        );
        let pub_key = hex::decode(&hexes[2]).map_err(|_| invalid_payload_error)?;

        Ok(WalletRegistration {
            wallet_identifier: WalletIdentifier {
                chain_type: ChainType::from(chain),
                pub_key: PublicKey::from(pub_key),
            },
            sign_schema,
        })
    }
}