// Copyright 2018 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use rand::thread_rng; use std::cmp::min; use std::io::Cursor; use std::ops::Add; /// Keychain trait and its main supporting types. The Identifier is a /// semi-opaque structure (just bytes) to track keys within the Keychain. /// BlindingFactor is a useful wrapper around a private key to help with /// commitment generation. use std::{error, fmt}; use crate::blake2::blake2b::blake2b; use crate::extkey_bip32::{self, ChildNumber}; use serde::{de, ser}; //TODO: Convert errors to use ErrorKind use crate::util; use crate::util::secp::constants::SECRET_KEY_SIZE; use crate::util::secp::key::{PublicKey, SecretKey}; use crate::util::secp::pedersen::Commitment; use crate::util::secp::{self, Message, Secp256k1, Signature}; use crate::util::static_secp_instance; use zeroize::Zeroize; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; // Size of an identifier in bytes pub const IDENTIFIER_SIZE: usize = 17; #[derive(PartialEq, Eq, Clone, Debug, Serialize, Deserialize)] pub enum Error { Secp(secp::Error), KeyDerivation(extkey_bip32::Error), Transaction(String), RangeProof(String), SwitchCommitment, } impl From for Error { fn from(e: secp::Error) -> Error { Error::Secp(e) } } impl From for Error { fn from(e: extkey_bip32::Error) -> Error { Error::KeyDerivation(e) } } impl error::Error for Error { fn description(&self) -> &str { match *self { _ => "some kind of keychain error", } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { _ => write!(f, "some kind of keychain error"), } } } #[derive(Clone, PartialEq, Eq, Ord, Hash, PartialOrd)] pub struct Identifier([u8; IDENTIFIER_SIZE]); impl ser::Serialize for Identifier { fn serialize(&self, serializer: S) -> Result where S: ser::Serializer, { serializer.serialize_str(&self.to_hex()) } } impl<'de> de::Deserialize<'de> for Identifier { fn deserialize(deserializer: D) -> Result where D: de::Deserializer<'de>, { deserializer.deserialize_str(IdentifierVisitor) } } struct IdentifierVisitor; impl<'de> de::Visitor<'de> for IdentifierVisitor { type Value = Identifier; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("an identifier") } fn visit_str(self, s: &str) -> Result where E: de::Error, { let identifier = Identifier::from_hex(s).unwrap(); Ok(identifier) } } impl Identifier { pub fn zero() -> Identifier { Identifier::from_bytes(&[0; IDENTIFIER_SIZE]) } pub fn from_path(path: &ExtKeychainPath) -> Identifier { path.to_identifier() } pub fn to_path(&self) -> ExtKeychainPath { ExtKeychainPath::from_identifier(&self) } pub fn to_value_path(&self, value: u64) -> ValueExtKeychainPath { ValueExtKeychainPath { value, ext_keychain_path: self.to_path(), } } /// output the path itself, for insertion into bulletproof /// recovery processes can grind through possiblities to find the /// correct length if required pub fn serialize_path(&self) -> [u8; IDENTIFIER_SIZE - 1] { let mut retval = [0u8; IDENTIFIER_SIZE - 1]; retval.copy_from_slice(&self.0[1..IDENTIFIER_SIZE]); retval } /// restore from a serialized path pub fn from_serialized_path(len: u8, p: &[u8]) -> Identifier { let mut id = [0; IDENTIFIER_SIZE]; id[0] = len; for i in 1..IDENTIFIER_SIZE { id[i] = p[i - 1]; } Identifier(id) } /// Return the parent path pub fn parent_path(&self) -> Identifier { let mut p = ExtKeychainPath::from_identifier(&self); if p.depth > 0 { p.path[p.depth as usize - 1] = ChildNumber::from(0); p.depth = p.depth - 1; } Identifier::from_path(&p) } pub fn from_bytes(bytes: &[u8]) -> Identifier { let mut identifier = [0; IDENTIFIER_SIZE]; for i in 0..min(IDENTIFIER_SIZE, bytes.len()) { identifier[i] = bytes[i]; } Identifier(identifier) } pub fn to_bytes(&self) -> [u8; IDENTIFIER_SIZE] { self.0.clone() } pub fn from_pubkey(secp: &Secp256k1, pubkey: &PublicKey) -> Identifier { let bytes = pubkey.serialize_vec(secp, true); let identifier = blake2b(IDENTIFIER_SIZE, &[], &bytes[..]); Identifier::from_bytes(&identifier.as_bytes()) } /// Return the identifier of the secret key /// which is the blake2b (10 byte) digest of the PublicKey /// corresponding to the secret key provided. pub fn from_secret_key(secp: &Secp256k1, key: &SecretKey) -> Result { let key_id = PublicKey::from_secret_key(secp, key)?; Ok(Identifier::from_pubkey(secp, &key_id)) } pub fn from_hex(hex: &str) -> Result { let bytes = util::from_hex(hex.to_string()).unwrap(); Ok(Identifier::from_bytes(&bytes)) } pub fn to_hex(&self) -> String { util::to_hex(self.0.to_vec()) } pub fn to_bip_32_string(&self) -> String { let p = ExtKeychainPath::from_identifier(&self); let mut retval = String::from("m"); for i in 0..p.depth { retval.push_str(&format!("/{}", ::from(p.path[i as usize]))); } retval } } impl AsRef<[u8]> for Identifier { fn as_ref(&self) -> &[u8] { &self.0.as_ref() } } impl ::std::fmt::Debug for Identifier { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { r#try!(write!(f, "{}(", stringify!(Identifier))); r#try!(write!(f, "{}", self.to_hex())); write!(f, ")") } } impl fmt::Display for Identifier { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.to_hex()) } } #[derive(Default, Clone, PartialEq, Serialize, Deserialize, Zeroize)] pub struct BlindingFactor([u8; SECRET_KEY_SIZE]); // Dummy `Debug` implementation that prevents secret leakage. impl fmt::Debug for BlindingFactor { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> fmt::Result { write!(f, "BlindingFactor(