diff options
| author | Nicholas Rodrigues Lordello <[email protected]> | 2021-03-18 09:28:50 +0100 |
|---|---|---|
| committer | Nicholas Rodrigues Lordello <[email protected]> | 2021-03-18 09:28:50 +0100 |
| commit | 789f4585504119de8e490aa12a8c02b649f24ee0 (patch) | |
| tree | ef2df8f30af6f06102b49555a308d77d9eae36ef | |
| parent | 1ce0c196c10dc92977114279180ea714056c587d (diff) | |
added hashing command
| -rw-r--r-- | src/cmd.rs | 12 | ||||
| -rw-r--r-- | src/cmd/hash.rs | 41 | ||||
| -rw-r--r-- | src/cmd/sign.rs | 75 | ||||
| -rw-r--r-- | src/main.rs | 3 | ||||
| -rw-r--r-- | src/transaction.rs | 15 |
5 files changed, 91 insertions, 55 deletions
@@ -2,6 +2,7 @@ pub mod address; pub mod export; +pub mod hash; pub mod new; pub mod sign; @@ -43,3 +44,14 @@ impl AccountOptions { hdk::derive(seed, &path) } } + +/// Permissive hex encoding parsing, ignoring all whitespace and accepting bot +/// upper and lower-case string with an optional `0x` prefix. +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()) +} diff --git a/src/cmd/hash.rs b/src/cmd/hash.rs new file mode 100644 index 0000000..78f33cb --- /dev/null +++ b/src/cmd/hash.rs @@ -0,0 +1,41 @@ +//! Module implementing the `hash` subcommand for `keccak256` hashing data. + +use crate::{cmd, hash}; +use anyhow::Result; +use std::{ + fs, + io::{self, Read}, + path::PathBuf, + str, +}; +use structopt::StructOpt; + +#[derive(Debug, StructOpt)] +pub struct Options { + /// The data is hexidecimal encoded. + #[structopt(short, long)] + hex: bool, + + /// Path to the data to hash. Use `-` for standard in. + #[structopt(name = "DATA", default_value = "-")] + data: PathBuf, +} + +pub fn run(options: Options) -> Result<()> { + let data = match options.data.to_str() { + Some("-") => { + let mut buf = Vec::new(); + io::stdin().read_to_end(&mut buf)?; + buf + } + _ => fs::read(&options.data)?, + }; + let bytes = if options.hex { + cmd::permissive_hex(str::from_utf8(&data)?)? + } else { + data.into_boxed_slice() + }; + + println!("0x{}", hex::encode(hash::keccak256(bytes))); + Ok(()) +} diff --git a/src/cmd/sign.rs b/src/cmd/sign.rs index 088a627..70f2d27 100644 --- a/src/cmd/sign.rs +++ b/src/cmd/sign.rs @@ -1,10 +1,15 @@ //! Module implementing the `sign` subcommand for generating ECDSA signatures. -use crate::{account::Address, cmd::AccountOptions, hash, transaction::Transaction}; +use crate::{ + account::Address, + cmd::{self, AccountOptions}, + hash, + transaction::Transaction, +}; use anyhow::{anyhow, Context as _, Result}; use ethnum::U256; use std::convert::TryInto; -use structopt::{clap::arg_enum, StructOpt}; +use structopt::StructOpt; #[derive(Debug, StructOpt)] pub struct Options { @@ -35,16 +40,9 @@ enum Data { /// Sign an Ethereum message. Message { - /// The message format. Specify "hex" if the message is a hexadecimal - /// encoded string. - #[structopt( - short, - long, - default_value = "string", - case_insensitive = true, - possible_values = &Format::variants(), - )] - format: Format, + /// The message is encoded as a hexadecimal string. + #[structopt(short, long)] + hex: bool, /// The message to sign in the "eth_sign" scheme. This message will be /// prefixed with "\x19Ethereum Signed Message:\n" and its length before @@ -55,15 +53,9 @@ enum Data { /// Sign a raw data. Raw { - /// The message should be Keccak-256 hashed for signing. - #[structopt(short, long)] - hash: bool, - - /// The 32 byte message or binary data to sign specified as a - /// hexadecimal string. If "hash" is not specified, then the specified - /// value must be exactly 32 bytes long. - #[structopt(name = "BYTES", parse(try_from_str = permissive_hex))] - bytes: Box<[u8]>, + /// The 32 byte message to sign specified as a hexadecimal string. + #[structopt(name = "BYTES", parse(try_from_str = permissive_hex_digest))] + message: [u8; 32], }, } @@ -93,18 +85,10 @@ struct TransactionOptions { value: U256, /// The transaction input calldata. - #[structopt(short, long, default_value = "0x", parse(try_from_str = permissive_hex))] + #[structopt(short, long, default_value = "0x", parse(try_from_str = cmd::permissive_hex))] data: Box<[u8]>, } -arg_enum! { - #[derive(Debug)] - enum Format { - String, - Hex, - } -} - impl Data { fn message(&self) -> Result<[u8; 32]> { match self { @@ -115,10 +99,11 @@ impl Data { } => Ok(hash::keccak256( &transaction.as_parameters().encode(*chain_id, None), )), - Data::Message { format, message } => { - let bytes = match format { - Format::String => message.clone().into_bytes().into_boxed_slice(), - Format::Hex => permissive_hex(&message)?, + Data::Message { hex, message } => { + let bytes = if *hex { + cmd::permissive_hex(&message)? + } else { + message.clone().into_bytes().into_boxed_slice() }; let mut buffer = Vec::new(); @@ -128,16 +113,7 @@ impl Data { Ok(hash::keccak256(&buffer)) } - Data::Raw { hash, bytes } => { - if *hash { - Ok(hash::keccak256(&bytes)) - } else { - bytes - .as_ref() - .try_into() - .context("data for signing must be exactly 32 bytes long or hashed") - } - } + Data::Raw { message } => Ok(*message), } } } @@ -177,13 +153,10 @@ pub fn run(options: Options) -> Result<()> { 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()) +fn permissive_hex_digest(s: &str) -> Result<[u8; 32]> { + Ok(cmd::permissive_hex(s)?[..] + .try_into() + .context("message for signing must be exactly 32 bytes long")?) } fn ether(s: &str) -> Result<U256> { diff --git a/src/main.rs b/src/main.rs index c96228b..4fe666a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -23,6 +23,8 @@ enum Options { Address(address::Options), #[structopt(about = "Export a private key")] Export(export::Options), + #[structopt(about = "Keccak256 hash data")] + Hash(cmd::hash::Options), #[structopt(about = "Generate a new HD wallet mnemonic")] New(new::Options), #[structopt(about = "Sign a message")] @@ -33,6 +35,7 @@ fn main() { if let Err(err) = match Options::from_args() { Options::Address(options) => address::run(options), Options::Export(options) => export::run(options), + Options::Hash(options) => cmd::hash::run(options), Options::New(options) => new::run(options), Options::Sign(options) => sign::run(options), } { diff --git a/src/transaction.rs b/src/transaction.rs index 9aa95ea..fe4eb35 100644 --- a/src/transaction.rs +++ b/src/transaction.rs @@ -1,7 +1,10 @@ //! Module defining Ethereum transaction data as well as an RLP encoding //! implementation. -use crate::account::{Address, Signature}; +use crate::{ + account::{Address, Signature}, + hash, +}; use ethnum::U256; /// An Ethereum transaction. @@ -53,6 +56,11 @@ impl Transaction { &rlp::uint(s), ]) } + + /// Returns the 32-byte message used for signing. + pub fn signing_message(&self, chain_id: u64) -> [u8; 32] { + hash::keccak256(self.encode(chain_id, None)) + } } /// Tiny RLP encoding implementation. @@ -116,7 +124,7 @@ fn replay_protection(chain_id: u64, v: u8) -> u64 { #[cfg(test)] mod tests { use super::*; - use crate::{account::PrivateKey, ganache::DETERMINISTIC_PRIVATE_KEY, hash}; + use crate::{account::PrivateKey, ganache::DETERMINISTIC_PRIVATE_KEY}; use hex_literal::hex; const CHAIN_ID: u64 = 0x1337; @@ -146,8 +154,7 @@ mod tests { #[test] fn rlp_encode_with_signature() { let key = PrivateKey::new(DETERMINISTIC_PRIVATE_KEY).unwrap(); - let message = hash::keccak256(transaction().encode(CHAIN_ID, None)); - let signature = key.sign(message); + let signature = key.sign(transaction().signing_message(CHAIN_ID)); assert_eq!( transaction().encode(CHAIN_ID, Some(signature)), |
