aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Cargo.lock7
-rw-r--r--Cargo.toml1
-rw-r--r--src/cmd/sign.rs28
-rw-r--r--src/mnemonic.rs2
-rw-r--r--src/serialization.rs5
-rw-r--r--src/transaction.rs3
-rw-r--r--src/typeddata.rs553
-rw-r--r--tests/new.rs13
-rw-r--r--tests/sign_typeddata.rs50
-rw-r--r--tests/util/mod.rs77
10 files changed, 707 insertions, 32 deletions
diff --git a/Cargo.lock b/Cargo.lock
index 532be76..f685d77 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -130,6 +130,7 @@ dependencies = [
"hex",
"hex-literal",
"hmac",
+ "maplit",
"pbkdf2",
"secp256k1",
"serde",
@@ -205,6 +206,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7f823d141fe0a24df1e23b4af4e3c7ba9e5966ec514ea068c93024aa7deb765"
[[package]]
+name = "maplit"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3e2e65a1a2e43cfcb47a895c4c8b10d1f4a61097f9f254f183aee60cad9c651d"
+
+[[package]]
name = "opaque-debug"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
diff --git a/Cargo.toml b/Cargo.toml
index 9114d2e..fc98358 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -21,3 +21,4 @@ unicode-normalization = "0.1"
[dev-dependencies]
hex-literal = "0.3"
+maplit = "1"
diff --git a/src/cmd/sign.rs b/src/cmd/sign.rs
index 290b1a3..f292f0d 100644
--- a/src/cmd/sign.rs
+++ b/src/cmd/sign.rs
@@ -5,6 +5,7 @@ use anyhow::{ensure, Context as _, Result};
use hdwallet::{
hash,
transaction::{LegacyTransaction, Transaction},
+ typeddata::TypedData,
};
use std::{convert::TryInto, path::PathBuf};
use structopt::StructOpt;
@@ -12,18 +13,19 @@ use structopt::StructOpt;
#[derive(Debug, StructOpt)]
pub struct Options {
#[structopt(subcommand)]
- data: Data,
+ input: Input,
#[structopt(flatten)]
account: AccountOptions,
}
#[derive(Debug, StructOpt)]
-enum Data {
+#[structopt(rename_all = "lowercase")]
+enum Input {
/// Sign an Ethereum transaction.
Transaction {
/// Path to transaction to sign in JSON format.
- #[structopt(name = "MESSAGE")]
+ #[structopt(name = "TRANSACTION")]
transaction: PathBuf,
/// Only output the transaction signature instead of the RLP-encoded
@@ -46,6 +48,13 @@ enum Data {
message: PathBuf,
},
+ /// Sign EIP-712 typed data.
+ TypedData {
+ /// Path to the EIP-712 typed data in JSON format.
+ #[structopt(name = "TYPEDDATA")]
+ typed_data: PathBuf,
+ },
+
/// Sign a raw data.
Raw {
/// The 32 byte message to sign specified as a hexadecimal string.
@@ -56,8 +65,8 @@ enum Data {
pub fn run(options: Options) -> Result<()> {
let account = options.account.private_key()?;
- match options.data {
- Data::Transaction {
+ match options.input {
+ Input::Transaction {
transaction,
signature_only,
allow_missing_relay_protection,
@@ -78,7 +87,7 @@ pub fn run(options: Options) -> Result<()> {
println!("0x{}", hex::encode(transaction.encode(signature)));
}
}
- Data::Message { message } => {
+ Input::Message { message } => {
let bytes = cmd::read_input(&message)?;
let message = hash::keccak256({
let mut buffer = Vec::with_capacity(46 + bytes.len());
@@ -89,7 +98,12 @@ pub fn run(options: Options) -> Result<()> {
});
println!("{}", account.sign(message));
}
- Data::Raw { message } => {
+ Input::TypedData { typed_data } => {
+ let bytes = cmd::read_input(&typed_data)?;
+ let typed_data = serde_json::from_slice::<TypedData>(&bytes)?;
+ println!("{}", account.sign(typed_data.digest()));
+ }
+ Input::Raw { message } => {
println!("{}", account.sign(message));
}
}
diff --git a/src/mnemonic.rs b/src/mnemonic.rs
index 1d553f0..05d9930 100644
--- a/src/mnemonic.rs
+++ b/src/mnemonic.rs
@@ -63,7 +63,7 @@ impl Mnemonic {
}
fn from_phrase_str(mnemonic: &str) -> Result<Self> {
- let (language, words) = Language::split(mnemonic.as_ref())?;
+ let (language, words) = Language::split(mnemonic)?;
let len = mnemonic_to_byte_length(words.len())?;
let buf = {
diff --git a/src/serialization.rs b/src/serialization.rs
index c972f86..466b759 100644
--- a/src/serialization.rs
+++ b/src/serialization.rs
@@ -1,5 +1,10 @@
//! Module with JSON serialization helpers.
+use serde_json::{Map, Value};
+
+/// A JSON object.
+pub type JsonObject = Map<String, Value>;
+
/// `U256` serialization methods.
pub mod u256 {
use ethnum::{AsU256 as _, U256};
diff --git a/src/transaction.rs b/src/transaction.rs
index bc3b8bc..cab34bc 100644
--- a/src/transaction.rs
+++ b/src/transaction.rs
@@ -10,12 +10,11 @@ mod rlp;
pub use self::{
eip1559::Eip1559Transaction, eip2930::Eip2930Transaction, legacy::LegacyTransaction,
};
-use crate::{account::Signature, hash};
+use crate::{account::Signature, hash, serialization::JsonObject};
use serde::{
de::{self, Deserializer},
Deserialize,
};
-use serde_json::Map as JsonObject;
/// An Ethereum transaction.
#[derive(Clone, Debug)]
diff --git a/src/typeddata.rs b/src/typeddata.rs
new file mode 100644
index 0000000..e399272
--- /dev/null
+++ b/src/typeddata.rs
@@ -0,0 +1,553 @@
+//! Module for hashing EIP-712 typed data.
+
+use crate::{
+ account::Address,
+ hash,
+ serialization::{self, JsonObject},
+};
+use anyhow::{bail, ensure, Context as _, Result};
+use ethnum::U256;
+use serde::{
+ de::{self, Deserializer},
+ Deserialize,
+};
+use serde_json::Value;
+use std::{
+ borrow::Cow,
+ collections::{BTreeMap, HashMap},
+ fmt::{self, Display, Formatter, Write},
+};
+
+/// EIP-712 typed data.
+pub struct TypedData {
+ digest: [u8; 32],
+}
+
+impl TypedData {
+ /// Returns the EIP-712 digest of the typed data.
+ pub fn digest(&self) -> [u8; 32] {
+ self.digest
+ }
+}
+
+impl<'de> Deserialize<'de> for TypedData {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ let blob = TypedDataBlob::deserialize(deserializer)?;
+ Ok(Self {
+ digest: blob.digest().map_err(de::Error::custom)?,
+ })
+ }
+}
+
+#[derive(Deserialize)]
+struct TypedDataBlob {
+ types: Types,
+ #[serde(rename = "primaryType")]
+ primary_type: String,
+ domain: JsonObject,
+ message: JsonObject,
+}
+
+impl TypedDataBlob {
+ fn digest(self) -> Result<[u8; 32]> {
+ self.verify_domain_type()?;
+
+ let TypedDataBlob {
+ types,
+ primary_type,
+ domain,
+ message,
+ } = self;
+ let domain_separator = types.struct_hash("EIP712Domain", domain)?;
+ let message_hash = types.struct_hash(&primary_type, message)?;
+
+ let mut buffer = [0; 66];
+ buffer[0..2].copy_from_slice(b"\x19\x01");
+ buffer[2..34].copy_from_slice(&domain_separator);
+ buffer[34..66].copy_from_slice(&message_hash);
+ Ok(hash::keccak256(buffer))
+ }
+
+ fn verify_domain_type(&self) -> Result<()> {
+ const DOMAIN_MEMBERS: [(&str, MemberKind); 5] = [
+ ("name", MemberKind::String),
+ ("version", MemberKind::String),
+ ("chainId", MemberKind::Uint(256)),
+ ("verifyingContract", MemberKind::Address),
+ ("salt", MemberKind::Bytes(Some(32))),
+ ];
+
+ let domain_type = self.types.type_definition("EIP712Domain")?;
+ ensure!(
+ !domain_type.members.is_empty(),
+ "EIP-712 domain must have at least one member"
+ );
+ domain_type.members.iter().try_fold(
+ DOMAIN_MEMBERS.iter(),
+ |mut allowed_members, member| {
+ let (_, kind) = allowed_members
+ .find(|(name, _)| member.name == *name)
+ .with_context(|| format!("unexpected EIP-712 domain member {}", member.name))?;
+ ensure!(
+ &member.kind == kind,
+ "expected EIP-712 domain member {} to be of type {}",
+ member,
+ kind
+ );
+ Ok(allowed_members)
+ },
+ )?;
+
+ Ok(())
+ }
+}
+
+#[derive(Deserialize)]
+#[serde(transparent)]
+struct Types(HashMap<String, Vec<Member>>);
+
+impl Types {
+ fn struct_hash(&self, kind: &str, mut data: JsonObject) -> Result<[u8; 32]> {
+ let type_definition = self.type_definition(kind)?;
+ let mut buffer = vec![0_u8; 32 * (1 + type_definition.members.len())];
+ buffer[0..32].copy_from_slice(&self.type_hash(kind)?);
+ for (i, member) in type_definition.members.iter().enumerate() {
+ buffer[(i + 1) * 32..][..32].copy_from_slice(
+ &self.encode_value(
+ &member.kind,
+ data.remove(&member.name).with_context(|| {
+ format!("{} value missing property {}", kind, member.name)
+ })?,
+ )?,
+ );
+ }
+
+ ensure!(
+ data.is_empty(),
+ "additional unspecified {} properties: {}",
+ kind,
+ data.keys().cloned().collect::<Vec<_>>().join(", "),
+ );
+ Ok(hash::keccak256(&buffer))
+ }
+
+ fn encode_type(&self, kind: &str) -> Result<String> {
+ let type_definition = self.type_definition(kind)?;
+ let mut sub_types = BTreeMap::new();
+
+ let mut unresolved_sub_types = type_definition.struct_references().collect::<Vec<_>>();
+ while let Some(sub_type_name) = unresolved_sub_types
+ .pop()
+ .filter(|name| !sub_types.contains_key(name))
+ {
+ let sub_type = self.type_definition(sub_type_name)?;
+ unresolved_sub_types.extend(sub_type.struct_references());
+ sub_types.insert(sub_type_name, sub_type);
+ }
+
+ let mut buffer = type_definition.to_string();
+ for sub_type in sub_types.values() {
+ write!(buffer, "{}", sub_type)?;
+ }
+
+ Ok(buffer)
+ }
+
+ fn type_hash(&self, kind: &str) -> Result<[u8; 32]> {
+ let encoded_type = self.encode_type(kind)?;
+ Ok(hash::keccak256(&encoded_type))
+ }
+
+ fn type_definition<'a>(&'a self, kind: &'a str) -> Result<TypeDefinition<'a>> {
+ let members = self
+ .0
+ .get(kind)
+ .with_context(|| format!("missing EIP-712 type definition for {}", kind))?;
+
+ Ok(TypeDefinition { kind, members })
+ }
+
+ fn encode_value(&self, kind: &MemberKind, value: Value) -> Result<[u8; 32]> {
+ Ok(match kind {
+ MemberKind::Bytes(n) => {
+ let bytes = serialization::bytes::deserialize(value)?;
+ match n {
+ Some(n) => {
+ let mut buffer = [0_u8; 32];
+ buffer
+ .get_mut(..(*n as usize))
+ .with_context(|| format!("invalid byte array length {}", n))?
+ .copy_from_slice(&bytes);
+ buffer
+ }
+ None => hash::keccak256(&bytes),
+ }
+ }
+ MemberKind::Uint(n) => {
+ // TODO(nlordell): Actual signed integer support.
+ let value = serialization::u256::deserialize(value)?;
+ ensure!(
+ value.leading_zeros() + n >= 256,
+ "value {:#x} overflows uint{}",
+ value,
+ n,
+ );
+ value.to_be_bytes()
+ }
+ MemberKind::Bool => match bool::deserialize(value)? {
+ true => U256::ONE,
+ false => U256::ZERO,
+ }
+ .to_be_bytes(),
+ MemberKind::Address => {
+ let address = Address::deserialize(value)?;
+ let mut buffer = [0_u8; 32];
+ buffer[12..].copy_from_slice(&*address);
+ buffer
+ }
+ MemberKind::String => hash::keccak256(&*Cow::<str>::deserialize(value)?),
+ MemberKind::Struct(inner) => {
+ let value = match value {
+ Value::Object(value) => value,
+ value => bail!("expected JSON object but got '{}'", value),
+ };
+ self.struct_hash(inner, value)?
+ }
+ _ => {
+ todo!()
+ }
+ })
+ }
+}
+
+struct TypeDefinition<'a> {
+ kind: &'a str,
+ members: &'a [Member],
+}
+
+impl<'a> TypeDefinition<'a> {
+ fn struct_references(&self) -> impl Iterator<Item = &'a str> + 'a {
+ self.members
+ .iter()
+ .filter_map(|member| member.kind.struct_reference())
+ }
+}
+
+impl Display for TypeDefinition<'_> {
+ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
+ write!(f, "{}(", self.kind)?;
+ if let Some(first_member) = self.members.get(0) {
+ write!(f, "{}", first_member)?;
+ }
+ for member in self.members.get(1..).into_iter().flatten() {
+ write!(f, ",{}", member)?;
+ }
+ write!(f, ")")
+ }
+}
+
+#[derive(Deserialize)]
+struct Member {
+ pub name: String,
+ #[serde(rename = "type")]
+ pub kind: MemberKind,
+}
+
+impl Display for Member {
+ fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
+ write!(f, "{} {}", self.kind, self.name)
+ }
+}
+
+#[derive(Debug, PartialEq)]
+enum MemberKind {
+ Bytes(Option<u32>),
+ Uint(u32),
+ Int(u32),
+ Bool,
+ Address,
+ String,
+ Struct(String),
+ Array(Box<MemberKind>, Option<usize>),
+}
+
+impl MemberKind {
+ fn from_str(value: &str) -> Self {
+ match value {
+ "bool" => return MemberKind::Bool,
+ "address" => return MemberKind::Address,
+ "bytes" => return MemberKind::Bytes(None),
+ "string" => return MemberKind::String,
+ _ => {}
+ }
+
+ if let Some((prefix, n)) = value.find(char::is_numeric).and_then(|i| {
+ let (prefix, n) = value.split_at(i);
+ Some((prefix, n.parse::<u32>().ok()?))
+ }) {
+ match (prefix, n) {
+ ("bytes", n) if (1..=32).contains(&n) => return MemberKind::Bytes(Some(n as _)),
+ ("uint", n) if n % 8 == 0 && (8..=256).contains(&n) => return MemberKind::Uint(n),
+ ("int", n) if n % 8 == 0 && (8..=256).contains(&n) => return MemberKind::Int(n),
+ _ => {}
+ }
+ }
+
+ if let Some(prefix) = value.strip_suffix("[]") {
+ return MemberKind::Array(Box::new(MemberKind::from_str(prefix)), None);
+ }
+ if let Some((prefix, n)) = value.strip_suffix(']').and_then(|value| {
+ let (prefix, n) = value.rsplit_once('[')?;
+ Some((prefix, n.parse::<usize>().ok()?))
+ }) {
+ return MemberKind::Array(Box::new(MemberKind::from_str(prefix)), Some(n));
+ }
+
+ MemberKind::Struct(value.to_string())
+ }
+
+ fn struct_reference(&self) -> Option<&str> {
+ match self {
+ MemberKind::Struct(name) => Some(name),
+ MemberKind::Array(inner, _) => inner.struct_reference(),
+ _ => None,
+ }
+ }
+}
+
+impl Display for MemberKind {
+ fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+ match self {
+ MemberKind::Bytes(None) => f.write_str("bytes"),
+ MemberKind::Bytes(Some(n)) => write!(f, "bytes{}", n),
+ MemberKind::Uint(n) => write!(f, "uint{}", n),
+ MemberKind::Int(n) => write!(f, "int{}", n),
+ MemberKind::Bool => f.write_str("bool"),
+ MemberKind::Address => f.write_str("address"),
+ MemberKind::String => f.write_str("string"),
+ MemberKind::Struct(kind) => f.write_str(kind),
+ MemberKind::Array(kind, None) => write!(f, "{}[]", kind),
+ MemberKind::Array(kind, Some(n)) => write!(f, "{}[{}]", kind, n),
+ }
+ }
+}
+
+impl<'de> Deserialize<'de> for MemberKind {
+ fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
+ where
+ D: Deserializer<'de>,
+ {
+ let value = Cow::<str>::deserialize(deserializer)?;
+ Ok(MemberKind::from_str(&*value))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use hex_literal::hex;
+ use maplit::hashmap;
+
+ #[test]
+ fn typed_data_digest() {
+ let typed_data = serde_json::from_str::<TypedData>(
+ r#"{
+ "types": {
+ "EIP712Domain": [
+ { "name": "name", "type": "string" },
+ { "name": "version", "type": "string" },
+ { "name": "chainId", "type": "uint256" },
+ { "name": "verifyingContract", "type": "address" }
+ ],
+ "Person": [
+ { "name": "name", "type": "string" },
+ { "name": "wallet", "type": "address" }
+ ],
+ "Mail": [
+ { "name": "from", "type": "Person" },
+ { "name": "to", "type": "Person" },
+ { "name": "contents", "type": "string" }
+ ]
+ },
+ "primaryType": "Mail",
+ "domain": {
+ "name": "Ether Mail",
+ "version": "1",
+ "chainId": 1,
+ "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC"
+ },
+ "message": {
+ "from": {
+ "name": "Cow",
+ "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826"
+ },
+ "to": {
+ "name": "Bob",
+ "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB"
+ },
+ "contents": "Hello, Bob!"
+ }
+ }"#,
+ )
+ .unwrap();
+ assert_eq!(
+ typed_data.digest(),
+ hex!("be609aee343fb3c4b28e1df9e632fca64fcfaede20f02e86244efddf30957bd2"),
+ );
+ }
+
+ #[test]
+ fn encode_types() {
+ let types = Types(hashmap! {
+ "Transaction".to_string() => vec![
+ Member {
+ name: "from".to_string(),
+ kind: MemberKind::Struct("Person".to_string()),
+ },
+ Member {
+ name: "to".to_string(),
+ kind: MemberKind::Struct("Person".to_string()),
+ },
+ Member {
+ name: "tx".to_string(),
+ kind: MemberKind::Struct("Asset".to_string()),
+ },
+ ],
+ "Person".to_string() => vec![
+ Member {
+ name: "wallet".to_string(),
+ kind: MemberKind::Address,
+ },
+ Member {
+ name: "name".to_string(),
+ kind: MemberKind::String,
+ },
+ ],
+ "Asset".to_string() => vec![
+ Member {
+ name: "token".to_string(),
+ kind: MemberKind::Address,
+ },
+ Member {
+ name: "amount".to_string(),
+ kind: MemberKind::Uint(256),
+ },
+ ],
+ });
+ assert_eq!(
+ types.encode_type("Transaction").unwrap(),
+ "Transaction(Person from,Person to,Asset tx)Asset(address token,uint256 amount)Person(address wallet,string name)",
+ );
+
+ let types = Types(hashmap! {
+ "Foo".to_string() => vec![
+ Member {
+ name: "bar".to_string(),
+ kind: MemberKind::Array(
+ Box::new(MemberKind::Array(
+ Box::new(MemberKind::Struct("Bar".to_string())),
+ None,
+ )),
+ Some(1),
+ ),
+ },
+ ],
+ "Bar".to_string() => vec![
+ Member {
+ name: "baz".to_string(),
+ kind: MemberKind::Array(
+ Box::new(MemberKind::Array(
+ Box::new(MemberKind::Struct("Baz".to_string())),
+ Some(1),
+ )),
+ None,
+ ),
+ },
+ ],
+ "Baz".to_string() => vec![],
+ });
+ assert_eq!(
+ types.encode_type("Foo").unwrap(),
+ "Foo(Bar[][1] bar)Bar(Baz[1][] baz)Baz()",
+ );
+ }
+
+ #[test]
+ fn member_kind_from_and_to_str() {
+ for (name, kind) in [
+ ("bool", MemberKind::Bool),
+ ("address", MemberKind::Address),
+ ("bytes", MemberKind::Bytes(None)),
+ ("string", MemberKind::String),
+ ("bytes12", MemberKind::Bytes(Some(12))),
+ ("uint96", MemberKind::Uint(96)),
+ ("int256", MemberKind::Int(256)),
+ ("bytes0", MemberKind::Struct("bytes0".to_string())),
+ ("uint9", MemberKind::Struct("uint9".to_string())),
+ ("uint320", MemberKind::Struct("uint320".to_string())),
+ ("int42", MemberKind::Struct("int42".to_string())),
+ ("int0", MemberKind::Struct("int0".to_string())),
+ (
+ "uint256[]",
+ MemberKind::Array(Box::new(MemberKind::Uint(256)), None),
+ ),
+ (
+ "bool[][3]",
+ MemberKind::Array(
+ Box::new(MemberKind::Array(Box::new(MemberKind::Bool), None)),
+ Some(3),
+ ),
+ ),
+ ("uint256]", MemberKind::Struct("uint256]".to_string())),
+ ("uin[t256]", MemberKind::Struct("uin[t256]".to_string())),
+ ] {
+ let parsed = MemberKind::from_str(name);
+ assert_eq!(parsed, kind);
+ assert_eq!(parsed.to_string(), name);
+ }
+ }
+
+ #[test]
+ fn type_definition_display() {
+ for (type_definition, formatted) in [
+ (
+ TypeDefinition {
+ kind: "Empty",
+ members: &[],
+ },
+ "Empty()",
+ ),
+ (
+ TypeDefinition {
+ kind: "Foo",
+ members: &[Member {
+ name: "foo".to_string(),
+ kind: MemberKind::Address,
+ }],
+ },
+ "Foo(address foo)",
+ ),
+ (
+ TypeDefinition {
+ kind: "FooBar",
+ members: &[
+ Member {
+ name: "foo".to_string(),
+ kind: MemberKind::Address,
+ },
+ Member {
+ name: "bar".to_string(),
+ kind: MemberKind::Array(Box::new(MemberKind::Uint(256)), None),
+ },
+ ],
+ },
+ "FooBar(address foo,uint256[] bar)",
+ ),
+ ] {
+ assert_eq!(type_definition.to_string(), formatted);
+ }
+ }
+}
diff --git a/tests/new.rs b/tests/new.rs
index 4ddbf0c..a44dd2d 100644
--- a/tests/new.rs
+++ b/tests/new.rs
@@ -1,20 +1,23 @@
mod util;
use hdwallet::mnemonic::Mnemonic;
+use util::Hdwallet;
#[test]
fn generates_random_mnemonic() {
- let mnemonic = util::exec("new", &[]);
+ let mnemonic = Hdwallet::run("new", &[]);
assert!(Mnemonic::from_phrase(mnemonic).is_ok())
}
#[test]
fn errors_on_invalid_language() {
- assert!(util::try_exec("new", &["--language", "klingon"]).is_err());
+ assert!(Hdwallet::new("new", &["--language", "klingon"])
+ .execute()
+ .is_err());
}
#[test]
fn errors_on_invalid_length() {
- assert!(util::try_exec("new", &["--length", "1"]).is_err());
- assert!(util::try_exec("new", &["--length", "42"]).is_err());
-} \ No newline at end of file
+ assert!(Hdwallet::new("new", &["--length", "1"]).execute().is_err());
+ assert!(Hdwallet::new("new", &["--length", "42"]).execute().is_err());
+}
diff --git a/tests/sign_typeddata.rs b/tests/sign_typeddata.rs
new file mode 100644
index 0000000..4c6da7f
--- /dev/null
+++ b/tests/sign_typeddata.rs
@@ -0,0 +1,50 @@
+mod util;
+
+use crate::util::Hdwallet;
+
+#[test]
+fn signs_typed_data() {
+ let signature = Hdwallet::new("sign", &["typeddata", "-"])
+ .stdin(
+ r#"{
+ "types": {
+ "EIP712Domain": [
+ { "name": "name", "type": "string" },
+ { "name": "version", "type": "string" },
+ { "name": "chainId", "type": "uint256" },
+ { "name": "verifyingContract", "type": "address" }
+ ],
+ "Person": [
+ { "name": "name", "type": "string" },
+ { "name": "wallet", "type": "address" }
+ ],
+ "Mail": [
+ { "name": "from", "type": "Person" },
+ { "name": "to", "type": "Person" },
+ { "name": "contents", "type": "string" }
+ ]
+ },
+ "primaryType": "Mail",
+ "domain": {
+ "name": "Ether Mail",
+ "version": "1",
+ "chainId": 1,
+ "verifyingContract": "0xCcCCccccCCCCcCCCCCCcCcCccCcCCCcCcccccccC"
+ },
+ "message": {
+ "from": {
+ "name": "Cow",
+ "wallet": "0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826"
+ },
+ "to": {
+ "name": "Bob",
+ "wallet": "0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB"
+ },
+ "contents": "Hello, Bob!"
+ }
+ }"#,
+ )
+ .execute()
+ .unwrap();
+ assert_eq!(signature, "0x12bdd486cb42c3b3c414bb04253acfe7d402559e7637562987af6bd78508f38623c1cc09880613762cc913d49fd7d3c091be974c0dee83fb233300b6b58727311c");
+}
diff --git a/tests/util/mod.rs b/tests/util/mod.rs
index 3cc4c66..cd29b28 100644
--- a/tests/util/mod.rs
+++ b/tests/util/mod.rs
@@ -1,29 +1,72 @@
+#![allow(dead_code)]
+
#[path = "../../src/ganache.rs"]
mod ganache;
-use std::{str, process::Command};
pub use ganache::*;
+use std::{
+ io::Write as _,
+ process::{Command, Stdio},
+ str, thread,
+};
-/// Utility function for running the `hdwallet` command for integration tests.
-pub fn exec(subcommand: &str, args: &[&str]) -> String {
- try_exec(subcommand, args).unwrap()
+/// Utility type for building an `hdwallet` command for integration tests.
+pub struct Hdwallet {
+ command: Command,
+ stdin: Option<Vec<u8>>,
}
-/// Try and execute a command, returning an error if there was one.
-pub fn try_exec(subcommand: &str, args: &[&str]) -> Result<String, String> {
- let output = Command::new("cargo")
- .env("MNEMONIC", ganache::DETERMINISTIC_MNEMONIC)
- .args(["run", "--", subcommand])
- .args(args)
- .output()
- .unwrap();
- if output.status.success() {
- Ok(string_from_utf8(output.stdout))
- } else {
- Err(string_from_utf8(output.stderr))
+impl Hdwallet {
+ /// Create a new `hdwallet` command builder.
+ pub fn new(subcommand: &str, args: &[&str]) -> Self {
+ let mut command = Command::new("cargo");
+ command
+ .env("MNEMONIC", ganache::DETERMINISTIC_MNEMONIC)
+ .args(["run", "--", subcommand])
+ .args(args);
+ Self {
+ command,
+ stdin: None,
+ }
+ }
+
+ /// Sets the standard input to be used for the command.
+ pub fn stdin(mut self, data: impl Into<Vec<u8>>) -> Self {
+ self.stdin = Some(data.into());
+ self
+ }
+
+ /// Executes the command and returns the standard output on success and
+ /// standard error on failure.
+ pub fn execute(mut self) -> Result<String, String> {
+ self.command.stdout(Stdio::piped()).stderr(Stdio::piped());
+ if self.stdin.is_some() {
+ self.command.stdin(Stdio::piped());
+ }
+
+ let mut process = self.command.spawn().map_err(|err| err.to_string())?;
+
+ if let Some(data) = self.stdin {
+ let mut stdin = process.stdin.take().unwrap();
+ thread::spawn(move || {
+ stdin.write_all(&data).unwrap();
+ });
+ }
+
+ let output = process.wait_with_output().map_err(|err| err.to_string())?;
+ if output.status.success() {
+ Ok(string_from_utf8(output.stdout))
+ } else {
+ Err(string_from_utf8(output.stderr))
+ }
+ }
+
+ /// Builds and executes an `hdwallet` command.
+ pub fn run(subcommand: &str, args: &[&str]) -> String {
+ Hdwallet::new(subcommand, args).execute().unwrap()
}
}
fn string_from_utf8(bytes: Vec<u8>) -> String {
str::from_utf8(&bytes).unwrap().trim().to_string()
-} \ No newline at end of file
+}