Skip to content

Commit

Permalink
Merge pull request #147 from ergoplatform/secret-key-to-bytes
Browse files Browse the repository at this point in the history
Add to_bytes to SecretKey
  • Loading branch information
greenhat committed Nov 18, 2020
2 parents ad5b17b + 9a53af8 commit 5e8baa6
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
5 changes: 5 additions & 0 deletions bindings/ergo-lib-wasm/src/secret_key.rs
Expand Up @@ -37,6 +37,11 @@ impl SecretKey {
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()
}
}

impl From<SecretKey> for wallet::secret_key::SecretKey {
Expand Down
5 changes: 5 additions & 0 deletions ergo-lib/src/sigma_protocol/private_input.rs
Expand Up @@ -31,6 +31,11 @@ impl DlogProverInput {
.map(DlogProverInput::from)
}

/// byte representation of the underlying scalar
pub fn to_bytes(&self) -> [u8; DlogProverInput::SIZE_BYTES] {
self.w.to_bytes().into()
}

/// public key of discrete logarithm signature protocol
pub fn public_image(&self) -> ProveDlog {
// test it, see https://github.com/ergoplatform/sigma-rust/issues/38
Expand Down
21 changes: 21 additions & 0 deletions ergo-lib/src/wallet/secret_key.rs
Expand Up @@ -26,6 +26,13 @@ impl SecretKey {
SecretKey::DlogSecretKey(dpi) => Address::P2PK(dpi.public_image()),
}
}

/// Encode from a serialized key
pub fn to_bytes(&self) -> Vec<u8> {
match self {
SecretKey::DlogSecretKey(key) => key.to_bytes().to_vec(),
}
}
}

impl From<SecretKey> for PrivateInput {
Expand All @@ -41,3 +48,17 @@ impl From<DlogProverInput> for SecretKey {
SecretKey::DlogSecretKey(pi)
}
}

#[cfg(test)]
mod tests {
use super::*;
use std::convert::TryInto;

#[test]
fn dlog_roundtrip() {
let sk = SecretKey::random_dlog();
let sk_copy =
SecretKey::dlog_from_bytes(&sk.to_bytes().as_slice().try_into().unwrap()).unwrap();
assert_eq!(sk, sk_copy);
}
}

0 comments on commit 5e8baa6

Please sign in to comment.