소스 검색

crypto/keypair: import public and private key from bytes

ghassmo 4 년 전
부모
커밋
9882856eeb
2개의 변경된 파일22개의 추가작업 그리고 4개의 파일을 삭제
  1. 17 3
      src/crypto/keypair.rs
  2. 5 1
      src/error.rs

+ 17 - 3
src/crypto/keypair.rs

@@ -45,6 +45,13 @@ impl SecretKey {
     pub fn to_bytes(self) -> [u8; 32] {
     pub fn to_bytes(self) -> [u8; 32] {
         self.0.to_bytes()
         self.0.to_bytes()
     }
     }
+
+    pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self> {
+        match pallas::Base::from_bytes(bytes).into() {
+            Some(k) => Ok(Self(k)),
+            None => Err(Error::SecretKeyFromBytes),
+        }
+    }
 }
 }
 
 
 #[derive(Copy, Clone, PartialEq, Debug)]
 #[derive(Copy, Clone, PartialEq, Debug)]
@@ -64,14 +71,21 @@ impl PublicKey {
     pub fn to_bytes(self) -> [u8; 32] {
     pub fn to_bytes(self) -> [u8; 32] {
         self.0.to_bytes()
         self.0.to_bytes()
     }
     }
+
+    pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self> {
+        match pallas::Point::from_bytes(bytes).into() {
+            Some(k) => Ok(Self(k)),
+            None => Err(Error::PublicKeyFromBytes),
+        }
+    }
 }
 }
 
 
+// TODO maybe it's better to use TryFrom
 impl From<Address> for PublicKey {
 impl From<Address> for PublicKey {
-    fn from(address: Address) -> Self {
+    fn from(address: Address) -> PublicKey {
         let mut bytes = [0u8; 32];
         let mut bytes = [0u8; 32];
         bytes.copy_from_slice(&address.0[1..33]);
         bytes.copy_from_slice(&address.0[1..33]);
-        let publickey = pallas::Point::from_bytes(&bytes).unwrap();
-        Self(publickey)
+        Self::from_bytes(&bytes).unwrap()
     }
     }
 }
 }
 
 

+ 5 - 1
src/error.rs

@@ -150,9 +150,13 @@ pub enum Error {
     #[error(transparent)]
     #[error(transparent)]
     AsyncChannelReceiverError(#[from] async_channel::RecvError),
     AsyncChannelReceiverError(#[from] async_channel::RecvError),
 
 
-    /// Address
+    /// Keypari & Address
     #[error("Error converting Address to PublicKey")]
     #[error("Error converting Address to PublicKey")]
     AddressToPublicKeyError,
     AddressToPublicKeyError,
+    #[error("Error converting bytes to PublicKey")]
+    PublicKeyFromBytes,
+    #[error("Error converting bytes to SecretKey")]
+    SecretKeyFromBytes,
     #[error("Invalid Address")]
     #[error("Invalid Address")]
     InvalidAddress,
     InvalidAddress,
 }
 }