-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.rs
More file actions
269 lines (225 loc) · 9.03 KB
/
Copy pathmain.rs
File metadata and controls
269 lines (225 loc) · 9.03 KB
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
use ark_ec_vrfs::suites::bandersnatch::edwards as bandersnatch;
use ark_ec_vrfs::{prelude::ark_serialize, suites::bandersnatch::edwards::RingContext};
use bandersnatch::{IetfProof, Input, Output, Public, RingProof, Secret};
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
const RING_SIZE: usize = 1023;
// This is the IETF `Prove` procedure output as described in section 2.2
// of the Bandersnatch VRFs specification
#[derive(CanonicalSerialize, CanonicalDeserialize)]
struct IetfVrfSignature {
output: Output,
proof: IetfProof,
}
// This is the IETF `Prove` procedure output as described in section 4.2
// of the Bandersnatch VRFs specification
#[derive(CanonicalSerialize, CanonicalDeserialize)]
struct RingVrfSignature {
output: Output,
// This contains both the Pedersen proof and actual ring proof.
proof: RingProof,
}
// "Static" ring context data
fn ring_context() -> &'static RingContext {
use std::sync::OnceLock;
static RING_CTX: OnceLock<RingContext> = OnceLock::new();
RING_CTX.get_or_init(|| {
use bandersnatch::PcsParams;
use std::{fs::File, io::Read};
let manifest_dir =
std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is not set");
let filename = format!("{}/data/zcash-srs-2-11-uncompressed.bin", manifest_dir);
let mut file = File::open(filename).unwrap();
let mut buf = Vec::new();
file.read_to_end(&mut buf).unwrap();
let pcs_params = PcsParams::deserialize_uncompressed_unchecked(&mut &buf[..]).unwrap();
RingContext::from_srs(pcs_params, RING_SIZE).unwrap()
})
}
// Construct VRF Input Point from arbitrary data (section 1.2)
fn vrf_input_point(vrf_input_data: &[u8]) -> Input {
let point =
<bandersnatch::BandersnatchSha512Ell2 as ark_ec_vrfs::Suite>::data_to_point(vrf_input_data)
.unwrap();
Input::from(point)
}
// Prover actor.
struct Prover {
pub prover_idx: usize,
pub secret: Secret,
pub ring: Vec<Public>,
}
impl Prover {
pub fn new(ring: Vec<Public>, prover_idx: usize) -> Self {
Self {
prover_idx,
secret: Secret::from_seed(&prover_idx.to_le_bytes()),
ring,
}
}
/// Anonymous VRF signature.
///
/// Used for tickets submission.
pub fn ring_vrf_sign(&self, vrf_input_data: &[u8], aux_data: &[u8]) -> Vec<u8> {
use ark_ec_vrfs::ring::Prover as _;
let input = vrf_input_point(vrf_input_data);
let output = self.secret.output(input);
// Backend currently requires the wrapped type (plain affine points)
let pts: Vec<_> = self.ring.iter().map(|pk| pk.0).collect();
// Proof construction
let ring_ctx = ring_context();
let prover_key = ring_ctx.prover_key(&pts);
let prover = ring_ctx.prover(prover_key, self.prover_idx);
let proof = self.secret.prove(input, output, aux_data, &prover);
// Output and Ring Proof bundled together (as per section 2.2)
let signature = RingVrfSignature { output, proof };
let mut buf = Vec::new();
signature.serialize_compressed(&mut buf).unwrap();
buf
}
/// Non-Anonymous VRF signature.
///
/// Used for ticket claiming during block production.
/// Not used with Safrole test vectors.
pub fn ietf_vrf_sign(&self, vrf_input_data: &[u8], aux_data: &[u8]) -> Vec<u8> {
use ark_ec_vrfs::ietf::Prover as _;
let input = vrf_input_point(vrf_input_data);
let output = self.secret.output(input);
let proof = self.secret.prove(input, output, aux_data);
// Output and IETF Proof bundled together (as per section 2.2)
let signature = IetfVrfSignature { output, proof };
let mut buf = Vec::new();
signature.serialize_compressed(&mut buf).unwrap();
buf
}
}
type RingCommitment = ark_ec_vrfs::ring::RingCommitment<bandersnatch::BandersnatchSha512Ell2>;
// Verifier actor.
struct Verifier {
pub commitment: RingCommitment,
pub ring: Vec<Public>,
}
impl Verifier {
fn new(ring: Vec<Public>) -> Self {
// Backend currently requires the wrapped type (plain affine points)
let pts: Vec<_> = ring.iter().map(|pk| pk.0).collect();
let verifier_key = ring_context().verifier_key(&pts);
let commitment = verifier_key.commitment();
Self { ring, commitment }
}
/// Anonymous VRF signature verification.
///
/// Used for tickets verification.
///
/// On success returns the VRF output hash.
pub fn ring_vrf_verify(
&self,
vrf_input_data: &[u8],
aux_data: &[u8],
signature: &[u8],
) -> Result<[u8; 32], ()> {
use ark_ec_vrfs::ring::prelude::fflonk::pcs::PcsParams;
use ark_ec_vrfs::ring::Verifier as _;
use bandersnatch::VerifierKey;
let signature = RingVrfSignature::deserialize_compressed(signature).unwrap();
let input = vrf_input_point(vrf_input_data);
let output = signature.output;
let ring_ctx = ring_context();
// The verifier key is reconstructed from the commitment and the constant
// verifier key component of the SRS in order to verify some proof.
// As an alternative we can construct the verifier key using the
// RingContext::verifier_key() method, but is more expensive.
// In other words, we prefer computing the commitment once, when the keyset changes.
let verifier_key = VerifierKey::from_commitment_and_kzg_vk(
self.commitment.clone(),
ring_ctx.pcs_params.raw_vk(),
);
let verifier = ring_ctx.verifier(verifier_key);
if Public::verify(input, output, aux_data, &signature.proof, &verifier).is_err() {
println!("Ring signature verification failure");
return Err(());
}
println!("Ring signature verified");
// This truncated hash is the actual value used as ticket-id/score in JAM
let vrf_output_hash: [u8; 32] = output.hash()[..32].try_into().unwrap();
println!(" vrf-output-hash: {}", hex::encode(vrf_output_hash));
Ok(vrf_output_hash)
}
/// Non-Anonymous VRF signature verification.
///
/// Used for ticket claim verification during block import.
/// Not used with Safrole test vectors.
///
/// On success returns the VRF output hash.
pub fn ietf_vrf_verify(
&self,
vrf_input_data: &[u8],
aux_data: &[u8],
signature: &[u8],
signer_key_index: usize,
) -> Result<[u8; 32], ()> {
use ark_ec_vrfs::ietf::Verifier as _;
let signature = IetfVrfSignature::deserialize_compressed(signature).unwrap();
let input = vrf_input_point(vrf_input_data);
let output = signature.output;
let public = &self.ring[signer_key_index];
if public
.verify(input, output, aux_data, &signature.proof)
.is_err()
{
println!("Ring signature verification failure");
return Err(());
}
println!("Ietf signature verified");
// This is the actual value used as ticket-id/score
// NOTE: as far as vrf_input_data is the same, this matches the one produced
// using the ring-vrf (regardless of aux_data).
let vrf_output_hash: [u8; 32] = output.hash()[..32].try_into().unwrap();
println!(" vrf-output-hash: {}", hex::encode(vrf_output_hash));
Ok(vrf_output_hash)
}
}
macro_rules! measure_time {
($func_name:expr, $func_call:expr) => {{
let start = std::time::Instant::now();
let result = $func_call;
let duration = start.elapsed();
println!("* Time taken by {}: {:?}", $func_name, duration);
result
}};
}
fn main() {
let ring_set: Vec<_> = (0..RING_SIZE)
.map(|i| Secret::from_seed(&i.to_le_bytes()).public())
.collect();
let prover_key_index = 3;
let prover = Prover::new(ring_set.clone(), prover_key_index);
let verifier = Verifier::new(ring_set);
let vrf_input_data = b"foo";
//--- Anonymous VRF
let aux_data = b"bar";
// Prover signs some data.
let ring_signature = measure_time! {
"ring-vrf-sign",
prover.ring_vrf_sign(vrf_input_data, aux_data)
};
// Verifier checks it without knowing who is the signer.
let ring_vrf_output = measure_time! {
"ring-vrf-verify",
verifier.ring_vrf_verify(vrf_input_data, aux_data, &ring_signature).unwrap()
};
//--- Non anonymous VRF
let other_aux_data = b"hello";
// Prover signs the same vrf-input data (we want the output to match)
// But different aux data.
let ietf_signature = measure_time! {
"ietf-vrf-sign",
prover.ietf_vrf_sign(vrf_input_data, other_aux_data)
};
// Verifier checks the signature knowing the signer identity.
let ietf_vrf_output = measure_time! {
"ietf-vrf-verify",
verifier.ietf_vrf_verify(vrf_input_data, other_aux_data, &ietf_signature, prover_key_index).unwrap()
};
// Must match
assert_eq!(ring_vrf_output, ietf_vrf_output);
}