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
//! Secret key
use std::convert::TryInto;

use ergo_lib::ergotree_interpreter::sigma_protocol::private_input::DlogProverInput;
use ergo_lib::wallet;
use wasm_bindgen::prelude::*;

use crate::address::Address;

extern crate derive_more;
use derive_more::{From, Into};

/// Secret key for the prover
#[wasm_bindgen]
#[derive(PartialEq, Debug, Clone, From, Into)]
pub struct SecretKey(wallet::secret_key::SecretKey);

#[wasm_bindgen]
impl SecretKey {
    /// generate random key
    pub fn random_dlog() -> SecretKey {
        SecretKey(wallet::secret_key::SecretKey::random_dlog())
    }

    /// Parse dlog secret key from bytes (SEC-1-encoded scalar)
    pub fn dlog_from_bytes(bytes: &[u8]) -> Result<SecretKey, JsValue> {
        let sized_bytes: &[u8; DlogProverInput::SIZE_BYTES] = bytes.try_into().map_err(|_| {
            JsValue::from_str(&format!(
                "expected byte array of size {}, found {}",
                DlogProverInput::SIZE_BYTES,
                bytes.len()
            ))
        })?;
        wallet::secret_key::SecretKey::dlog_from_bytes(sized_bytes)
            .map(SecretKey)
            .ok_or_else(|| JsValue::from_str("failed to parse scalar"))
    }

    /// Address (encoded public image)
    pub fn get_address(&self) -> Address {
        self.0.get_address_from_public_image().into()
    }

    /// Encode from a serialized key
    pub fn to_bytes(&self) -> Vec<u8> {
        self.0.to_bytes()
    }
}

/// SecretKey collection
#[wasm_bindgen]
pub struct SecretKeys(Vec<SecretKey>);

#[wasm_bindgen]
impl SecretKeys {
    /// Create empty SecretKeys
    #[wasm_bindgen(constructor)]
    pub fn new() -> Self {
        SecretKeys(vec![])
    }

    /// Returns the number of elements in the collection
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns the element of the collection with a given index
    pub fn get(&self, index: usize) -> SecretKey {
        self.0[index].clone()
    }

    /// Adds an elements to the collection
    pub fn add(&mut self, elem: &SecretKey) {
        self.0.push(elem.clone());
    }
}

impl From<&SecretKeys> for Vec<wallet::secret_key::SecretKey> {
    fn from(v: &SecretKeys) -> Self {
        v.0.clone().iter().map(|i| i.0.clone()).collect()
    }
}
impl From<Vec<wallet::secret_key::SecretKey>> for SecretKeys {
    fn from(v: Vec<wallet::secret_key::SecretKey>) -> Self {
        SecretKeys(v.into_iter().map(SecretKey::from).collect())
    }
}