use alloc::vec::Vec;
use core::fmt;
use halo2_proofs::plonk;
use pasta_curves::vesta;
use rand::{CryptoRng, RngCore};
use tracing::debug;
use super::{Authorized, Bundle};
use crate::{
circuit::VerifyingKey,
primitives::redpallas::{self, Binding, SpendAuth},
};
#[derive(Debug)]
struct BundleSignature {
signature: redpallas::batch::Item<SpendAuth, Binding>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum BatchError {
RestrictionUnsupportedByKey,
}
impl fmt::Display for BatchError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BatchError::RestrictionUnsupportedByKey => write!(
f,
"bundle disables cross-address transfers, but the verifying key's circuit \
version does not constrain the cross-address restriction",
),
}
}
}
impl core::error::Error for BatchError {}
#[derive(Debug)]
pub struct BatchValidator<'a> {
proofs: plonk::BatchVerifier<vesta::Affine>,
signatures: Vec<BundleSignature>,
vk: &'a VerifyingKey,
}
impl<'a> BatchValidator<'a> {
pub fn new(vk: &'a VerifyingKey) -> Self {
BatchValidator {
proofs: plonk::BatchVerifier::new(),
signatures: vec![],
vk,
}
}
pub fn add_bundle<V: Copy + Into<i64>>(
&mut self,
bundle: &Bundle<Authorized, V>,
sighash: [u8; 32],
) -> Result<(), BatchError> {
if !bundle.flags().cross_address_enabled() && !self.vk.supports_cross_address_restriction()
{
return Err(BatchError::RestrictionUnsupportedByKey);
}
for action in bundle.actions().iter() {
self.signatures.push(BundleSignature {
signature: action
.rk()
.create_batch_item(action.authorization().clone(), &sighash),
});
}
self.signatures.push(BundleSignature {
signature: bundle
.binding_validating_key()
.create_batch_item(bundle.authorization().binding_signature().clone(), &sighash),
});
bundle
.authorization()
.proof()
.add_to_batch(&mut self.proofs, bundle.to_instances());
Ok(())
}
pub fn validate<R: RngCore + CryptoRng>(self, rng: R) -> bool {
if self.signatures.is_empty() {
return true;
}
let mut validator = redpallas::batch::Verifier::new();
for sig in self.signatures.iter() {
validator.queue(sig.signature.clone());
}
match validator.verify(rng) {
Ok(()) => self.proofs.finalize(&self.vk.params, &self.vk.vk),
Err(e) => {
debug!("RedPallas batch validation failed: {}", e);
false
}
}
}
}
#[cfg(test)]
mod tests {
use rand::rngs::OsRng;
use super::{BatchError, BatchValidator};
use crate::{
bundle::tests::{sample_authorized_bundle, with_cross_address_disabled},
circuit::{OrchardCircuitVersion, VerifyingKey},
};
#[test]
fn add_bundle_rejects_unsupported_cross_address_restriction() {
let bundle = with_cross_address_disabled(sample_authorized_bundle(1))
.try_map_value_balance(i64::try_from)
.expect("generated bundle value balance fits in i64");
for circuit_version in [
OrchardCircuitVersion::InsecurePreNu6_2,
OrchardCircuitVersion::FixedPostNu6_2,
] {
let vk = VerifyingKey::build(circuit_version);
let mut validator = BatchValidator::new(&vk);
assert_eq!(
validator.add_bundle(&bundle, [0; 32]),
Err(BatchError::RestrictionUnsupportedByKey)
);
}
let vk = VerifyingKey::build(OrchardCircuitVersion::PostNu6_3);
let mut validator = BatchValidator::new(&vk);
assert_eq!(validator.add_bundle(&bundle, [0; 32]), Ok(()));
}
#[test]
fn empty_batch_validates() {
for circuit_version in [
OrchardCircuitVersion::InsecurePreNu6_2,
OrchardCircuitVersion::FixedPostNu6_2,
OrchardCircuitVersion::PostNu6_3,
] {
let vk = VerifyingKey::build(circuit_version);
assert!(BatchValidator::new(&vk).validate(OsRng));
}
}
}