proof.rs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. use halo2::{
  2. plonk,
  3. plonk::Circuit,
  4. poly::commitment,
  5. transcript::{Blake2bRead, Blake2bWrite},
  6. };
  7. use pasta_curves::{pallas, vesta};
  8. #[derive(Debug)]
  9. pub struct VerifyingKey {
  10. pub params: commitment::Params<vesta::Affine>,
  11. pub vk: plonk::VerifyingKey<vesta::Affine>,
  12. }
  13. impl VerifyingKey {
  14. pub fn build(k: u32, c: impl Circuit<pallas::Base>) -> Self {
  15. let params = commitment::Params::new(k);
  16. let vk = plonk::keygen_vk(&params, &c).unwrap();
  17. VerifyingKey { params, vk }
  18. }
  19. }
  20. #[derive(Debug)]
  21. pub struct ProvingKey {
  22. pub params: commitment::Params<vesta::Affine>,
  23. pub pk: plonk::ProvingKey<vesta::Affine>,
  24. }
  25. impl ProvingKey {
  26. pub fn build(k: u32, c: impl Circuit<pallas::Base>) -> Self {
  27. let params = commitment::Params::new(k);
  28. let vk = plonk::keygen_vk(&params, &c).unwrap();
  29. let pk = plonk::keygen_pk(&params, vk, &c).unwrap();
  30. ProvingKey { params, pk }
  31. }
  32. }
  33. #[derive(Clone, Debug)]
  34. pub struct Proof(Vec<u8>);
  35. impl AsRef<[u8]> for Proof {
  36. fn as_ref(&self) -> &[u8] {
  37. &self.0
  38. }
  39. }
  40. impl Proof {
  41. pub fn create(
  42. pk: &ProvingKey,
  43. circuits: &[impl Circuit<pallas::Base>],
  44. pubinputs: &[pallas::Base],
  45. ) -> Result<Self, plonk::Error> {
  46. let mut transcript = Blake2bWrite::<_, vesta::Affine, _>::init(vec![]);
  47. plonk::create_proof(
  48. &pk.params,
  49. &pk.pk,
  50. circuits,
  51. &[&[pubinputs]],
  52. &mut transcript,
  53. )?;
  54. Ok(Proof(transcript.finalize()))
  55. }
  56. pub fn verify(
  57. &self,
  58. vk: &VerifyingKey,
  59. pubinputs: &[pallas::Base],
  60. ) -> Result<(), plonk::Error> {
  61. let msm = vk.params.empty_msm();
  62. let mut transcript = Blake2bRead::init(&self.0[..]);
  63. let guard = plonk::verify_proof(&vk.params, &vk.vk, msm, &[&[pubinputs]], &mut transcript)?;
  64. let msm = guard.clone().use_challenges();
  65. if msm.eval() {
  66. Ok(())
  67. } else {
  68. Err(plonk::Error::ConstraintSystemFailure)
  69. }
  70. }
  71. pub fn new(bytes: Vec<u8>) -> Self {
  72. Proof(bytes)
  73. }
  74. }