zkutil/
utils.rs

1extern crate bellman_ce;
2extern crate rand;
3extern crate byteorder;
4extern crate num_bigint;
5extern crate num_traits;
6
7use std::fmt::Display;
8use itertools::Itertools;
9use num_bigint::BigUint;
10use num_traits::Num;
11use bellman_ce::{
12    groth16::Proof,
13    pairing::{
14        ff::PrimeField,
15        CurveAffine,
16        bn256::{
17            G1Affine,
18            G2Affine,
19            Fq12,
20            Bn256,
21        },
22    },
23};
24
25pub fn repr_to_big<T: Display>(r: T) -> String {
26    BigUint::from_str_radix(&format!("{}", r)[2..], 16).unwrap().to_str_radix(10)
27}
28
29pub fn repr_to_hex<T: Display>(r: T) -> String {
30    format!("{}", r)[2..].to_string()
31}
32
33pub fn proof_to_hex(proof: &Proof<Bn256>) -> String {
34    let a = proof.a.into_xy_unchecked();
35    let b = proof.b.into_xy_unchecked();
36    let c = proof.c.into_xy_unchecked();
37    [a.0, a.1, b.0.c1, b.0.c0, b.1.c1, b.1.c0, c.0, c.1]
38        .iter()
39        .map(|e| repr_to_hex(e.into_repr()))
40        .join("")
41}
42
43pub fn p1_to_vec(p: &G1Affine) -> Vec<String> {
44    let xy = p.into_xy_unchecked();
45    vec![
46        repr_to_big(xy.0.into_repr()),
47        repr_to_big(xy.1.into_repr()),
48        if p.is_zero() { "0".to_string() } else { "1".to_string() }
49    ]
50}
51
52pub fn p2_to_vec(p: &G2Affine) -> Vec<Vec<String>> {
53    let xy = p.into_xy_unchecked();
54    vec![
55        vec![
56            repr_to_big(xy.0.c0.into_repr()),
57            repr_to_big(xy.0.c1.into_repr()),
58        ],
59        vec![
60            repr_to_big(xy.1.c0.into_repr()),
61            repr_to_big(xy.1.c1.into_repr()),
62        ],
63        if p.is_zero() {
64            vec!["0".to_string(), "0".to_string()]
65        } else {
66            vec!["1".to_string(), "0".to_string()]
67        },
68    ]
69}
70
71pub fn pairing_to_vec(p: &Fq12) -> Vec<Vec<Vec<String>>> {
72    vec![
73        vec![
74            vec![
75                repr_to_big(p.c0.c0.c0.into_repr()),
76                repr_to_big(p.c0.c0.c1.into_repr()),
77            ],
78            vec![
79                repr_to_big(p.c0.c1.c0.into_repr()),
80                repr_to_big(p.c0.c1.c1.into_repr()),
81            ],
82            vec![
83                repr_to_big(p.c0.c2.c0.into_repr()),
84                repr_to_big(p.c0.c2.c1.into_repr()),
85            ],
86        ],
87        vec![
88            vec![
89                repr_to_big(p.c1.c0.c0.into_repr()),
90                repr_to_big(p.c1.c0.c1.into_repr()),
91            ],
92            vec![
93                repr_to_big(p.c1.c1.c0.into_repr()),
94                repr_to_big(p.c1.c1.c1.into_repr()),
95            ],
96            vec![
97                repr_to_big(p.c1.c2.c0.into_repr()),
98                repr_to_big(p.c1.c2.c1.into_repr()),
99            ],
100        ],
101    ]
102}