ethdos-fold/src/signature.rs
src/signature.rsRaw
1//! This file is just some helper methods on top of https://github.com/kilic/arkeddsa in order to
2//! use the Signature and PublicKey as ExternalInputs in the FCircuit.
3use ark_crypto_primitives::sponge::{
4 poseidon::{PoseidonConfig, PoseidonSponge},
5 Absorb, CryptographicSponge,
6};
7use ark_ec::{AffineRepr, CurveGroup};
8use ark_ff::{BigInteger, PrimeField};
9use ark_r1cs_std::alloc::{AllocVar, AllocationMode};
10use ark_r1cs_std::boolean::Boolean;
11use ark_r1cs_std::prelude::CurveVar;
12use ark_relations::r1cs::{Namespace, SynthesisError};
13use ark_serialize::CanonicalSerialize;
14use ark_std::{rand::Rng, Zero};
15use core::borrow::Borrow;
16use rand_core::CryptoRngCore;
17use std::fmt::Debug;
18
19use arkeddsa::{signature::Signature, PublicKey, SigningKey};
20
21use crate::fcircuit::CF;
22
23// recall, here C = ed_on_bn254, so C::BaseField = BN254::ScalarField
24#[derive(Clone, Copy, Debug, PartialEq)]
25pub struct SigPk<C: CurveGroup> {
26 pub pk: PublicKey<C>,
27 pub sig: Signature<C>,
28}
29impl<C: CurveGroup> Default for SigPk<C> {
30 fn default() -> Self {
31 Self {
32 pk: PublicKey(C::zero().into_affine()),
33 sig: Signature::new(C::zero().into_affine(), C::ScalarField::zero()),
34 }
35 }
36}
37impl<C: CurveGroup> SigPk<C> {
38 pub fn to_bytes(self) -> Vec<u8> {
39 let sig_bytes = self.sig.to_bytes();
40 let pk_bytes = self.pk.to_bytes();
41 [sig_bytes, pk_bytes].concat()
42 }
43 pub fn from_bytes(b: Vec<u8>) -> Self {
44 let u_point_size = C::Affine::generator().serialized_size(ark_serialize::Compress::No);
45
46 let sig = Signature::<C>::from_bytes(&b[..32 + u_point_size]).unwrap();
47 let pk = PublicKey::<C>::from_bytes(&b[32 + u_point_size..]).unwrap();
48 Self { pk, sig }
49 }
50}
51
52#[derive(Clone, Debug)]
53pub struct SigPkVar<C: CurveGroup, GC: CurveVar<C, CF<C>>> {
54 pub pk: GC,
55 pub sig_r: GC,
56 pub sig_s: Vec<Boolean<CF<C>>>,
57}
58impl<C: CurveGroup, GC: CurveVar<C, CF<C>>> Default for SigPkVar<C, GC> {
59 fn default() -> Self {
60 Self {
61 pk: GC::zero(),
62 sig_r: GC::zero(),
63 sig_s: vec![Boolean::<CF<C>>::FALSE; 253], // TODO 253-> fieldbitsize
64 }
65 }
66}
67
68impl<C, GC> AllocVar<SigPk<C>, CF<C>> for SigPkVar<C, GC>
69where
70 C: CurveGroup,
71 GC: CurveVar<C, CF<C>>,
72{
73 fn new_variable<T: Borrow<SigPk<C>>>(
74 cs: impl Into<Namespace<CF<C>>>,
75 f: impl FnOnce() -> Result<T, SynthesisError>,
76 mode: AllocationMode,
77 ) -> Result<Self, SynthesisError> {
78 f().and_then(|val| {
79 let cs = cs.into();
80
81 let e = val.borrow();
82 let pk = GC::new_variable(cs.clone(), || Ok(e.pk.0), mode)?;
83 let sig_r = GC::new_variable(cs.clone(), || Ok(e.sig.r), mode)?;
84 let sig_s = Vec::<Boolean<CF<C>>>::new_variable(
85 cs.clone(),
86 || Ok(e.sig.s.into_bigint().to_bits_le()),
87 mode,
88 )?;
89 let v = Self { pk, sig_r, sig_s };
90
91 Ok(v)
92 })
93 }
94}
95
96pub fn hash_pk<C: CurveGroup>(
97 poseidon_config: &PoseidonConfig<C::BaseField>,
98 pk: PublicKey<C>,
99) -> C::BaseField
100where
101 C::BaseField: PrimeField + Absorb,
102{
103 let mut poseidon = PoseidonSponge::new(poseidon_config);
104 let (pk_x, pk_y): (C::BaseField, C::BaseField) = pk.xy().unwrap();
105 poseidon.absorb(&vec![pk_x, pk_y]);
106 let k = poseidon.squeeze_field_elements::<C::BaseField>(1);
107 *k.first().unwrap()
108}
109
110// returns a vector of signatures & publickeys, where each signature is of the previous public key
111pub fn gen_signatures<R: Rng + CryptoRngCore, C: CurveGroup>(
112 rng: &mut R,
113 poseidon_config: &PoseidonConfig<C::BaseField>,
114 steps: usize,
115) -> Vec<SigPk<C>>
116where
117 C::BaseField: PrimeField + Absorb,
118{
119 let mut prev_pk = None;
120 let mut res: Vec<SigPk<C>> = Vec::new();
121 for _ in 0..steps {
122 let extinp = gen_sig(rng, poseidon_config, prev_pk);
123 res.push(extinp);
124 prev_pk = Some(extinp.pk);
125 }
126 res
127}
128
129// generates a new secret key, and signs the given `prev_pk` with it. If the `prev_pk==None`, it
130// will use the newly generated public key as the prev_pk.
131pub fn gen_sig<R: Rng + CryptoRngCore, C: CurveGroup>(
132 rng: &mut R,
133 poseidon_config: &PoseidonConfig<C::BaseField>,
134 prev_pk: Option<PublicKey<C>>,
135) -> SigPk<C>
136where
137 C::BaseField: PrimeField + Absorb,
138{
139 let sk = SigningKey::<C>::generate::<blake2::Blake2b512>(rng).unwrap();
140 let pk = sk.public_key();
141
142 // if prev_pk!=None, use it, else, set the new pk to it
143 let prev_pk = if let Some(v) = prev_pk { v } else { *pk };
144
145 let msg = hash_pk(poseidon_config, prev_pk);
146
147 let sig = sk
148 .sign::<blake2::Blake2b512>(poseidon_config, &msg)
149 .unwrap();
150 pk.verify(poseidon_config, &msg, &sig).unwrap();
151 SigPk { pk: *pk, sig }
152}