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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
#[cfg(feature = "c-secp256k1")]
use secp256k1::{Message, Error, RecoverableSignature, RecoveryId, SECP256K1};
#[cfg(feature = "c-secp256k1")]
use secp256k1::key::{PublicKey, SecretKey};
#[cfg(feature = "rust-secp256k1")]
use secp256k1::{self, Message, Error, Signature, RecoveryId, SecretKey, PublicKey};

use rlp::{self, Encodable, Decodable, RlpStream, DecoderError, UntrustedRlp};
use bigint::{Address, Gas, H256, U256, B256, M256};
use sha3::{Digest, Keccak256};
use address::FromKey;
use std::marker::PhantomData;
use std::str::FromStr;
use super::{TransactionAction, RlpHash};

/// Refer to EIP155 related to chain ID.
pub trait SignaturePatch {
    fn chain_id() -> Option<u64>;
}

/// Frontier signature patch without EIP155.
pub struct GlobalSignaturePatch;
impl SignaturePatch for GlobalSignaturePatch {
    fn chain_id() -> Option<u64> { None }
}

/// EIP155 Ethereum Classic chain.
pub struct ClassicSignaturePatch;
impl SignaturePatch for ClassicSignaturePatch {
    fn chain_id() -> Option<u64> { Some(61) }
}

/// Refer to Homestead transaction validation.
pub trait ValidationPatch {
    fn require_low_s() -> bool;
}

/// Frontier validation patch.
pub struct FrontierValidationPatch;
impl ValidationPatch for FrontierValidationPatch {
    fn require_low_s() -> bool { false }
}

/// Homestead validation patch.
pub struct HomesteadValidationPatch;
impl ValidationPatch for HomesteadValidationPatch {
    fn require_low_s() -> bool { true }
}

const ECDSA_SIGNATURE_BYTES: usize = 65;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TransactionSignature {
    pub v: u64,
    pub r: H256,
    pub s: H256,
}

impl TransactionSignature {
    pub fn standard_v(&self) -> u8 {
        let v = self.v;
        if v == 27 || v == 28 || v > 36 {
            ((v - 1) % 2) as u8
        } else {
            4
        }
    }

    pub fn is_low_s(&self) -> bool {
        self.s <= H256::from_str("0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0").unwrap()
    }

    pub fn is_valid(&self) -> bool {
        self.standard_v() <= 1 &&
            self.r < H256::from_str("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141").unwrap() &&
            self.r >= H256::from(1) &&
            self.s < H256::from_str("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141").unwrap() &&
            self.s >= H256::from(1)
    }

    pub fn chain_id(&self) -> Option<u64> {
        if self.v > 36 {
            Some((self.v - 35) / 2)
        } else {
            None
        }
    }

    #[cfg(feature = "c-secp256k1")]
    pub fn to_recoverable_signature(&self) -> Result<RecoverableSignature, Error> {
        let mut sig = [0u8; 64];
        sig[0..32].copy_from_slice(&self.r);
        sig[32..64].copy_from_slice(&self.s);

        RecoverableSignature::from_compact(&SECP256K1, &sig, RecoveryId::from_i32(self.standard_v() as i32)?)
    }

    #[cfg(feature = "rust-secp256k1")]
    pub fn to_recoverable_signature(&self) -> Result<(Signature, RecoveryId), Error> {
        let mut sig = [0u8; 64];
        sig[0..32].copy_from_slice(&self.r);
        sig[32..64].copy_from_slice(&self.s);

        Ok((Signature::parse(&sig), RecoveryId::parse(self.standard_v() as u8)?))
    }
}

pub struct UnsignedTransaction {
    pub nonce: U256,
    pub gas_price: Gas,
    pub gas_limit: Gas,
    pub action: TransactionAction,
    pub value: U256,
    pub input: Vec<u8>,
}

impl UnsignedTransaction {
    fn signing_rlp_append(&self, s: &mut RlpStream, chain_id: Option<u64>) {
        s.begin_list(if chain_id.is_some() { 9 } else { 6 });
        s.append(&self.nonce);
        s.append(&self.gas_price);
        s.append(&self.gas_limit);
        s.append(&self.action);
        s.append(&self.value);
        s.append(&self.input);

        if let Some(chain_id) = chain_id {
            s.append(&chain_id);
            s.append(&0u8);
            s.append(&0u8);
        }
    }

    fn signing_hash(&self, chain_id: Option<u64>) -> H256 {
        let mut stream = RlpStream::new();
        self.signing_rlp_append(&mut stream, chain_id);
        H256::from(Keccak256::digest(&stream.drain()).as_slice())
    }

    pub fn sign<P: SignaturePatch>(self, key: &SecretKey) -> Transaction {
        let hash = self.signing_hash(P::chain_id());
        // hash is always MESSAGE_SIZE bytes.
        let msg = {
            #[cfg(feature = "c-secp256k1")]
            { Message::from_slice(&hash).unwrap() }
            #[cfg(feature = "rust-secp256k1")]
            { let mut a = [0u8; 32];
              for i in 0..32 {
                  a[i] = hash[i];
              }
              Message::parse(&a)
            }
        };

        // SecretKey and Message are always valid.
        let s = {
            #[cfg(feature = "c-secp256k1")]
            { SECP256K1.sign_recoverable(&msg, key).unwrap() }
            #[cfg(feature = "rust-secp256k1")]
            { secp256k1::sign(&msg, key).unwrap() }
        };
        let (rid, sig) = {
            #[cfg(feature = "c-secp256k1")]
            { s.serialize_compact(&SECP256K1) }
            #[cfg(feature = "rust-secp256k1")]
            { (s.1, s.0.serialize()) }
        };

        let sig = TransactionSignature {
            v: ({
                #[cfg(feature = "c-secp256k1")]
                { rid.to_i32() }
                #[cfg(feature = "rust-secp256k1")]
                { let v: i32 = rid.into(); v }
            } + if let Some(n) = P::chain_id() { (35 + n * 2) as i32 } else { 27 }) as u64,
            r: H256::from(&sig[0..32]),
            s: H256::from(&sig[32..64]),
        };

        Transaction {
            nonce: self.nonce,
            gas_price: self.gas_price,
            gas_limit: self.gas_limit,
            action: self.action,
            value: self.value,
            input: self.input,
            signature: sig,
        }
    }

    pub fn sign_global(self, key: &SecretKey) -> Transaction {
        self.sign::<GlobalSignaturePatch>(key)
    }
}

impl From<Transaction> for UnsignedTransaction {
    fn from(val: Transaction) -> UnsignedTransaction {
        UnsignedTransaction {
            nonce: val.nonce,
            gas_price: val.gas_price,
            gas_limit: val.gas_limit,
            action: val.action,
            value: val.value,
            input: val.input,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Transaction {
    pub nonce: U256,
    pub gas_price: Gas,
    pub gas_limit: Gas,
    pub action: TransactionAction,
    pub value: U256,
    pub signature: TransactionSignature,
    pub input: Vec<u8>, // The input data, either data or init, depending on TransactionAction.
}

impl Transaction {
    pub fn caller(&self) -> Result<Address, Error> {
        let unsigned = UnsignedTransaction::from((*self).clone());
        let hash = unsigned.signing_hash(self.signature.chain_id());
        let sig = self.signature.to_recoverable_signature()?;
        let public_key = {
            #[cfg(feature = "c-secp256k1")]
            { SECP256K1.recover(&Message::from_slice(&hash).unwrap(), &sig)? }
            #[cfg(feature = "rust-secp256k1")]
            { let mut a = [0u8; 32];
              for i in 0..32 {
                  a[i] = hash[i];
              }
              secp256k1::recover(&Message::parse(&a), &sig.0, &sig.1)?
            }
        };

        Ok(Address::from_public_key(&public_key))
    }

    pub fn address(&self) -> Result<Address, Error> {
        Ok(self.action.address(self.caller()?, self.nonce))
    }

    pub fn is_basic_valid<P: SignaturePatch, Q: ValidationPatch>(&self) -> bool {
        if !self.signature.is_valid() {
            return false;
        }

        if self.signature.chain_id().is_some() && self.signature.chain_id() != P::chain_id() {
            return false;
        }

        if self.caller().is_err() {
            return false;
        }

        if Q::require_low_s() && !self.signature.is_low_s() {
            return false;
        }

        return true;
    }
}

impl Encodable for Transaction {
    fn rlp_append(&self, s: &mut RlpStream) {
        s.begin_list(9);
        s.append(&self.nonce);
        s.append(&self.gas_price);
        s.append(&self.gas_limit);
        s.append(&self.action);
        s.append(&self.value);
        s.append(&self.input);
        s.append(&self.signature.v);
        s.append(&self.signature.r);
        s.append(&self.signature.s);
    }
}

impl Decodable for Transaction {
    fn decode(rlp: &UntrustedRlp) -> Result<Self, DecoderError> {
        Ok(Self {
            nonce: rlp.val_at(0)?,
            gas_price: rlp.val_at(1)?,
            gas_limit: rlp.val_at(2)?,
            action: rlp.val_at(3)?,
            value: rlp.val_at(4)?,
            input: rlp.val_at(5)?,
            signature: TransactionSignature {
                v: rlp.val_at(6)?,
                r: rlp.val_at(7)?,
                s: rlp.val_at(8)?,
            },
        })
    }
}

impl RlpHash for Transaction {
    fn rlp_hash(&self) -> H256 {
        H256::from(Keccak256::digest(&rlp::encode(self)).as_slice())
    }
}

#[cfg(test)]
mod tests {
    use secp256k1::{SecretKey, PublicKey, Message, Signature, RecoveryId};
    use rlp::{self, Encodable, Decodable, RlpStream, DecoderError, UntrustedRlp};
    use bigint::{Address, Gas, H256, U256, B256};
    use sha3::{Digest, Keccak256};
    use address::FromKey;
    use rand::os::OsRng;
    use super::{Transaction, UnsignedTransaction, TransactionAction, ClassicSignaturePatch,
                HomesteadValidationPatch};

    #[test]
    pub fn should_recover_address() {
        let mut rng = OsRng::new().unwrap();
        let secret_key = SecretKey::random(&mut rng);
        let address = Address::from_secret_key(&secret_key);

        let unsigned = UnsignedTransaction {
            nonce: U256::zero(),
            gas_price: Gas::zero(),
            gas_limit: Gas::zero(),
            action: TransactionAction::Create,
            value: U256::zero(),
            input: Vec::new()
        };
        let signed = unsigned.sign::<ClassicSignaturePatch>(&secret_key);

        assert_eq!(signed.signature.chain_id(), Some(61));
        assert!(signed.is_basic_valid::<ClassicSignaturePatch, HomesteadValidationPatch>());
        assert_eq!(signed.caller(), address);
    }
}