aboutsummaryrefslogtreecommitdiff
path: root/src/cmd/sign.rs
blob: 088a62788ec8ef265515d53aa4e75431cc82fd43 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
//! Module implementing the `sign` subcommand for generating ECDSA signatures.

use crate::{account::Address, cmd::AccountOptions, hash, transaction::Transaction};
use anyhow::{anyhow, Context as _, Result};
use ethnum::U256;
use std::convert::TryInto;
use structopt::{clap::arg_enum, StructOpt};

#[derive(Debug, StructOpt)]
pub struct Options {
    #[structopt(subcommand)]
    data: Data,

    #[structopt(flatten)]
    account: AccountOptions,
}

#[derive(Debug, StructOpt)]
enum Data {
    /// Sign an Ethereum transaction.
    Transaction {
        #[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.
    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 to sign in the "eth_sign" scheme. This message will be
        /// prefixed with "\x19Ethereum Signed Message:\n" and its length before
        /// hashing and singing.
        #[structopt(name = "MESSAGE")]
        message: String,
    },

    /// 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]>,
    },
}

#[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<Address>,

    /// 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 {
        String,
        Hex,
    }
}

impl Data {
    fn message(&self) -> Result<[u8; 32]> {
        match self {
            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.clone().into_bytes().into_boxed_slice(),
                    Format::Hex => permissive_hex(&message)?,
                };

                let mut buffer = Vec::new();
                buffer.extend_from_slice(b"\x19Ethereum Signed Message:\n");
                buffer.extend_from_slice(bytes.len().to_string().as_bytes());
                buffer.extend_from_slice(&bytes);

                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")
                }
            }
        }
    }
}

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);

    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(())
}

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 ether(s: &str) -> Result<U256> {
    parse_unit(s, 18)
}

fn gwei(s: &str) -> Result<U256> {
    parse_unit(s, 9)
}

fn parse_unit(s: &str, decimals: u8) -> Result<U256> {
    if let Some(hex) = s.strip_prefix("0x") {
        Ok(U256::from_str_radix(hex, 16)?)
    } else {
        let radix = U256::new(10).pow(decimals as _);
        let (n, frac) = match s.find('.') {
            Some(i) => {
                let (n, frac) = s.split_at(i);
                let frac = {
                    let digits = &frac[1..];
                    let offset = decimals
                        .checked_sub(digits.len().try_into()?)
                        .ok_or_else(|| anyhow!("fractional part too long"))?;
                    digits.parse::<U256>()? * U256::new(10).pow(offset as _)
                };

                (n.parse::<U256>()?, frac)
            }
            None => (s.parse::<U256>()?, U256::ZERO),
        };

        Ok(n.checked_mul(radix)
            .and_then(|n| n.checked_add(frac))
            .ok_or_else(|| anyhow!("Ξ value too high"))?)
    }
}

fn gas(s: &str) -> Result<U256> {
    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::<U256>()?
        .checked_mul(U256::new(radix))
        .ok_or_else(|| anyhow!("gas limit too high"))
}