From 3a128ac62d5f39664435c636188e0ac88c1e40de Mon Sep 17 00:00:00 2001 From: Nicholas Rodrigues Lordello Date: Thu, 25 Feb 2021 19:02:55 +0100 Subject: Added support for transaction signing --- src/account/signature.rs | 2 +- src/cmd/sign.rs | 122 +++++++++++++++++++++++++++++++++-------------- src/main.rs | 1 + src/transaction.rs | 114 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 201 insertions(+), 38 deletions(-) create mode 100644 src/transaction.rs (limited to 'src') diff --git a/src/account/signature.rs b/src/account/signature.rs index fd3c53d..4c4195b 100644 --- a/src/account/signature.rs +++ b/src/account/signature.rs @@ -3,7 +3,7 @@ use std::fmt::{self, Display, Formatter}; /// A secp256k1 signature. -#[derive(Clone, Debug, Eq, PartialEq)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct Signature { /// Signature V value in Electrum notation. pub v: u8, diff --git a/src/cmd/sign.rs b/src/cmd/sign.rs index b8b789b..088a627 100644 --- a/src/cmd/sign.rs +++ b/src/cmd/sign.rs @@ -1,6 +1,6 @@ //! Module implementing the `sign` subcommand for generating ECDSA signatures. -use crate::{account::Address, cmd::AccountOptions, hash}; +use crate::{account::Address, cmd::AccountOptions, hash, transaction::Transaction}; use anyhow::{anyhow, Context as _, Result}; use ethnum::U256; use std::convert::TryInto; @@ -19,32 +19,18 @@ pub struct Options { enum Data { /// Sign an Ethereum transaction. Transaction { - /// The transaction nonce. - #[structopt(short, long)] - nonce: u64, - - /// The value of the transaction. This can be either a decimal GWei - /// value, or a hexadecimal Wei value. - #[structopt(short = "p", long, parse(try_from_str = gwei))] - gas_price: U256, - - /// The gas limit for the transaction. Can use `M` and `K` suffixes for - /// million and thousand respectively. - #[structopt(short, long, default_value = "21K", parse(try_from_str = gas))] - gas: u64, - - /// The transaction recipient. Omit for contract creation transactions. - #[structopt(short, long)] - to: Option
, - - /// The value of the transaction. This can be either a decimal Ether - /// value, or a "0x"-prefixed hexadecimal Wei value. - #[structopt(short, long, default_value = "0", parse(try_from_str = ether))] - value: U256, - - /// The transaction input calldata. - #[structopt(short, long, default_value = "0x", parse(try_from_str = permissive_hex))] - data: Box<[u8]>, + #[structopt(flatten)] + transaction: TransactionOptions, + + /// The chain ID to sign this transaction for. Use 0 to indicate no + /// relay protection should be used. + #[structopt(short, long, env)] + chain_id: u64, + + /// Only output the transaction signature instead of the RLP-encoded + /// signed transaction. + #[structopt(long)] + signature_only: bool, }, /// Sign an Ethereum message. @@ -81,6 +67,36 @@ enum Data { }, } +#[derive(Debug, StructOpt)] +struct TransactionOptions { + /// The transaction nonce. + #[structopt(short, long)] + nonce: U256, + + /// The value of the transaction. This can be either a decimal GWei + /// value, or a "0x"-prefixed hexadecimal Wei value. + #[structopt(short = "p", long, parse(try_from_str = gwei))] + gas_price: U256, + + /// The gas limit for the transaction. Can use `M` and `K` suffixes for + /// million and thousand respectively. + #[structopt(short, long, default_value = "21K", parse(try_from_str = gas))] + gas: U256, + + /// The transaction recipient. Omit for contract creation transactions. + #[structopt(short, long)] + to: Option
, + + /// The value of the transaction. This can be either a decimal Ether + /// value, or a "0x"-prefixed hexadecimal Wei value. + #[structopt(short, long, default_value = "0", parse(try_from_str = ether))] + value: U256, + + /// The transaction input calldata. + #[structopt(short, long, default_value = "0x", parse(try_from_str = permissive_hex))] + data: Box<[u8]>, +} + arg_enum! { #[derive(Debug)] enum Format { @@ -90,14 +106,18 @@ arg_enum! { } impl Data { - fn message(self) -> Result<[u8; 32]> { + fn message(&self) -> Result<[u8; 32]> { match self { - Data::Transaction { .. } => { - todo!("rlp encode transaction") - } + Data::Transaction { + transaction, + chain_id, + .. + } => Ok(hash::keccak256( + &transaction.as_parameters().encode(*chain_id, None), + )), Data::Message { format, message } => { let bytes = match format { - Format::String => message.into_bytes().into_boxed_slice(), + Format::String => message.clone().into_bytes().into_boxed_slice(), Format::Hex => permissive_hex(&message)?, }; @@ -109,7 +129,7 @@ impl Data { Ok(hash::keccak256(&buffer)) } Data::Raw { hash, bytes } => { - if hash { + if *hash { Ok(hash::keccak256(&bytes)) } else { bytes @@ -122,10 +142,38 @@ impl Data { } } +impl TransactionOptions { + fn as_parameters(&self) -> Transaction { + Transaction { + nonce: self.nonce, + gas_price: self.gas_price, + gas: self.gas, + to: self.to, + value: self.value, + data: self.data.clone().into(), + } + } +} + pub fn run(options: Options) -> Result<()> { let message = options.data.message()?; let signature = options.account.private_key()?.sign(message); - println!("{}", signature); + + match options.data { + Data::Transaction { + transaction, + chain_id, + signature_only: false, + } => println!( + "0x{}", + hex::encode( + transaction + .as_parameters() + .encode(chain_id, Some(signature)) + ) + ), + _ => println!("{}", signature), + } Ok(()) } @@ -173,14 +221,14 @@ fn parse_unit(s: &str, decimals: u8) -> Result { } } -fn gas(s: &str) -> Result { +fn gas(s: &str) -> Result { let (n, radix) = match s.as_bytes().last().map(u8::to_ascii_lowercase) { Some(b'm') => (&s[..s.len() - 1], 1_000_000), Some(b'k') => (&s[..s.len() - 1], 1_000), _ => (s, 1), }; - n.parse::()? - .checked_mul(radix) + n.parse::()? + .checked_mul(U256::new(radix)) .ok_or_else(|| anyhow!("gas limit too high")) } diff --git a/src/main.rs b/src/main.rs index c89a390..4aa453e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,6 +4,7 @@ mod hash; mod hdk; mod mnemonic; mod rand; +mod transaction; use crate::cmd::*; use std::process; diff --git a/src/transaction.rs b/src/transaction.rs new file mode 100644 index 0000000..3229478 --- /dev/null +++ b/src/transaction.rs @@ -0,0 +1,114 @@ +//! Module defining Ethereum transaction data as well as an RLP encoding +//! implementation. + +use crate::account::{Address, Signature}; +use ethnum::U256; + +/// An Ethereum transaction. +#[derive(Clone, Debug)] +pub struct Transaction { + /// The nonce for the transaction. + pub nonce: U256, + /// The gas price in Wei for the transaction. + pub gas_price: U256, + /// The gas limit for the transaction. + pub gas: U256, + /// The target address for the transaction. This can also be `None` to + /// indicate a contract creation transaction. + pub to: Option
, + /// The amount of Ether to send with the transaction. + pub value: U256, + /// The calldata to use for the transaction. + pub data: Vec, +} + +impl Transaction { + /// Returns the RLP encoded transaction with an optional signature. + pub fn encode(&self, chain_id: u64, signature: Option) -> Vec { + // NOTE: This is currently not at all optimal in terms of memory + // allocations, but we don't really care. + let (v, r, s) = if let Some(Signature { v, r, s }) = signature { + ( + replay_protection(chain_id, v), + U256::from_be_bytes(r), + U256::from_be_bytes(s), + ) + } else { + (chain_id, U256::ZERO, U256::ZERO) + }; + + rlp::list(&[ + &rlp::uint(self.nonce)[..], + &rlp::uint(self.gas_price), + &rlp::uint(self.gas), + &if let Some(address) = self.to { + rlp::bytes(&*address) + } else { + rlp::bytes(b"") + }, + &rlp::uint(self.value), + &rlp::bytes(&self.data), + &rlp::uint(v), + &rlp::uint(r), + &rlp::uint(s), + ]) + } +} + +/// Tiny RLP encoding implementation. +mod rlp { + use ethnum::AsU256; + + /// RLP encode some bytes. + pub fn bytes(bytes: &[u8]) -> Vec { + match bytes { + [x] if *x < 0x80 => vec![*x], + _ => { + let mut buf = len(bytes.len(), 0x80); + buf.extend_from_slice(bytes); + buf + } + } + } + + /// RLP encode a list. + pub fn list(items: &[&[u8]]) -> Vec { + let total_len = items.iter().map(|item| item.len()).sum(); + let mut buf = len(total_len, 0xc0); + for item in items { + buf.extend_from_slice(item); + } + buf + } + + /// RLP encode a length. + pub fn len(len: usize, offset: u8) -> Vec { + if len < 56 { + vec![len as u8 + offset] + } else { + let bl_buf = len.to_be_bytes(); + let bl = { + let start = len.leading_zeros() / 8; + &bl_buf[start as usize..] + }; + let mut buf = vec![bl.len() as u8 + offset + 55]; + buf.extend_from_slice(bl); + buf + } + } + + /// RLP encode a unsigned integer. This ensures that it is shortned to its + /// shortest little endian byte representation. + pub fn uint(value: impl AsU256) -> Vec { + let value = value.as_u256(); + let start = value.leading_zeros() / 8; + bytes(&value.to_be_bytes()[start as usize..]) + } +} + +/// Apply EIP-155 replay protection to the specified `v` value. +fn replay_protection(chain_id: u64, v: u8) -> u64 { + assert!(v == 27 || v == 28, "invalid signature v-value"); + let v = v as u64; + v + 8 + chain_id * 2 +} -- cgit v1.2.3