diff options
| author | Nicholas Rodrigues Lordello <[email protected]> | 2020-12-01 18:54:35 +0100 |
|---|---|---|
| committer | Nicholas Rodrigues Lordello <[email protected]> | 2020-12-01 18:54:35 +0100 |
| commit | e00c34041a67b3e59de4aaf0c8efe24823a1e5f3 (patch) | |
| tree | 3a25a1cd301d2076e99c12e2c04a354c24c1404b /src/cmd/sign.rs | |
| parent | a699b6b4fe6f0e2567f7298fd8174e779f1bd43d (diff) | |
added ability to sign
Diffstat (limited to 'src/cmd/sign.rs')
| -rw-r--r-- | src/cmd/sign.rs | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/src/cmd/sign.rs b/src/cmd/sign.rs new file mode 100644 index 0000000..59095ae --- /dev/null +++ b/src/cmd/sign.rs @@ -0,0 +1,48 @@ +//! Module implementing the `address` subcommand for displaying the public +//! address for corresponding account. + +use crate::{cmd::AccountOptions, hash}; +use anyhow::{Context as _, Result}; +use std::convert::TryInto; +use structopt::StructOpt; + +#[derive(Debug, StructOpt)] +#[structopt(about = "print account public address")] +pub struct Options { + #[structopt(flatten)] + account: AccountOptions, + + /// The message should be Keccak-256 hashed for signing. + #[structopt(short, long)] + hash_message: bool, + + /// The 32 byte message or binary data to sign specified as a hexadecimal + /// string. If "hash-data" is not specified, then the specified value must + /// be exactly 32 bytes long. + #[structopt(name = "MESSAGE", parse(try_from_str = permissive_hex))] + message: Box<[u8]>, +} + +pub fn run(options: Options) -> Result<()> { + let message = if options.hash_message { + hash::keccak256(&options.message) + } else { + options + .message + .as_ref() + .try_into() + .context("message for signing must be exactly 32 bytes long or hashed")? + }; + let signature = options.account.private_key()?.sign(message); + println!("{}", signature); + Ok(()) +} + +fn permissive_hex(s: &str) -> Result<Box<[u8]>> { + let trimmed = s.chars().filter(|c| !c.is_whitespace()).collect::<String>(); + let hex_string = trimmed.strip_prefix("0x").unwrap_or(&trimmed); + let bytes = hex::decode(&hex_string)?; + // NOTE: Use a boxed slice instead of a `Vec` as the former has special + // scemantics with `structopt`. + Ok(bytes.into_boxed_slice()) +} |
