-
Notifications
You must be signed in to change notification settings - Fork 112
/
Copy pathtests.rs
238 lines (200 loc) · 7.56 KB
/
tests.rs
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
//! Tests for verifying simple Halo2 proofs with the async verifier
use std::future::ready;
use futures::stream::{FuturesUnordered, StreamExt};
use tower::ServiceExt;
use halo2::pasta::{group::ff::PrimeField, pallas};
use orchard::{
builder::Builder,
bundle::Flags,
circuit::ProvingKey,
keys::{FullViewingKey, Scope, SpendingKey},
value::NoteValue,
Anchor, Bundle,
};
use rand::rngs::OsRng;
use zebra_chain::{
orchard::ShieldedData,
serialization::{ZcashDeserializeInto, ZcashSerialize},
};
use crate::primitives::halo2::*;
#[allow(dead_code, clippy::print_stdout)]
fn generate_test_vectors() {
let proving_key = ProvingKey::build();
let rng = OsRng;
let sk = SpendingKey::from_bytes([7; 32]).unwrap();
let recipient = FullViewingKey::from(&sk).address_at(0u32, Scope::External);
let enable_spends = true;
let enable_outputs = true;
let flags =
zebra_chain::orchard::Flags::ENABLE_SPENDS | zebra_chain::orchard::Flags::ENABLE_OUTPUTS;
let anchor_bytes = [0; 32];
let note_value = 10;
let shielded_data: Vec<zebra_chain::orchard::ShieldedData> = (1..=4)
.map(|num_recipients| {
let mut builder = Builder::new(
Flags::from_parts(enable_spends, enable_outputs),
Anchor::from_bytes(anchor_bytes).unwrap(),
);
for _ in 0..num_recipients {
builder
.add_recipient(None, recipient, NoteValue::from_raw(note_value), None)
.unwrap();
}
let bundle: Bundle<_, i64> = builder.build(rng).unwrap();
let bundle = bundle
.create_proof(&proving_key, rng)
.unwrap()
.apply_signatures(rng, [0; 32], &[])
.unwrap();
zebra_chain::orchard::ShieldedData {
flags,
value_balance: note_value.try_into().unwrap(),
shared_anchor: anchor_bytes.try_into().unwrap(),
proof: zebra_chain::primitives::Halo2Proof(
bundle.authorization().proof().as_ref().into(),
),
actions: bundle
.actions()
.iter()
.map(|a| {
let action = zebra_chain::orchard::Action {
cv: a.cv_net().to_bytes().try_into().unwrap(),
nullifier: a.nullifier().to_bytes().try_into().unwrap(),
rk: <[u8; 32]>::from(a.rk()).try_into().unwrap(),
cm_x: pallas::Base::from_repr(a.cmx().into()).unwrap(),
ephemeral_key: a.encrypted_note().epk_bytes.try_into().unwrap(),
enc_ciphertext: a.encrypted_note().enc_ciphertext.into(),
out_ciphertext: a.encrypted_note().out_ciphertext.into(),
};
zebra_chain::orchard::shielded_data::AuthorizedAction {
action,
spend_auth_sig: <[u8; 64]>::from(a.authorization()).into(),
}
})
.collect::<Vec<_>>()
.try_into()
.unwrap(),
binding_sig: <[u8; 64]>::from(bundle.authorization().binding_signature())
.try_into()
.unwrap(),
}
})
.collect();
for sd in shielded_data {
println!(
"{}",
hex::encode(sd.clone().zcash_serialize_to_vec().unwrap())
);
}
}
async fn verify_orchard_halo2_proofs<V>(
verifier: &mut V,
shielded_data: Vec<ShieldedData>,
) -> Result<(), V::Error>
where
V: tower::Service<Item, Response = ()>,
<V as tower::Service<Item>>::Error: From<tower::BoxError> + std::fmt::Debug,
{
let mut async_checks = FuturesUnordered::new();
for sd in shielded_data {
tracing::trace!(?sd);
let rsp = verifier.ready().await?.call(Item::from(&sd));
async_checks.push(rsp);
}
while let Some(result) = async_checks.next().await {
tracing::trace!(?result);
result?;
}
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
// TODO: This test fails on nightly so it is temporally disabled. Enable when #6232 is resolved.
#[ignore]
async fn verify_generated_halo2_proofs() {
let _init_guard = zebra_test::init();
// These test vectors are generated by `generate_test_vectors()` function.
let shielded_data = zebra_test::vectors::ORCHARD_SHIELDED_DATA
.clone()
.iter()
.map(|bytes| {
let maybe_shielded_data: Option<zebra_chain::orchard::ShieldedData> = bytes
.zcash_deserialize_into()
.expect("a valid orchard::ShieldedData instance");
maybe_shielded_data.unwrap()
})
.collect();
// Use separate verifier so shared batch tasks aren't killed when the test ends (#2390)
let mut verifier = Fallback::new(
Batch::new(
Verifier::new(&VERIFYING_KEY),
crate::primitives::MAX_BATCH_SIZE,
None,
crate::primitives::MAX_BATCH_LATENCY,
),
tower::service_fn(
(|item: Item| ready(item.verify_single(&VERIFYING_KEY).map_err(Halo2Error::from)))
as fn(_) -> _,
),
);
// This should fail if any of the proofs fail to validate.
assert!(verify_orchard_halo2_proofs(&mut verifier, shielded_data)
.await
.is_ok());
}
async fn verify_invalid_orchard_halo2_proofs<V>(
verifier: &mut V,
shielded_data: Vec<ShieldedData>,
) -> Result<(), V::Error>
where
V: tower::Service<Item, Response = ()>,
<V as tower::Service<Item>>::Error: From<tower::BoxError> + std::fmt::Debug,
{
let mut async_checks = FuturesUnordered::new();
for sd in shielded_data {
let mut sd = sd.clone();
sd.flags.remove(zebra_chain::orchard::Flags::ENABLE_SPENDS);
sd.flags.remove(zebra_chain::orchard::Flags::ENABLE_OUTPUTS);
tracing::trace!(?sd);
let rsp = verifier.ready().await?.call(Item::from(&sd));
async_checks.push(rsp);
}
while let Some(result) = async_checks.next().await {
tracing::trace!(?result);
result?;
}
Ok(())
}
#[tokio::test(flavor = "multi_thread")]
async fn correctly_err_on_invalid_halo2_proofs() {
let _init_guard = zebra_test::init();
// These test vectors are generated by `generate_test_vectors()` function.
let shielded_data = zebra_test::vectors::ORCHARD_SHIELDED_DATA
.clone()
.iter()
.map(|bytes| {
let maybe_shielded_data: Option<zebra_chain::orchard::ShieldedData> = bytes
.zcash_deserialize_into()
.expect("a valid orchard::ShieldedData instance");
maybe_shielded_data.unwrap()
})
.collect();
// Use separate verifier so shared batch tasks aren't killed when the test ends (#2390)
let mut verifier = Fallback::new(
Batch::new(
Verifier::new(&VERIFYING_KEY),
crate::primitives::MAX_BATCH_SIZE,
None,
crate::primitives::MAX_BATCH_LATENCY,
),
tower::service_fn(
(|item: Item| ready(item.verify_single(&VERIFYING_KEY).map_err(Halo2Error::from)))
as fn(_) -> _,
),
);
// This should fail if any of the proofs fail to validate.
assert!(
verify_invalid_orchard_halo2_proofs(&mut verifier, shielded_data)
.await
.is_err()
);
}