khodpay-signing 0.2.0

EVM signing: EIP-1559 transactions, EIP-712 typed data, and ERC-4337 UserOperation
Documentation
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! RLP encoding for EIP-1559 transactions.
//!
//! This module implements RLP (Recursive Length Prefix) encoding for
//! EIP-1559 transactions as specified in EIP-2718.

use crate::{AccessListItem, Address, Eip1559Transaction};
use primitive_types::U256;
use rlp::RlpStream;
use sha3::{Digest, Keccak256};

impl Eip1559Transaction {
    /// Encodes the unsigned transaction for signing.
    ///
    /// Returns `0x02 || rlp([chain_id, nonce, max_priority_fee_per_gas, max_fee_per_gas,
    /// gas_limit, to, value, data, access_list])`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use khodpay_signing::{Eip1559Transaction, ChainId, Wei};
    ///
    /// let tx = Eip1559Transaction::builder()
    ///     .chain_id(ChainId::BscMainnet)
    ///     .nonce(0)
    ///     .max_priority_fee_per_gas(Wei::from_gwei(1))
    ///     .max_fee_per_gas(Wei::from_gwei(5))
    ///     .gas_limit(21000)
    ///     .value(Wei::ZERO)
    ///     .build()
    ///     .unwrap();
    ///
    /// let encoded = tx.encode_unsigned();
    /// assert_eq!(encoded[0], 0x02); // EIP-1559 type prefix
    /// ```
    pub fn encode_unsigned(&self) -> Vec<u8> {
        let mut stream = RlpStream::new_list(9);

        // chain_id
        stream.append(&u64::from(self.chain_id));

        // nonce
        stream.append(&self.nonce);

        // max_priority_fee_per_gas
        append_u256(&mut stream, self.max_priority_fee_per_gas.as_u256());

        // max_fee_per_gas
        append_u256(&mut stream, self.max_fee_per_gas.as_u256());

        // gas_limit
        stream.append(&self.gas_limit);

        // to (address or empty for contract creation)
        match &self.to {
            Some(addr) => stream.append(&addr.as_bytes().as_slice()),
            None => stream.append_empty_data(),
        };

        // value
        append_u256(&mut stream, self.value.as_u256());

        // data
        stream.append(&self.data);

        // access_list
        encode_access_list(&mut stream, &self.access_list);

        // Prepend type byte (0x02 for EIP-1559)
        let mut encoded = vec![Self::TYPE];
        encoded.extend_from_slice(&stream.out());
        encoded
    }

    /// Computes the signing hash for this transaction.
    ///
    /// The signing hash is `keccak256(0x02 || rlp(unsigned_tx))`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use khodpay_signing::{Eip1559Transaction, ChainId, Wei};
    ///
    /// let tx = Eip1559Transaction::builder()
    ///     .chain_id(ChainId::BscMainnet)
    ///     .nonce(0)
    ///     .max_priority_fee_per_gas(Wei::from_gwei(1))
    ///     .max_fee_per_gas(Wei::from_gwei(5))
    ///     .gas_limit(21000)
    ///     .value(Wei::ZERO)
    ///     .build()
    ///     .unwrap();
    ///
    /// let hash = tx.signing_hash();
    /// assert_eq!(hash.len(), 32);
    /// ```
    pub fn signing_hash(&self) -> [u8; 32] {
        let encoded = self.encode_unsigned();
        let hash = Keccak256::digest(&encoded);
        let mut result = [0u8; 32];
        result.copy_from_slice(&hash);
        result
    }
}

/// Appends a U256 value to the RLP stream.
///
/// U256 values are encoded as big-endian bytes with leading zeros stripped.
fn append_u256(stream: &mut RlpStream, value: U256) {
    if value.is_zero() {
        stream.append_empty_data();
    } else {
        let mut bytes = [0u8; 32];
        value.to_big_endian(&mut bytes);
        // Find first non-zero byte
        let start = bytes.iter().position(|&b| b != 0).unwrap_or(32);
        stream.append(&&bytes[start..]);
    }
}

/// Encodes the access list into the RLP stream.
fn encode_access_list(stream: &mut RlpStream, access_list: &[AccessListItem]) {
    stream.begin_list(access_list.len());
    for item in access_list {
        stream.begin_list(2);
        stream.append(&item.address.as_bytes().as_slice());
        stream.begin_list(item.storage_keys.len());
        for key in &item.storage_keys {
            stream.append(&key.as_slice());
        }
    }
}

/// Helper to encode an address for RLP.
impl Address {
    /// Returns the RLP encoding of this address.
    pub fn rlp_bytes(&self) -> Vec<u8> {
        rlp::encode(&self.as_bytes().as_slice()).to_vec()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{AccessListItem, ChainId, Wei};

    fn test_address() -> Address {
        "0x742d35Cc6634C0532925a3b844Bc454e4438f44e"
            .parse()
            .unwrap()
    }

    // ==================== Encoding Tests ====================

    #[test]
    fn test_encode_unsigned_type_prefix() {
        let tx = Eip1559Transaction::builder()
            .chain_id(ChainId::BscMainnet)
            .nonce(0)
            .max_priority_fee_per_gas(Wei::from_gwei(1))
            .max_fee_per_gas(Wei::from_gwei(5))
            .gas_limit(21000)
            .build()
            .unwrap();

        let encoded = tx.encode_unsigned();
        assert_eq!(encoded[0], 0x02);
    }

    #[test]
    fn test_encode_unsigned_not_empty() {
        let tx = Eip1559Transaction::builder()
            .chain_id(ChainId::BscMainnet)
            .nonce(0)
            .max_priority_fee_per_gas(Wei::from_gwei(1))
            .max_fee_per_gas(Wei::from_gwei(5))
            .gas_limit(21000)
            .build()
            .unwrap();

        let encoded = tx.encode_unsigned();
        assert!(encoded.len() > 1);
    }

    #[test]
    fn test_encode_unsigned_deterministic() {
        let tx = Eip1559Transaction::builder()
            .chain_id(ChainId::BscMainnet)
            .nonce(0)
            .max_priority_fee_per_gas(Wei::from_gwei(1))
            .max_fee_per_gas(Wei::from_gwei(5))
            .gas_limit(21000)
            .build()
            .unwrap();

        let encoded1 = tx.encode_unsigned();
        let encoded2 = tx.encode_unsigned();
        assert_eq!(encoded1, encoded2);
    }

    #[test]
    fn test_encode_unsigned_with_recipient() {
        let tx = Eip1559Transaction::builder()
            .chain_id(ChainId::BscMainnet)
            .nonce(0)
            .max_priority_fee_per_gas(Wei::from_gwei(1))
            .max_fee_per_gas(Wei::from_gwei(5))
            .gas_limit(21000)
            .to(test_address())
            .value(Wei::from_ether(1))
            .build()
            .unwrap();

        let encoded = tx.encode_unsigned();
        assert_eq!(encoded[0], 0x02);
        assert!(encoded.len() > 20); // Should include address
    }

    #[test]
    fn test_encode_unsigned_with_data() {
        let tx = Eip1559Transaction::builder()
            .chain_id(ChainId::BscMainnet)
            .nonce(0)
            .max_priority_fee_per_gas(Wei::from_gwei(1))
            .max_fee_per_gas(Wei::from_gwei(5))
            .gas_limit(65000)
            .to(test_address())
            .data(vec![0xa9, 0x05, 0x9c, 0xbb]) // transfer selector
            .build()
            .unwrap();

        let encoded = tx.encode_unsigned();
        assert_eq!(encoded[0], 0x02);
    }

    #[test]
    fn test_encode_unsigned_with_access_list() {
        let item = AccessListItem::new(test_address(), vec![[1u8; 32]]);

        let tx = Eip1559Transaction::builder()
            .chain_id(ChainId::BscMainnet)
            .nonce(0)
            .max_priority_fee_per_gas(Wei::from_gwei(1))
            .max_fee_per_gas(Wei::from_gwei(5))
            .gas_limit(21000)
            .access_list(vec![item])
            .build()
            .unwrap();

        let encoded = tx.encode_unsigned();
        assert_eq!(encoded[0], 0x02);
    }

    #[test]
    fn test_encode_different_chain_ids() {
        let tx_bsc = Eip1559Transaction::builder()
            .chain_id(ChainId::BscMainnet)
            .nonce(0)
            .max_priority_fee_per_gas(Wei::from_gwei(1))
            .max_fee_per_gas(Wei::from_gwei(5))
            .gas_limit(21000)
            .build()
            .unwrap();

        let tx_testnet = Eip1559Transaction::builder()
            .chain_id(ChainId::BscTestnet)
            .nonce(0)
            .max_priority_fee_per_gas(Wei::from_gwei(1))
            .max_fee_per_gas(Wei::from_gwei(5))
            .gas_limit(21000)
            .build()
            .unwrap();

        let encoded_bsc = tx_bsc.encode_unsigned();
        let encoded_testnet = tx_testnet.encode_unsigned();

        // Different chain IDs should produce different encodings
        assert_ne!(encoded_bsc, encoded_testnet);
    }

    #[test]
    fn test_encode_different_nonces() {
        let tx1 = Eip1559Transaction::builder()
            .chain_id(ChainId::BscMainnet)
            .nonce(0)
            .max_priority_fee_per_gas(Wei::from_gwei(1))
            .max_fee_per_gas(Wei::from_gwei(5))
            .gas_limit(21000)
            .build()
            .unwrap();

        let tx2 = Eip1559Transaction::builder()
            .chain_id(ChainId::BscMainnet)
            .nonce(1)
            .max_priority_fee_per_gas(Wei::from_gwei(1))
            .max_fee_per_gas(Wei::from_gwei(5))
            .gas_limit(21000)
            .build()
            .unwrap();

        assert_ne!(tx1.encode_unsigned(), tx2.encode_unsigned());
    }

    // ==================== Signing Hash Tests ====================

    #[test]
    fn test_signing_hash_length() {
        let tx = Eip1559Transaction::builder()
            .chain_id(ChainId::BscMainnet)
            .nonce(0)
            .max_priority_fee_per_gas(Wei::from_gwei(1))
            .max_fee_per_gas(Wei::from_gwei(5))
            .gas_limit(21000)
            .build()
            .unwrap();

        let hash = tx.signing_hash();
        assert_eq!(hash.len(), 32);
    }

    #[test]
    fn test_signing_hash_deterministic() {
        let tx = Eip1559Transaction::builder()
            .chain_id(ChainId::BscMainnet)
            .nonce(0)
            .max_priority_fee_per_gas(Wei::from_gwei(1))
            .max_fee_per_gas(Wei::from_gwei(5))
            .gas_limit(21000)
            .build()
            .unwrap();

        let hash1 = tx.signing_hash();
        let hash2 = tx.signing_hash();
        assert_eq!(hash1, hash2);
    }

    #[test]
    fn test_signing_hash_different_for_different_tx() {
        let tx1 = Eip1559Transaction::builder()
            .chain_id(ChainId::BscMainnet)
            .nonce(0)
            .max_priority_fee_per_gas(Wei::from_gwei(1))
            .max_fee_per_gas(Wei::from_gwei(5))
            .gas_limit(21000)
            .build()
            .unwrap();

        let tx2 = Eip1559Transaction::builder()
            .chain_id(ChainId::BscMainnet)
            .nonce(1)
            .max_priority_fee_per_gas(Wei::from_gwei(1))
            .max_fee_per_gas(Wei::from_gwei(5))
            .gas_limit(21000)
            .build()
            .unwrap();

        assert_ne!(tx1.signing_hash(), tx2.signing_hash());
    }

    #[test]
    fn test_signing_hash_different_chains() {
        let tx_bsc = Eip1559Transaction::builder()
            .chain_id(ChainId::BscMainnet)
            .nonce(0)
            .max_priority_fee_per_gas(Wei::from_gwei(1))
            .max_fee_per_gas(Wei::from_gwei(5))
            .gas_limit(21000)
            .build()
            .unwrap();

        let tx_testnet = Eip1559Transaction::builder()
            .chain_id(ChainId::BscTestnet)
            .nonce(0)
            .max_priority_fee_per_gas(Wei::from_gwei(1))
            .max_fee_per_gas(Wei::from_gwei(5))
            .gas_limit(21000)
            .build()
            .unwrap();

        // Different chain IDs should produce different signing hashes
        // This is critical for replay protection
        assert_ne!(tx_bsc.signing_hash(), tx_testnet.signing_hash());
    }

    #[test]
    fn test_signing_hash_with_value() {
        let tx = Eip1559Transaction::builder()
            .chain_id(ChainId::BscMainnet)
            .nonce(0)
            .max_priority_fee_per_gas(Wei::from_gwei(1))
            .max_fee_per_gas(Wei::from_gwei(5))
            .gas_limit(21000)
            .to(test_address())
            .value(Wei::from_ether(1))
            .build()
            .unwrap();

        let hash = tx.signing_hash();
        assert_eq!(hash.len(), 32);
    }

    // ==================== Known Vector Test ====================

    #[test]
    fn test_encode_known_transaction() {
        // Test against a known EIP-1559 transaction encoding
        // This is a simple transfer on BSC mainnet
        let recipient: Address = "0x0000000000000000000000000000000000000001"
            .parse()
            .unwrap();

        let tx = Eip1559Transaction::builder()
            .chain_id(ChainId::BscMainnet) // 56
            .nonce(0)
            .max_priority_fee_per_gas(Wei::from_gwei(1))
            .max_fee_per_gas(Wei::from_gwei(5))
            .gas_limit(21000)
            .to(recipient)
            .value(Wei::from_wei(0u64))
            .build()
            .unwrap();

        let encoded = tx.encode_unsigned();

        // Verify structure:
        // - First byte is 0x02 (EIP-1559 type)
        // - Rest is RLP encoded list
        assert_eq!(encoded[0], 0x02);

        // The second byte should indicate an RLP list
        // For short lists, it's 0xc0 + length or 0xf7 + length_of_length
        assert!(encoded[1] >= 0xc0);
    }

    // ==================== U256 Encoding Tests ====================

    #[test]
    fn test_u256_zero_encoding() {
        let mut stream = RlpStream::new();
        append_u256(&mut stream, U256::zero());
        let encoded = stream.out();
        // Zero should be encoded as empty bytes (0x80)
        assert_eq!(encoded.as_ref(), &[0x80]);
    }

    #[test]
    fn test_u256_small_value_encoding() {
        let mut stream = RlpStream::new();
        append_u256(&mut stream, U256::from(127));
        let encoded = stream.out();
        // Small values (< 128) are encoded as single byte
        assert_eq!(encoded.as_ref(), &[127]);
    }

    #[test]
    fn test_u256_larger_value_encoding() {
        let mut stream = RlpStream::new();
        append_u256(&mut stream, U256::from(256));
        let encoded = stream.out();
        // 256 = 0x0100, encoded as 0x82 0x01 0x00
        assert_eq!(encoded.as_ref(), &[0x82, 0x01, 0x00]);
    }

    // ==================== Access List Encoding Tests ====================

    #[test]
    fn test_empty_access_list_encoding() {
        let mut stream = RlpStream::new();
        encode_access_list(&mut stream, &[]);
        let encoded = stream.out();
        // Empty list is 0xc0
        assert_eq!(encoded.as_ref(), &[0xc0]);
    }

    #[test]
    fn test_access_list_with_item() {
        let item = AccessListItem::address_only(test_address());
        let mut stream = RlpStream::new();
        encode_access_list(&mut stream, &[item]);
        let encoded = stream.out();
        // Should be a non-empty list
        assert!(encoded.len() > 1);
        assert!(encoded[0] >= 0xc0);
    }
}