From 177d24325a098e6e62ee9445a0a3cf59a119628c Mon Sep 17 00:00:00 2001 From: Nicholas Rodrigues Lordello Date: Sat, 31 Jul 2021 11:34:58 +0200 Subject: add commpand for export public key --- src/account.rs | 9 +++++++-- src/cmd.rs | 1 + src/cmd/public_key.rs | 26 ++++++++++++++++++++++++++ src/main.rs | 3 +++ 4 files changed, 37 insertions(+), 2 deletions(-) create mode 100644 src/cmd/public_key.rs (limited to 'src') diff --git a/src/account.rs b/src/account.rs index 7d1eeb5..6233f6a 100644 --- a/src/account.rs +++ b/src/account.rs @@ -25,10 +25,15 @@ impl PrivateKey { Ok(PrivateKey(key)) } + /// Returns the public key for the private key. + pub fn public(&self) -> PublicKey { + let secp = Secp256k1::signing_only(); + PublicKey::from_secret_key(&secp, &self.0) + } + /// Returns the public address for the private key. pub fn address(&self) -> Address { - let secp = Secp256k1::signing_only(); - let public_key = PublicKey::from_secret_key(&secp, &self.0).serialize_uncompressed(); + let public_key = self.public().serialize_uncompressed(); // NOTE: An ethereum address is the last 20 bytes of the keccak hash of // the public key. Note that `libsecp256k1` public key is serialized diff --git a/src/cmd.rs b/src/cmd.rs index c10f834..c976d54 100644 --- a/src/cmd.rs +++ b/src/cmd.rs @@ -5,6 +5,7 @@ pub mod export; pub mod hash; pub mod hex; pub mod new; +pub mod public_key; pub mod sign; use crate::{account::PrivateKey, hdk, mnemonic::Mnemonic}; diff --git a/src/cmd/public_key.rs b/src/cmd/public_key.rs new file mode 100644 index 0000000..31e5d0a --- /dev/null +++ b/src/cmd/public_key.rs @@ -0,0 +1,26 @@ +//! Module implementing the `address` subcommand for displaying the public +//! address for corresponding account. + +use crate::cmd::AccountOptions; +use anyhow::Result; +use structopt::StructOpt; + +#[derive(Debug, StructOpt)] +pub struct Options { + #[structopt(flatten)] + account: AccountOptions, +} + +pub fn run(options: Options) -> Result<()> { + println!( + "0x{}", + hex::encode( + &options + .account + .private_key()? + .public() + .serialize_uncompressed() + ) + ); + Ok(()) +} diff --git a/src/main.rs b/src/main.rs index 29d8ea5..8385469 100644 --- a/src/main.rs +++ b/src/main.rs @@ -29,6 +29,8 @@ enum Options { Hex(cmd::hex::Options), #[structopt(about = "Generate a new HD wallet mnemonic")] New(new::Options), + #[structopt(about = "Export the public key for an account")] + PublicKey(public_key::Options), #[structopt(about = "Sign a message")] Sign(sign::Options), } @@ -41,6 +43,7 @@ fn main() { Options::Hex(options) => cmd::hex::run(options), Options::New(options) => new::run(options), Options::Sign(options) => sign::run(options), + Options::PublicKey(options) => public_key::run(options), } { if cfg!(debug_assertions) { eprintln!("ERROR: {:?}", err); -- cgit v1.2.3