less_than.rs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2022 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. // cargo run --release --example lesthan --all-features
  19. use halo2_proofs::{
  20. circuit::{floor_planner, Layouter, Value},
  21. dev::MockProver,
  22. pasta::{pallas, vesta},
  23. plonk,
  24. plonk::{Advice, Circuit, Column, ConstraintSystem, Error, SingleVerifier},
  25. transcript::{Blake2bRead, Blake2bWrite},
  26. };
  27. use log::{error, info};
  28. use rand::rngs::OsRng;
  29. use darkfi::{
  30. consensus::{types::Float10, utils::fbig2base, RADIX_BITS},
  31. crypto::{
  32. proof::{ProvingKey, VerifyingKey},
  33. Proof,
  34. },
  35. zk::gadget::{
  36. less_than::{LessThanChip, LessThanConfig},
  37. native_range_check::NativeRangeCheckChip,
  38. },
  39. };
  40. const WINDOW_SIZE: usize = 3;
  41. const NUM_BITS: usize = 253;
  42. const NUM_WINDOWS: usize = 85;
  43. #[derive(Default)]
  44. struct LessThanCircuit {
  45. a: Value<pallas::Base>,
  46. b: Value<pallas::Base>,
  47. }
  48. impl Circuit<pallas::Base> for LessThanCircuit {
  49. type Config = (LessThanConfig<WINDOW_SIZE, NUM_BITS, NUM_WINDOWS>, Column<Advice>);
  50. type FloorPlanner = floor_planner::V1;
  51. fn without_witnesses(&self) -> Self {
  52. Self::default()
  53. }
  54. fn configure(meta: &mut ConstraintSystem<pallas::Base>) -> Self::Config {
  55. let advices = [
  56. meta.advice_column(),
  57. meta.advice_column(),
  58. meta.advice_column(),
  59. meta.advice_column(),
  60. meta.advice_column(),
  61. meta.advice_column(),
  62. ];
  63. for advice in advices.iter() {
  64. meta.enable_equality(*advice);
  65. }
  66. let constants = meta.fixed_column();
  67. meta.enable_constant(constants);
  68. let k_values_table = meta.lookup_table_column();
  69. (
  70. LessThanChip::<WINDOW_SIZE, NUM_BITS, NUM_WINDOWS>::configure(
  71. meta,
  72. advices[1],
  73. advices[2],
  74. advices[3],
  75. advices[4],
  76. advices[5],
  77. k_values_table,
  78. ),
  79. advices[0],
  80. )
  81. }
  82. fn synthesize(
  83. &self,
  84. config: Self::Config,
  85. mut layouter: impl Layouter<pallas::Base>,
  86. ) -> Result<(), Error> {
  87. let less_than_chip =
  88. LessThanChip::<WINDOW_SIZE, NUM_BITS, NUM_WINDOWS>::construct(config.0.clone());
  89. NativeRangeCheckChip::<WINDOW_SIZE, NUM_BITS, NUM_WINDOWS>::load_k_table(
  90. &mut layouter,
  91. config.0.k_values_table,
  92. )?;
  93. less_than_chip.witness_less_than(
  94. layouter.namespace(|| "a < b"),
  95. self.a,
  96. self.b,
  97. 0,
  98. true,
  99. )?;
  100. Ok(())
  101. }
  102. }
  103. fn simple_lessthan(k: u32) -> Result<(), halo2_proofs::plonk::Error> {
  104. let circuit = LessThanCircuit {
  105. a: Value::known(pallas::Base::from(0)),
  106. b: Value::known(pallas::Base::from(1)),
  107. };
  108. let prover = MockProver::run(k, &circuit, vec![]).unwrap();
  109. prover.assert_satisfied();
  110. // Prover:
  111. let pk = ProvingKey::build(k, &LessThanCircuit::default());
  112. let mut transcript = Blake2bWrite::<_, vesta::Affine, _>::init(vec![]);
  113. plonk::create_proof(&pk.params, &pk.pk, &[circuit], &[&[]], &mut OsRng, &mut transcript)?;
  114. let proof = transcript.finalize();
  115. // Verifier:
  116. let vk = VerifyingKey::build(k, &LessThanCircuit::default());
  117. let strategy = SingleVerifier::new(&vk.params);
  118. let mut transcript = Blake2bRead::init(&proof[..]);
  119. plonk::verify_proof(&vk.params, &vk.vk, strategy, &[&[]], &mut transcript)?;
  120. Ok(())
  121. }
  122. fn fullrange_lessthan(k: u32) -> Result<(), halo2_proofs::plonk::Error> {
  123. let y_str: &'static str =
  124. "2485393101277319054866673974886504690592360759087472860138246047042221199789";
  125. let t_str: &'static str =
  126. "20228360686725123198855333388287068776098384779255635716769234906173337213460";
  127. let y: pallas::Base =
  128. fbig2base(Float10::from_str_native(y_str).unwrap().with_precision(*RADIX_BITS).value());
  129. let t: pallas::Base =
  130. fbig2base(Float10::from_str_native(t_str).unwrap().with_precision(*RADIX_BITS).value());
  131. let circuit = LessThanCircuit { a: Value::known(y), b: Value::known(t) };
  132. let prover = MockProver::run(k, &circuit, vec![]).unwrap();
  133. prover.assert_satisfied();
  134. assert!(prover.verify().is_ok());
  135. let public_inputs: Vec<pallas::Base> = vec![];
  136. let pk = ProvingKey::build(k, &LessThanCircuit::default());
  137. let vk = VerifyingKey::build(k, &LessThanCircuit::default());
  138. let mut transcript = Blake2bWrite::<_, vesta::Affine, _>::init(vec![]);
  139. plonk::create_proof(&pk.params, &pk.pk, &[circuit], &[&[]], &mut OsRng, &mut transcript)?;
  140. let proof = transcript.finalize();
  141. let strategy = SingleVerifier::new(&vk.params);
  142. let mut transcript = Blake2bRead::init(&proof[..]);
  143. plonk::verify_proof(&vk.params, &vk.vk, strategy, &[&[]], &mut transcript)?;
  144. Ok(())
  145. }
  146. fn main() {
  147. env_logger::init();
  148. let k = 11;
  149. simple_lessthan(k).unwrap();
  150. fullrange_lessthan(k).unwrap();
  151. }