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
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
use crate::get_hash_digest;
use crate::BSVErrors;
use crate::ECIESCiphertext;
use crate::ECIES;
use crate::{sha256r_digest::Sha256r, ECDSA};
use crate::{Hash, PublicKey, SigningHash};
use crate::{Signature, ToHex};
use k256::ecdsa::digest::Digest;
use k256::ecdsa::recoverable;
use k256::{EncodedPoint, SecretKey};
use rand_core::OsRng;
use wasm_bindgen::prelude::*;
use wasm_bindgen::throw_str;

#[wasm_bindgen]
#[derive(Debug, Clone)]
pub struct PrivateKey {
    pub(crate) secret_key: SecretKey,
    pub(crate) is_pub_key_compressed: bool,
}

/**
 * Internal Methods
 */
impl PrivateKey {
    /**
     * Standard ECDSA Message Signing
     */
    pub(crate) fn sign_message_impl(&self, msg: &[u8]) -> Result<Signature, BSVErrors> {
        ECDSA::sign_with_deterministic_k_impl(self, msg, SigningHash::Sha256, false)
    }

    pub(crate) fn to_wif_impl(&self) -> Result<String, BSVErrors> {
        // 1. Get Private Key hex
        let priv_key_hex = self.to_hex();

        // 2. Add 0x80 in front + 0x01 to end if compressed pub key

        let padded_hex = match self.is_pub_key_compressed {
            true => format!("80{}01", priv_key_hex),
            false => format!("80{}", priv_key_hex),
        };

        // 3. SHA256d
        let bytes = hex::decode(padded_hex.clone())?;

        let shad_hex = Hash::sha_256d(&bytes).to_bytes();

        // 4. Take first 4 bytes as checksum
        let checksum = shad_hex.to_vec()[0..4].to_hex();

        // 5. Add checksum to end of padded private key
        let extended_key = format!("{}{}", padded_hex, checksum);

        // 6 Base58 Result
        let extended_key_bytes = hex::decode(extended_key)?;

        Ok(bs58::encode(extended_key_bytes).into_string())
    }

    pub(crate) fn from_bytes_impl(bytes: &[u8]) -> Result<PrivateKey, BSVErrors> {
        let secret_key = SecretKey::from_bytes(bytes)?;

        Ok(PrivateKey {
            secret_key,
            is_pub_key_compressed: true,
        })
    }

    pub(crate) fn from_hex_impl(hex_str: &str) -> Result<PrivateKey, BSVErrors> {
        let bytes = hex::decode(hex_str)?;

        Self::from_bytes_impl(&bytes)
    }

    pub(crate) fn from_wif_impl(wif_string: &str) -> Result<PrivateKey, BSVErrors> {
        // 1. Decode from Base58
        let wif_bytes = bs58::decode(wif_string).into_vec()?;
        let wif_without_checksum = wif_bytes[0..wif_bytes.len() - 4].to_vec();

        // 2. Check the Checksum
        let checksum = wif_bytes[wif_bytes.len() - 4..].to_hex();
        let check_hash = Hash::sha_256d(&wif_without_checksum).to_bytes();
        let check_string = check_hash.to_vec()[0..4].to_hex();

        if check_string.ne(&checksum) {
            return Err(BSVErrors::FromWIF("Checksum does not match!".into()));
        }

        // Private Key is 32 bytes + prefix is 33 bytes, if 34 bytes and ends with 01, compressed is true
        fn is_compressed(unchecksum: &[u8]) -> bool {
            if unchecksum.len() < 34 {
                return false;
            }

            match unchecksum.last() {
                Some(last_byte) => last_byte.eq(&1),
                None => false,
            }
        }

        let is_compressed_pub_key = is_compressed(&wif_without_checksum);
        // 3. Check if compressed public key, return private key string
        let private_key_hex = match is_compressed_pub_key {
            true => wif_without_checksum[1..wif_without_checksum.len() - 1].to_hex(),
            false => wif_without_checksum[1..].to_hex(),
        };

        Ok(PrivateKey::from_hex_impl(&private_key_hex)?.compress_public_key(is_compressed_pub_key))
    }

    pub(crate) fn to_public_key_impl(&self) -> Result<PublicKey, BSVErrors> {
        let pub_key = PublicKey::from_private_key_impl(self);

        if !self.is_pub_key_compressed {
            return pub_key.to_decompressed_impl();
        }

        Ok(pub_key)
    }

    /**
     * Encrypt a message to the public key of this private key.
     */
    pub(crate) fn encrypt_message_impl(&self, message: &[u8]) -> Result<ECIESCiphertext, BSVErrors> {
        ECIES::encrypt_impl(message, self, &self.to_public_key_impl()?, false)
    }

    /**
     * Decrypt a message that was sent to the public key corresponding to this private key.
     */
    pub(crate) fn decrypt_message_impl(&self, ciphertext: &ECIESCiphertext, sender_pub_key: &PublicKey) -> Result<Vec<u8>, BSVErrors> {
        ECIES::decrypt_impl(ciphertext, self, sender_pub_key)
    }
}

#[wasm_bindgen]
impl PrivateKey {
    #[wasm_bindgen(js_name = toBytes)]
    pub fn to_bytes(&self) -> Vec<u8> {
        self.secret_key.to_bytes().to_vec()
    }

    #[wasm_bindgen(js_name = toHex)]
    pub fn to_hex(&self) -> String {
        let secret_key_bytes = self.to_bytes();
        hex::encode(secret_key_bytes)
    }

    #[wasm_bindgen(js_name = fromRandom)]
    pub fn from_random() -> PrivateKey {
        let secret_key = k256::SecretKey::random(&mut OsRng);

        PrivateKey {
            secret_key,
            is_pub_key_compressed: true,
        }
    }

    #[wasm_bindgen(js_name = getPoint)]
    /**
     * Finds the Public Key Point.
     * Always returns the compressed point.
     * To get the decompressed point: PublicKey::from_bytes(point).to_decompressed()
     */
    pub fn get_point(&self) -> Vec<u8> {
        EncodedPoint::from_secret_key(&self.secret_key, self.is_pub_key_compressed).as_bytes().into()
    }

    #[wasm_bindgen(js_name = compressPublicKey)]
    pub fn compress_public_key(&self, should_compress: bool) -> PrivateKey {
        let mut priv_key = self.clone();
        priv_key.is_pub_key_compressed = should_compress;
        priv_key
    }
}

/**
 * WASM Exported Methods
 */
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
impl PrivateKey {
    #[cfg_attr(target_arch = "wasm32", wasm_bindgen(js_name = fromWIF))]
    pub fn from_wif(wif_string: &str) -> Result<PrivateKey, JsValue> {
        match PrivateKey::from_wif_impl(wif_string) {
            Ok(v) => Ok(v),
            Err(e) => throw_str(&e.to_string()),
        }
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen(js_name = fromHex))]
    pub fn from_hex(hex_str: &str) -> Result<PrivateKey, JsValue> {
        match PrivateKey::from_hex_impl(hex_str) {
            Ok(v) => Ok(v),
            Err(e) => throw_str(&e.to_string()),
        }
    }

    #[cfg_attr(target_arch = "wasm32", wasm_bindgen(js_name = signMessage))]
    /**
     * Standard ECDSA Message Signing using SHA256 as the digestg
     */
    pub fn sign_message(&self, msg: &[u8]) -> Result<Signature, JsValue> {
        match PrivateKey::sign_message_impl(&self, msg) {
            Ok(v) => Ok(v),
            Err(e) => throw_str(&e.to_string()),
        }
    }

    #[wasm_bindgen(js_name = toWIF)]
    pub fn to_wif(&self) -> Result<String, JsValue> {
        match PrivateKey::to_wif_impl(&self) {
            Ok(v) => Ok(v),
            Err(e) => throw_str(&e.to_string()),
        }
    }

    #[wasm_bindgen(js_name = fromBytes)]
    pub fn from_bytes(bytes: &[u8]) -> Result<PrivateKey, JsValue> {
        match Self::from_bytes_impl(bytes) {
            Ok(v) => Ok(v),
            Err(e) => throw_str(&e.to_string()),
        }
    }

    #[wasm_bindgen(js_name = toPublicKey)]
    pub fn to_public_key(&self) -> Result<PublicKey, JsValue> {
        match self.to_public_key_impl() {
            Ok(v) => Ok(v),
            Err(e) => throw_str(&e.to_string()),
        }
    }

    /**
     * Encrypt a message to the public key of this private key.
     */
    #[wasm_bindgen(js_name = encryptMessage)]
    pub fn encrypt_message(&self, message: &[u8]) -> Result<ECIESCiphertext, JsValue> {
        match self.encrypt_message_impl(message) {
            Ok(v) => Ok(v),
            Err(e) => throw_str(&e.to_string()),
        }
    }

    /**
     * Decrypt a message that was sent to the public key corresponding to this private key.
     */
    #[wasm_bindgen(js_name = decryptMessage)]
    pub fn decrypt_message(&self, ciphertext: &ECIESCiphertext, sender_pub_key: &PublicKey) -> Result<Vec<u8>, JsValue> {
        match self.decrypt_message_impl(ciphertext, sender_pub_key) {
            Ok(v) => Ok(v),
            Err(e) => throw_str(&e.to_string()),
        }
    }
}

/**
 * Native Exported Methods
 */
#[cfg(not(target_arch = "wasm32"))]
impl PrivateKey {
    pub fn to_wif(&self) -> Result<String, BSVErrors> {
        PrivateKey::to_wif_impl(self)
    }

    pub fn from_wif(wif_string: &str) -> Result<PrivateKey, BSVErrors> {
        PrivateKey::from_wif_impl(wif_string)
    }

    pub fn from_hex(hex_str: &str) -> Result<PrivateKey, BSVErrors> {
        PrivateKey::from_hex_impl(hex_str)
    }

    /**
     * Standard ECDSA Message Signing using SHA256 as the digestg
     */
    pub fn sign_message(&self, msg: &[u8]) -> Result<Signature, BSVErrors> {
        PrivateKey::sign_message_impl(self, msg)
    }

    pub fn from_bytes(bytes: &[u8]) -> Result<PrivateKey, BSVErrors> {
        Self::from_bytes_impl(bytes)
    }

    pub fn to_public_key(&self) -> Result<PublicKey, BSVErrors> {
        self.to_public_key_impl()
    }

    /**
     * Encrypt a message to the public key of this private key.
     */
    pub fn encrypt_message(&self, message: &[u8]) -> Result<ECIESCiphertext, BSVErrors> {
        self.encrypt_message_impl(message)
    }

    /**
     * Decrypt a message that was sent to the public key corresponding to this private key.
     */
    pub fn decrypt_message(&self, ciphertext: &ECIESCiphertext, sender_pub_key: &PublicKey) -> Result<Vec<u8>, BSVErrors> {
        self.decrypt_message_impl(ciphertext, sender_pub_key)
    }
}