Skip to content

feat(cast): Sign Typed Data via CLI #4878

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jun 3, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 35 additions & 18 deletions cli/src/cmd/cast/wallet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,17 @@ pub mod vanity;

use crate::{
cmd::{cast::wallet::vanity::VanityArgs, Cmd},
opts::Wallet,
opts::{SignType, Wallet},
};
use cast::SimpleCast;
use clap::Parser;
use ethers::{
core::rand::thread_rng,
signers::{LocalWallet, Signer},
types::{Address, Signature},
types::{transaction::eip712::TypedData, Address, Signature},
};
use eyre::Context;
use std::{fs::File, io::BufReader};

/// CLI arguments for `cast send`.
#[derive(Debug, Parser)]
Expand Down Expand Up @@ -55,15 +56,11 @@ pub enum WalletSubcommands {
wallet: Wallet,
},

/// Sign a message.
/// Sign a message or typed data.
#[clap(visible_alias = "s")]
Sign {
/// The message to sign.
///
/// Messages starting with 0x are expected to be hex encoded,
/// which get decoded before being signed.
message: String,

#[clap(subcommand)]
command: Option<SignType>,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh now that I had a closer look, this enum is a breaking change because signing text now requires message command?

This is a bit suboptimal,
I think we can add this feature in a nonbreaking way by adding a --data bool flag which interprets the message as typed data?

wdyt?

Copy link
Contributor Author

@Oighty Oighty May 11, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, that seems reasonable.

Wdyt about the from_file param? Should I get rid of that and users can load their JSON into the shell however they see fit. E.g.
cast wallet sign --data "$(cat ./data.json)"

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah that should work!
but for typedata, I think we can keep the param is file check, doesn't hurt

#[clap(flatten)]
wallet: Wallet,
},
Expand Down Expand Up @@ -127,17 +124,37 @@ impl WalletSubcommands {
let addr = wallet.address();
println!("{}", SimpleCast::to_checksum_address(&addr));
}
WalletSubcommands::Sign { message, wallet } => {
WalletSubcommands::Sign { command, wallet } => {
let wallet = wallet.signer(0).await?;
let sig = match message.strip_prefix("0x") {
Some(data) => {
let data_bytes: Vec<u8> =
hex::decode(data).wrap_err("Could not decode 0x-prefixed string.")?;
wallet.sign_message(data_bytes).await?
match command {
Some(SignType::Message { message }) => {
let sig = match message.strip_prefix("0x") {
Some(data) => {
let data_bytes: Vec<u8> = hex::decode(data)
.wrap_err("Could not decode 0x-prefixed string.")?;
wallet.sign_message(data_bytes).await?
}
None => wallet.sign_message(message).await?,
};
println!("0x{sig}");
}
None => wallet.sign_message(message).await?,
};
println!("0x{sig}");
Some(SignType::TypedData { from_file, data }) => {
let typed_data: TypedData = if from_file {
// data is a file name, read json from file
let file = File::open(&data)?;
let reader = BufReader::new(file);
serde_json::from_reader(reader)?
} else {
// data is a json string
serde_json::from_str(&data)?
};
let sig = wallet.sign_typed_data(&typed_data).await?;
println!("0x{sig}");
}
None => {
println!("No subcommand provided. Please provide a subcommand for the type of data to sign.")
}
}
}
WalletSubcommands::Verify { message, signature, address } => {
match signature.verify(message, address) {
Expand Down
28 changes: 27 additions & 1 deletion cli/src/opts/wallet/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::opts::error::PrivateKeyError;
use async_trait::async_trait;
use cast::{AwsChainProvider, AwsClient, AwsHttpClient, AwsRegion, KmsClient};
use clap::Parser;
use clap::{Parser, Subcommand};
use ethers::{
signers::{
coins_bip39::English, AwsSigner, AwsSignerError, HDPath as LedgerHDPath, Ledger,
Expand Down Expand Up @@ -534,6 +534,32 @@ pub struct KeystoreFile {
pub address: Address,
}

#[derive(Debug, Subcommand)]
#[clap(
about = "Sign a message or typed data",
next_display_order = None
)]
pub enum SignType {
#[clap(
name = "message",
about = "Sign a message. The message will be prefixed with the Ethereum Signed Message header and hashed before signing."
)]
Message {
#[clap(value_name = "MESSAGE")]
message: String,
},
#[clap(
name = "typed-data",
about = "Sign typed data. The data will be combined and hashed using the EIP712 specification before signing. The data should be formatted as JSON."
)]
TypedData {
#[clap(short = 'f')]
from_file: bool,
#[clap(value_name = "JSON")]
data: String,
},
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
38 changes: 38 additions & 0 deletions cli/tests/fixtures/sign_typed_data.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"types": {
"EIP712Domain": [
{
"name": "name",
"type": "string"
},
{
"name": "version",
"type": "string"
},
{
"name": "chainId",
"type": "uint256"
},
{
"name": "verifyingContract",
"type": "address"
}
],
"Message": [
{
"name": "data",
"type": "string"
}
]
},
"primaryType": "Message",
"domain": {
"name": "example.metamask.io",
"version": "1",
"chainId": "1",
"verifyingContract": "0x0000000000000000000000000000000000000000"
},
"message": {
"data": "Hello!"
}
}
44 changes: 40 additions & 4 deletions cli/tests/it/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,32 +85,68 @@ casttest!(wallet_address_keystore_with_password_file, |_: TestProject, mut cmd:
assert!(out.contains("0xeC554aeAFE75601AaAb43Bd4621A22284dB566C2"));
});

// tests that `cast wallet sign` outputs the expected signature
casttest!(cast_wallet_sign_utf8_data, |_: TestProject, mut cmd: TestCommand| {
// tests that `cast wallet sign message` outputs the expected signature
casttest!(cast_wallet_sign_message_utf8_data, |_: TestProject, mut cmd: TestCommand| {
cmd.args([
"wallet",
"sign",
"--private-key",
"0x0000000000000000000000000000000000000000000000000000000000000001",
"message",
"test",
]);
let output = cmd.stdout_lossy();
assert_eq!(output.trim(), "0xfe28833983d6faa0715c7e8c3873c725ddab6fa5bf84d40e780676e463e6bea20fc6aea97dc273a98eb26b0914e224c8dd5c615ceaab69ddddcf9b0ae3de0e371c");
});

// tests that `cast wallet sign` outputs the expected signature, given a 0x-prefixed data
casttest!(cast_wallet_sign_hex_data, |_: TestProject, mut cmd: TestCommand| {
// tests that `cast wallet sign message` outputs the expected signature, given a 0x-prefixed data
casttest!(cast_wallet_sign_message_hex_data, |_: TestProject, mut cmd: TestCommand| {
cmd.args([
"wallet",
"sign",
"--private-key",
"0x0000000000000000000000000000000000000000000000000000000000000001",
"message",
"0x0000000000000000000000000000000000000000000000000000000000000000",
]);
let output = cmd.stdout_lossy();
assert_eq!(output.trim(), "0x23a42ca5616ee730ff3735890c32fc7b9491a9f633faca9434797f2c845f5abf4d9ba23bd7edb8577acebaa3644dc5a4995296db420522bb40060f1693c33c9b1c");
});

// tests that `cast wallet sign typed-data` outputs the expected signature, given a JSON string
casttest!(cast_wallet_sign_typed_data_string, |_: TestProject, mut cmd: TestCommand| {
cmd.args([
"wallet",
"sign",
"--private-key",
"0x0000000000000000000000000000000000000000000000000000000000000001",
"typed-data",
"{\"types\": {\"EIP712Domain\": [{\"name\": \"name\",\"type\": \"string\"},{\"name\": \"version\",\"type\": \"string\"},{\"name\": \"chainId\",\"type\": \"uint256\"},{\"name\": \"verifyingContract\",\"type\": \"address\"}],\"Message\": [{\"name\": \"data\",\"type\": \"string\"}]},\"primaryType\": \"Message\",\"domain\": {\"name\": \"example.metamask.io\",\"version\": \"1\",\"chainId\": \"1\",\"verifyingContract\": \"0x0000000000000000000000000000000000000000\"},\"message\": {\"data\": \"Hello!\"}}",
]);
let output = cmd.stdout_lossy();
assert_eq!(output.trim(), "0x06c18bdc8163219fddc9afaf5a0550e381326474bb757c86dc32317040cf384e07a2c72ce66c1a0626b6750ca9b6c035bf6f03e7ed67ae2d1134171e9085c0b51b");
});

// tests that `cast wallet sign typed-data` outputs the expected signature, given a JSON file
casttest!(cast_wallet_sign_typed_data_file, |_: TestProject, mut cmd: TestCommand| {
cmd.args([
"wallet",
"sign",
"--private-key",
"0x0000000000000000000000000000000000000000000000000000000000000001",
"typed-data",
"-f",
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("tests/fixtures/sign_typed_data.json")
.into_os_string()
.into_string()
.unwrap()
.as_str(),
]);
let output = cmd.stdout_lossy();
assert_eq!(output.trim(), "0x06c18bdc8163219fddc9afaf5a0550e381326474bb757c86dc32317040cf384e07a2c72ce66c1a0626b6750ca9b6c035bf6f03e7ed67ae2d1134171e9085c0b51b");
});

// tests that `cast estimate` is working correctly.
casttest!(estimate_function_gas, |_: TestProject, mut cmd: TestCommand| {
let eth_rpc_url = next_http_rpc_endpoint();
Expand Down