From e00c34041a67b3e59de4aaf0c8efe24823a1e5f3 Mon Sep 17 00:00:00 2001 From: Nicholas Rodrigues Lordello Date: Tue, 1 Dec 2020 18:54:35 +0100 Subject: added ability to sign --- src/cmd/sign.rs | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/cmd/sign.rs (limited to 'src/cmd') 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> { + let trimmed = s.chars().filter(|c| !c.is_whitespace()).collect::(); + 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()) +} -- cgit v1.2.3