Sfoglia il codice sorgente

sdk/crypto: Add FromStr implementation for Nullifier.

Luther Blissett 3 anni fa
parent
commit
f26ad3b7f0
3 ha cambiato i file con 29 aggiunte e 0 eliminazioni
  1. 1 0
      Cargo.lock
  2. 3 0
      src/sdk/Cargo.toml
  3. 25 0
      src/sdk/src/crypto/nullifier.rs

+ 1 - 0
Cargo.lock

@@ -1237,6 +1237,7 @@ dependencies = [
 name = "darkfi-sdk"
 version = "0.3.0"
 dependencies = [
+ "bs58",
  "pasta_curves",
  "thiserror",
 ]

+ 3 - 0
src/sdk/Cargo.toml

@@ -12,5 +12,8 @@ edition = "2021"
 # Error handling
 thiserror = "1.0.37"
 
+# Encoding
+bs58 = "0.4.0"
+
 # Cryptography
 pasta_curves = "0.4.0"

+ 25 - 0
src/sdk/src/crypto/nullifier.rs

@@ -1,3 +1,6 @@
+use core::str::FromStr;
+use std::io;
+
 use pasta_curves::{group::ff::PrimeField, pallas};
 
 /// The `Nullifier` is represented as a base field element.
@@ -32,3 +35,25 @@ impl From<pallas::Base> for Nullifier {
         Self(x)
     }
 }
+
+impl FromStr for Nullifier {
+    type Err = io::Error;
+
+    /// Tries to decode a base58 string into a `Nullifier` type.
+    fn from_str(s: &str) -> Result<Self, Self::Err> {
+        let bytes = match bs58::decode(s).into_vec() {
+            Ok(v) => v,
+            Err(e) => return Err(io::Error::new(io::ErrorKind::Other, e)),
+        };
+
+        if bytes.len() != 32 {
+            return Err(io::Error::new(io::ErrorKind::Other, "Length of decoded bytes is not 32"))
+        }
+
+        if let Some(nullifier) = Self::from_bytes(bytes.try_into().unwrap()) {
+            return Ok(nullifier)
+        }
+
+        return Err(io::Error::new(io::ErrorKind::Other, "Invalid bytes for Nullifier"))
+    }
+}