Skip to main content

revm_precompile/
bn254.rs

1//! BN254 precompiles added in [`EIP-1962`](https://eips.ethereum.org/EIPS/eip-1962)
2use crate::{
3    crypto, eth_precompile_fn,
4    utilities::{bool_to_bytes32, right_pad},
5    Address, EthPrecompileOutput, EthPrecompileResult, Precompile, PrecompileHalt, PrecompileId,
6};
7use std::vec::Vec;
8
9#[cfg_attr(feature = "bn", expect(dead_code))]
10pub mod arkworks;
11
12cfg_if::cfg_if! {
13    if #[cfg(feature = "bn")]{
14        pub(crate) mod substrate;
15        pub(crate) use substrate as crypto_backend;
16    } else {
17        pub(crate) use arkworks as crypto_backend;
18    }
19}
20
21/// Bn254 add precompile
22pub mod add {
23    use super::*;
24
25    /// Bn254 add precompile address
26    pub const ADDRESS: Address = crate::u64_to_address(6);
27
28    /// Bn254 add precompile with ISTANBUL gas rules
29    pub const ISTANBUL_ADD_GAS_COST: u64 = 150;
30
31    /// Bn254 add precompile with ISTANBUL gas rules
32    pub const ISTANBUL: Precompile = Precompile::new(PrecompileId::Bn254Add, ADDRESS, istanbul_add);
33
34    /// Bn254 add precompile with BYZANTIUM gas rules
35    pub const BYZANTIUM_ADD_GAS_COST: u64 = 500;
36
37    /// Bn254 add precompile with BYZANTIUM gas rules
38    pub const BYZANTIUM: Precompile =
39        Precompile::new(PrecompileId::Bn254Add, ADDRESS, byzantium_add);
40
41    eth_precompile_fn!(istanbul_add, |i, g| run_add(i, ISTANBUL_ADD_GAS_COST, g));
42    eth_precompile_fn!(byzantium_add, |i, g| run_add(i, BYZANTIUM_ADD_GAS_COST, g));
43}
44
45/// Bn254 mul precompile
46pub mod mul {
47    use super::*;
48
49    /// Bn254 mul precompile address
50    pub const ADDRESS: Address = crate::u64_to_address(7);
51
52    /// Bn254 mul precompile with ISTANBUL gas rules
53    pub const ISTANBUL_MUL_GAS_COST: u64 = 6_000;
54
55    /// Bn254 mul precompile with ISTANBUL gas rules
56    pub const ISTANBUL: Precompile = Precompile::new(PrecompileId::Bn254Mul, ADDRESS, istanbul_mul);
57
58    /// Bn254 mul precompile with BYZANTIUM gas rules
59    pub const BYZANTIUM_MUL_GAS_COST: u64 = 40_000;
60
61    /// Bn254 mul precompile with BYZANTIUM gas rules
62    pub const BYZANTIUM: Precompile =
63        Precompile::new(PrecompileId::Bn254Mul, ADDRESS, byzantium_mul);
64
65    eth_precompile_fn!(istanbul_mul, |i, g| run_mul(i, ISTANBUL_MUL_GAS_COST, g));
66    eth_precompile_fn!(byzantium_mul, |i, g| run_mul(i, BYZANTIUM_MUL_GAS_COST, g));
67}
68
69/// Bn254 pair precompile
70pub mod pair {
71    use super::*;
72
73    /// Bn254 pair precompile address
74    pub const ADDRESS: Address = crate::u64_to_address(8);
75
76    /// Bn254 pair precompile with ISTANBUL gas rules
77    pub const ISTANBUL_PAIR_PER_POINT: u64 = 34_000;
78
79    /// Bn254 pair precompile with ISTANBUL gas rules
80    pub const ISTANBUL_PAIR_BASE: u64 = 45_000;
81
82    /// Bn254 pair precompile with ISTANBUL gas rules
83    pub const ISTANBUL: Precompile =
84        Precompile::new(PrecompileId::Bn254Pairing, ADDRESS, istanbul_pair);
85
86    /// Bn254 pair precompile with BYZANTIUM gas rules
87    pub const BYZANTIUM_PAIR_PER_POINT: u64 = 80_000;
88
89    /// Bn254 pair precompile with BYZANTIUM gas rules
90    pub const BYZANTIUM_PAIR_BASE: u64 = 100_000;
91
92    /// Bn254 pair precompile with BYZANTIUM gas rules
93    pub const BYZANTIUM: Precompile =
94        Precompile::new(PrecompileId::Bn254Pairing, ADDRESS, byzantium_pair);
95
96    eth_precompile_fn!(istanbul_pair, |i, g| run_pair(
97        i,
98        ISTANBUL_PAIR_PER_POINT,
99        ISTANBUL_PAIR_BASE,
100        g
101    ));
102    eth_precompile_fn!(byzantium_pair, |i, g| run_pair(
103        i,
104        BYZANTIUM_PAIR_PER_POINT,
105        BYZANTIUM_PAIR_BASE,
106        g
107    ));
108}
109
110/// FQ_LEN specifies the number of bytes needed to represent an
111/// Fq element. This is an element in the base field of BN254.
112///
113/// Note: The base field is used to define G1 and G2 elements.
114const FQ_LEN: usize = 32;
115
116/// SCALAR_LEN specifies the number of bytes needed to represent an Fr element.
117/// This is an element in the scalar field of BN254.
118const SCALAR_LEN: usize = 32;
119
120/// FQ2_LEN specifies the number of bytes needed to represent an
121/// Fq^2 element.
122///
123/// Note: This is the quadratic extension of Fq, and by definition
124/// means we need 2 Fq elements.
125const FQ2_LEN: usize = 2 * FQ_LEN;
126
127/// G1_LEN specifies the number of bytes needed to represent a G1 element.
128///
129/// Note: A G1 element contains 2 Fq elements.
130const G1_LEN: usize = 2 * FQ_LEN;
131/// G2_LEN specifies the number of bytes needed to represent a G2 element.
132///
133/// Note: A G2 element contains 2 Fq^2 elements.
134const G2_LEN: usize = 2 * FQ2_LEN;
135
136/// Input length for the add operation.
137/// `ADD` takes two uncompressed G1 points (64 bytes each).
138pub const ADD_INPUT_LEN: usize = 2 * G1_LEN;
139
140/// Input length for the multiplication operation.
141/// `MUL` takes an uncompressed G1 point (64 bytes) and scalar (32 bytes).
142pub const MUL_INPUT_LEN: usize = G1_LEN + SCALAR_LEN;
143
144/// Pair element length.
145/// `PAIR` elements are composed of an uncompressed G1 point (64 bytes) and an uncompressed G2 point
146/// (128 bytes).
147pub const PAIR_ELEMENT_LEN: usize = G1_LEN + G2_LEN;
148
149/// Run the Bn254 add precompile
150pub fn run_add(input: &[u8], gas_cost: u64, gas_limit: u64) -> EthPrecompileResult {
151    if gas_cost > gas_limit {
152        return Err(PrecompileHalt::OutOfGas);
153    }
154
155    let input = right_pad::<ADD_INPUT_LEN>(input);
156
157    let p1_bytes = &input[..G1_LEN];
158    let p2_bytes = &input[G1_LEN..];
159    let output = crypto().bn254_g1_add(p1_bytes, p2_bytes)?;
160
161    Ok(EthPrecompileOutput::new(gas_cost, output.into()))
162}
163
164/// Run the Bn254 mul precompile
165pub fn run_mul(input: &[u8], gas_cost: u64, gas_limit: u64) -> EthPrecompileResult {
166    if gas_cost > gas_limit {
167        return Err(PrecompileHalt::OutOfGas);
168    }
169
170    let input = right_pad::<MUL_INPUT_LEN>(input);
171
172    let point_bytes = &input[..G1_LEN];
173    let scalar_bytes = &input[G1_LEN..G1_LEN + SCALAR_LEN];
174    let output = crypto().bn254_g1_mul(point_bytes, scalar_bytes)?;
175
176    Ok(EthPrecompileOutput::new(gas_cost, output.into()))
177}
178
179/// Run the Bn254 pair precompile
180pub fn run_pair(
181    input: &[u8],
182    pair_per_point_cost: u64,
183    pair_base_cost: u64,
184    gas_limit: u64,
185) -> EthPrecompileResult {
186    let gas_used = (input.len() / PAIR_ELEMENT_LEN) as u64 * pair_per_point_cost + pair_base_cost;
187    if gas_used > gas_limit {
188        return Err(PrecompileHalt::OutOfGas);
189    }
190
191    if !input.len().is_multiple_of(PAIR_ELEMENT_LEN) {
192        return Err(PrecompileHalt::Bn254PairLength);
193    }
194
195    let elements = input.len() / PAIR_ELEMENT_LEN;
196
197    let mut points = Vec::with_capacity(elements);
198
199    for pair in input.chunks_exact(PAIR_ELEMENT_LEN) {
200        let (encoded_g1_element, encoded_g2_element) = pair.split_at(G1_LEN);
201        points.push((encoded_g1_element, encoded_g2_element));
202    }
203
204    let pairing_result = crypto().bn254_pairing_check(&points)?;
205    Ok(EthPrecompileOutput::new(
206        gas_used,
207        bool_to_bytes32(pairing_result),
208    ))
209}
210
211#[cfg(test)]
212mod tests {
213    use crate::{
214        bn254::{
215            add::BYZANTIUM_ADD_GAS_COST,
216            mul::BYZANTIUM_MUL_GAS_COST,
217            pair::{BYZANTIUM_PAIR_BASE, BYZANTIUM_PAIR_PER_POINT},
218        },
219        PrecompileHalt,
220    };
221    use primitives::hex;
222
223    use super::*;
224
225    #[test]
226    fn test_bn254_add() {
227        let input = hex::decode(
228            "\
229             18b18acfb4c2c30276db5411368e7185b311dd124691610c5d3b74034e093dc9\
230             063c909c4720840cb5134cb9f59fa749755796819658d32efc0d288198f37266\
231             07c2b7f58a84bd6145f00c9c2bc0bb1a187f20ff2c92963a88019e7c6a014eed\
232             06614e20c147e940f2d70da3f74c9a17df361706a4485c742bd6788478fa17d7",
233        )
234        .unwrap();
235        let expected = hex::decode(
236            "\
237            2243525c5efd4b9c3d3c45ac0ca3fe4dd85e830a4ce6b65fa1eeaee202839703\
238            301d1d33be6da8e509df21cc35964723180eed7532537db9ae5e7d48f195c915",
239        )
240        .unwrap();
241
242        let outcome = run_add(&input, BYZANTIUM_ADD_GAS_COST, 500).unwrap();
243        assert_eq!(outcome.bytes, expected);
244
245        // Zero sum test
246        let input = hex::decode(
247            "\
248            0000000000000000000000000000000000000000000000000000000000000000\
249            0000000000000000000000000000000000000000000000000000000000000000\
250            0000000000000000000000000000000000000000000000000000000000000000\
251            0000000000000000000000000000000000000000000000000000000000000000",
252        )
253        .unwrap();
254        let expected = hex::decode(
255            "\
256            0000000000000000000000000000000000000000000000000000000000000000\
257            0000000000000000000000000000000000000000000000000000000000000000",
258        )
259        .unwrap();
260
261        let outcome = run_add(&input, BYZANTIUM_ADD_GAS_COST, 500).unwrap();
262        assert_eq!(outcome.bytes, expected);
263
264        // Out of gas test
265        let input = hex::decode(
266            "\
267            0000000000000000000000000000000000000000000000000000000000000000\
268            0000000000000000000000000000000000000000000000000000000000000000\
269            0000000000000000000000000000000000000000000000000000000000000000\
270            0000000000000000000000000000000000000000000000000000000000000000",
271        )
272        .unwrap();
273
274        let res = run_add(&input, BYZANTIUM_ADD_GAS_COST, 499);
275
276        assert!(matches!(res, Err(PrecompileHalt::OutOfGas)));
277
278        // No input test
279        let input = [0u8; 0];
280        let expected = hex::decode(
281            "\
282            0000000000000000000000000000000000000000000000000000000000000000\
283            0000000000000000000000000000000000000000000000000000000000000000",
284        )
285        .unwrap();
286
287        let outcome = run_add(&input, BYZANTIUM_ADD_GAS_COST, 500).unwrap();
288        assert_eq!(outcome.bytes, expected);
289
290        // Point not on curve fail
291        let input = hex::decode(
292            "\
293            1111111111111111111111111111111111111111111111111111111111111111\
294            1111111111111111111111111111111111111111111111111111111111111111\
295            1111111111111111111111111111111111111111111111111111111111111111\
296            1111111111111111111111111111111111111111111111111111111111111111",
297        )
298        .unwrap();
299
300        let res = run_add(&input, BYZANTIUM_ADD_GAS_COST, 500);
301        assert!(matches!(
302            res,
303            Err(ref f) if *f == PrecompileHalt::Bn254AffineGFailedToCreate
304        ));
305    }
306
307    #[test]
308    fn test_bn254_mul() {
309        let input = hex::decode(
310            "\
311            2bd3e6d0f3b142924f5ca7b49ce5b9d54c4703d7ae5648e61d02268b1a0a9fb7\
312            21611ce0a6af85915e2f1d70300909ce2e49dfad4a4619c8390cae66cefdb204\
313            00000000000000000000000000000000000000000000000011138ce750fa15c2",
314        )
315        .unwrap();
316        let expected = hex::decode(
317            "\
318            070a8d6a982153cae4be29d434e8faef8a47b274a053f5a4ee2a6c9c13c31e5c\
319            031b8ce914eba3a9ffb989f9cdd5b0f01943074bf4f0f315690ec3cec6981afc",
320        )
321        .unwrap();
322
323        let outcome = run_mul(&input, BYZANTIUM_MUL_GAS_COST, 40_000).unwrap();
324        assert_eq!(outcome.bytes, expected);
325
326        // Out of gas test
327        let input = hex::decode(
328            "\
329            0000000000000000000000000000000000000000000000000000000000000000\
330            0000000000000000000000000000000000000000000000000000000000000000\
331            0200000000000000000000000000000000000000000000000000000000000000",
332        )
333        .unwrap();
334
335        let res = run_mul(&input, BYZANTIUM_MUL_GAS_COST, 39_999);
336        assert!(matches!(res, Err(PrecompileHalt::OutOfGas)));
337
338        // Zero multiplication test
339        let input = hex::decode(
340            "\
341            0000000000000000000000000000000000000000000000000000000000000000\
342            0000000000000000000000000000000000000000000000000000000000000000\
343            0200000000000000000000000000000000000000000000000000000000000000",
344        )
345        .unwrap();
346        let expected = hex::decode(
347            "\
348            0000000000000000000000000000000000000000000000000000000000000000\
349            0000000000000000000000000000000000000000000000000000000000000000",
350        )
351        .unwrap();
352
353        let outcome = run_mul(&input, BYZANTIUM_MUL_GAS_COST, 40_000).unwrap();
354        assert_eq!(outcome.bytes, expected);
355
356        // No input test
357        let input = [0u8; 0];
358        let expected = hex::decode(
359            "\
360            0000000000000000000000000000000000000000000000000000000000000000\
361            0000000000000000000000000000000000000000000000000000000000000000",
362        )
363        .unwrap();
364
365        let outcome = run_mul(&input, BYZANTIUM_MUL_GAS_COST, 40_000).unwrap();
366        assert_eq!(outcome.bytes, expected);
367
368        // Point not on curve fail
369        let input = hex::decode(
370            "\
371            1111111111111111111111111111111111111111111111111111111111111111\
372            1111111111111111111111111111111111111111111111111111111111111111\
373            0f00000000000000000000000000000000000000000000000000000000000000",
374        )
375        .unwrap();
376
377        let res = run_mul(&input, BYZANTIUM_MUL_GAS_COST, 40_000);
378        assert!(matches!(
379            res,
380            Err(ref f) if *f == PrecompileHalt::Bn254AffineGFailedToCreate
381        ));
382    }
383
384    #[test]
385    fn test_bn254_pair() {
386        let input = hex::decode(
387            "\
388            1c76476f4def4bb94541d57ebba1193381ffa7aa76ada664dd31c16024c43f59\
389            3034dd2920f673e204fee2811c678745fc819b55d3e9d294e45c9b03a76aef41\
390            209dd15ebff5d46c4bd888e51a93cf99a7329636c63514396b4a452003a35bf7\
391            04bf11ca01483bfa8b34b43561848d28905960114c8ac04049af4b6315a41678\
392            2bb8324af6cfc93537a2ad1a445cfd0ca2a71acd7ac41fadbf933c2a51be344d\
393            120a2a4cf30c1bf9845f20c6fe39e07ea2cce61f0c9bb048165fe5e4de877550\
394            111e129f1cf1097710d41c4ac70fcdfa5ba2023c6ff1cbeac322de49d1b6df7c\
395            2032c61a830e3c17286de9462bf242fca2883585b93870a73853face6a6bf411\
396            198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2\
397            1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed\
398            090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b\
399            12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa",
400        )
401        .unwrap();
402        let expected =
403            hex::decode("0000000000000000000000000000000000000000000000000000000000000001")
404                .unwrap();
405
406        let outcome = run_pair(
407            &input,
408            BYZANTIUM_PAIR_PER_POINT,
409            BYZANTIUM_PAIR_BASE,
410            260_000,
411        )
412        .unwrap();
413        assert_eq!(outcome.bytes, expected);
414
415        // Out of gas test
416        let input = hex::decode(
417            "\
418            1c76476f4def4bb94541d57ebba1193381ffa7aa76ada664dd31c16024c43f59\
419            3034dd2920f673e204fee2811c678745fc819b55d3e9d294e45c9b03a76aef41\
420            209dd15ebff5d46c4bd888e51a93cf99a7329636c63514396b4a452003a35bf7\
421            04bf11ca01483bfa8b34b43561848d28905960114c8ac04049af4b6315a41678\
422            2bb8324af6cfc93537a2ad1a445cfd0ca2a71acd7ac41fadbf933c2a51be344d\
423            120a2a4cf30c1bf9845f20c6fe39e07ea2cce61f0c9bb048165fe5e4de877550\
424            111e129f1cf1097710d41c4ac70fcdfa5ba2023c6ff1cbeac322de49d1b6df7c\
425            2032c61a830e3c17286de9462bf242fca2883585b93870a73853face6a6bf411\
426            198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2\
427            1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed\
428            090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b\
429            12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa",
430        )
431        .unwrap();
432
433        let res = run_pair(
434            &input,
435            BYZANTIUM_PAIR_PER_POINT,
436            BYZANTIUM_PAIR_BASE,
437            259_999,
438        );
439        assert!(matches!(res, Err(PrecompileHalt::OutOfGas)));
440
441        // No input test
442        let input = [0u8; 0];
443        let expected =
444            hex::decode("0000000000000000000000000000000000000000000000000000000000000001")
445                .unwrap();
446
447        let outcome = run_pair(
448            &input,
449            BYZANTIUM_PAIR_PER_POINT,
450            BYZANTIUM_PAIR_BASE,
451            260_000,
452        )
453        .unwrap();
454        assert_eq!(outcome.bytes, expected);
455
456        // Point not on curve fail
457        let input = hex::decode(
458            "\
459            1111111111111111111111111111111111111111111111111111111111111111\
460            1111111111111111111111111111111111111111111111111111111111111111\
461            1111111111111111111111111111111111111111111111111111111111111111\
462            1111111111111111111111111111111111111111111111111111111111111111\
463            1111111111111111111111111111111111111111111111111111111111111111\
464            1111111111111111111111111111111111111111111111111111111111111111",
465        )
466        .unwrap();
467
468        let res = run_pair(
469            &input,
470            BYZANTIUM_PAIR_PER_POINT,
471            BYZANTIUM_PAIR_BASE,
472            260_000,
473        );
474        assert!(matches!(
475            res,
476            Err(ref f) if *f == PrecompileHalt::Bn254AffineGFailedToCreate
477        ));
478
479        // Invalid input length
480        let input = hex::decode(
481            "\
482            1111111111111111111111111111111111111111111111111111111111111111\
483            1111111111111111111111111111111111111111111111111111111111111111\
484            111111111111111111111111111111\
485        ",
486        )
487        .unwrap();
488
489        let res = run_pair(
490            &input,
491            BYZANTIUM_PAIR_PER_POINT,
492            BYZANTIUM_PAIR_BASE,
493            260_000,
494        );
495        assert!(matches!(res, Err(PrecompileHalt::Bn254PairLength)));
496
497        // Test with point at infinity - should return true (identity element)
498        // G1 point at infinity (0,0) followed by a valid G2 point
499        let input = hex::decode(
500            "\
501            0000000000000000000000000000000000000000000000000000000000000000\
502            0000000000000000000000000000000000000000000000000000000000000000\
503            209dd15ebff5d46c4bd888e51a93cf99a7329636c63514396b4a452003a35bf7\
504            04bf11ca01483bfa8b34b43561848d28905960114c8ac04049af4b6315a41678\
505            2bb8324af6cfc93537a2ad1a445cfd0ca2a71acd7ac41fadbf933c2a51be344d\
506            120a2a4cf30c1bf9845f20c6fe39e07ea2cce61f0c9bb048165fe5e4de877550",
507        )
508        .unwrap();
509        let expected =
510            hex::decode("0000000000000000000000000000000000000000000000000000000000000001")
511                .unwrap();
512
513        let outcome = run_pair(
514            &input,
515            BYZANTIUM_PAIR_PER_POINT,
516            BYZANTIUM_PAIR_BASE,
517            260_000,
518        )
519        .unwrap();
520        assert_eq!(outcome.bytes, expected);
521
522        // Test with G2 point at infinity - should also return true
523        // Valid G1 point followed by G2 point at infinity (0,0,0,0)
524        let input = hex::decode(
525            "\
526            1c76476f4def4bb94541d57ebba1193381ffa7aa76ada664dd31c16024c43f59\
527            3034dd2920f673e204fee2811c678745fc819b55d3e9d294e45c9b03a76aef41\
528            0000000000000000000000000000000000000000000000000000000000000000\
529            0000000000000000000000000000000000000000000000000000000000000000\
530            0000000000000000000000000000000000000000000000000000000000000000\
531            0000000000000000000000000000000000000000000000000000000000000000",
532        )
533        .unwrap();
534
535        let outcome = run_pair(
536            &input,
537            BYZANTIUM_PAIR_PER_POINT,
538            BYZANTIUM_PAIR_BASE,
539            260_000,
540        )
541        .unwrap();
542        assert_eq!(outcome.bytes, expected);
543    }
544}