arithmetic.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 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. use std::marker::PhantomData;
  19. use halo2_proofs::{
  20. circuit::{AssignedCell, Chip, Layouter},
  21. pasta::group::ff::WithSmallOrderMulGroup,
  22. plonk,
  23. plonk::{Advice, Column, ConstraintSystem, Constraints, Selector},
  24. poly::Rotation,
  25. };
  26. /// Arithmetic instructions implemented in the chip
  27. pub trait ArithInstruction<F: WithSmallOrderMulGroup<3> + Ord>: Chip<F> {
  28. /// Add two field elements and return their sum
  29. fn add(
  30. &self,
  31. layouter: impl Layouter<F>,
  32. a: &AssignedCell<F, F>,
  33. b: &AssignedCell<F, F>,
  34. ) -> Result<AssignedCell<F, F>, plonk::Error>;
  35. /// Subtract two field elements and return their difference
  36. fn sub(
  37. &self,
  38. layouter: impl Layouter<F>,
  39. a: &AssignedCell<F, F>,
  40. b: &AssignedCell<F, F>,
  41. ) -> Result<AssignedCell<F, F>, plonk::Error>;
  42. /// Multiply two field elements and return their product
  43. fn mul(
  44. &self,
  45. layouter: impl Layouter<F>,
  46. a: &AssignedCell<F, F>,
  47. b: &AssignedCell<F, F>,
  48. ) -> Result<AssignedCell<F, F>, plonk::Error>;
  49. }
  50. /// Configuration for the Arithmetic Chip
  51. #[derive(Clone, Debug)]
  52. pub struct ArithConfig {
  53. /// lhs
  54. a: Column<Advice>,
  55. /// rhs
  56. b: Column<Advice>,
  57. /// out
  58. c: Column<Advice>,
  59. /// Selector for the `add` operation
  60. q_add: Selector,
  61. /// Selector for the `sub` operation
  62. q_sub: Selector,
  63. /// Selector for the `mul` operation
  64. q_mul: Selector,
  65. }
  66. /// Arithmetic Chip
  67. pub struct ArithChip<F> {
  68. config: ArithConfig,
  69. _marker: PhantomData<F>,
  70. }
  71. impl<F: WithSmallOrderMulGroup<3> + Ord> Chip<F> for ArithChip<F> {
  72. type Config = ArithConfig;
  73. type Loaded = ();
  74. fn config(&self) -> &Self::Config {
  75. &self.config
  76. }
  77. fn loaded(&self) -> &Self::Loaded {
  78. &()
  79. }
  80. }
  81. impl<F: WithSmallOrderMulGroup<3> + Ord> ArithChip<F> {
  82. /// Configure the Arithmetic chip with the given columns
  83. pub fn configure(
  84. meta: &mut ConstraintSystem<F>,
  85. a: Column<Advice>,
  86. b: Column<Advice>,
  87. c: Column<Advice>,
  88. ) -> ArithConfig {
  89. let q_add = meta.selector();
  90. let q_sub = meta.selector();
  91. let q_mul = meta.selector();
  92. meta.create_gate("Field element addition: c = a + b", |meta| {
  93. let q_add = meta.query_selector(q_add);
  94. let a = meta.query_advice(a, Rotation::cur());
  95. let b = meta.query_advice(b, Rotation::cur());
  96. let c = meta.query_advice(c, Rotation::cur());
  97. Constraints::with_selector(q_add, Some(a + b - c))
  98. });
  99. meta.create_gate("Field element subtraction: c = a - b", |meta| {
  100. let q_sub = meta.query_selector(q_sub);
  101. let a = meta.query_advice(a, Rotation::cur());
  102. let b = meta.query_advice(b, Rotation::cur());
  103. let c = meta.query_advice(c, Rotation::cur());
  104. Constraints::with_selector(q_sub, Some(a - b - c))
  105. });
  106. meta.create_gate("Field element multiplication: c = a * b", |meta| {
  107. let q_mul = meta.query_selector(q_mul);
  108. let a = meta.query_advice(a, Rotation::cur());
  109. let b = meta.query_advice(b, Rotation::cur());
  110. let c = meta.query_advice(c, Rotation::cur());
  111. Constraints::with_selector(q_mul, Some(a * b - c))
  112. });
  113. ArithConfig { a, b, c, q_add, q_sub, q_mul }
  114. }
  115. pub fn construct(config: ArithConfig) -> Self {
  116. Self { config, _marker: PhantomData }
  117. }
  118. }
  119. impl<F: WithSmallOrderMulGroup<3> + Ord> ArithInstruction<F> for ArithChip<F> {
  120. fn add(
  121. &self,
  122. mut layouter: impl Layouter<F>,
  123. a: &AssignedCell<F, F>,
  124. b: &AssignedCell<F, F>,
  125. ) -> Result<AssignedCell<F, F>, plonk::Error> {
  126. layouter.assign_region(
  127. || "c = a + b",
  128. |mut region| {
  129. self.config.q_add.enable(&mut region, 0)?;
  130. a.copy_advice(|| "copy a", &mut region, self.config.a, 0)?;
  131. b.copy_advice(|| "copy b", &mut region, self.config.b, 0)?;
  132. let scalar_val = a.value().zip(b.value()).map(|(a, b)| *a + b);
  133. region.assign_advice(|| "c", self.config.c, 0, || scalar_val)
  134. },
  135. )
  136. }
  137. fn sub(
  138. &self,
  139. mut layouter: impl Layouter<F>,
  140. a: &AssignedCell<F, F>,
  141. b: &AssignedCell<F, F>,
  142. ) -> Result<AssignedCell<F, F>, plonk::Error> {
  143. layouter.assign_region(
  144. || "c = a - b",
  145. |mut region| {
  146. self.config.q_sub.enable(&mut region, 0)?;
  147. a.copy_advice(|| "copy a", &mut region, self.config.a, 0)?;
  148. b.copy_advice(|| "copy b", &mut region, self.config.b, 0)?;
  149. let scalar_val = a.value().zip(b.value()).map(|(a, b)| *a - b);
  150. region.assign_advice(|| "c", self.config.c, 0, || scalar_val)
  151. },
  152. )
  153. }
  154. fn mul(
  155. &self,
  156. mut layouter: impl Layouter<F>,
  157. a: &AssignedCell<F, F>,
  158. b: &AssignedCell<F, F>,
  159. ) -> Result<AssignedCell<F, F>, plonk::Error> {
  160. layouter.assign_region(
  161. || "c = a * b",
  162. |mut region| {
  163. self.config.q_mul.enable(&mut region, 0)?;
  164. a.copy_advice(|| "copy a", &mut region, self.config.a, 0)?;
  165. b.copy_advice(|| "copy b", &mut region, self.config.b, 0)?;
  166. let scalar_val = a.value().zip(b.value()).map(|(a, b)| *a * b);
  167. region.assign_advice(|| "c", self.config.c, 0, || scalar_val)
  168. },
  169. )
  170. }
  171. }
  172. #[cfg(test)]
  173. mod tests {
  174. use super::*;
  175. use crate::zk::assign_free_advice;
  176. use darkfi_sdk::pasta::pallas;
  177. use halo2_proofs::{
  178. arithmetic::Field,
  179. circuit::{floor_planner, Value},
  180. dev::{CircuitLayout, MockProver},
  181. plonk::{Circuit, Instance as InstanceColumn},
  182. };
  183. #[derive(Clone)]
  184. struct ArithCircuitConfig {
  185. primary: Column<InstanceColumn>,
  186. advices: [Column<Advice>; 3],
  187. arith_config: ArithConfig,
  188. }
  189. #[derive(Default)]
  190. struct ArithCircuit {
  191. pub one: Value<pallas::Base>,
  192. pub minus_one: Value<pallas::Base>,
  193. pub factor: Value<pallas::Base>,
  194. }
  195. impl Circuit<pallas::Base> for ArithCircuit {
  196. type Config = ArithCircuitConfig;
  197. type FloorPlanner = floor_planner::V1;
  198. type Params = ();
  199. fn without_witnesses(&self) -> Self {
  200. Self::default()
  201. }
  202. fn configure(meta: &mut ConstraintSystem<pallas::Base>) -> Self::Config {
  203. let advices = [meta.advice_column(), meta.advice_column(), meta.advice_column()];
  204. let primary = meta.instance_column();
  205. meta.enable_equality(primary);
  206. for advice in advices.iter() {
  207. meta.enable_equality(*advice);
  208. }
  209. let arith_config = ArithChip::configure(meta, advices[0], advices[1], advices[2]);
  210. Self::Config { primary, advices, arith_config }
  211. }
  212. fn synthesize(
  213. &self,
  214. config: Self::Config,
  215. mut layouter: impl Layouter<pallas::Base>,
  216. ) -> Result<(), plonk::Error> {
  217. let arith_chip = ArithChip::construct(config.arith_config.clone());
  218. let one = assign_free_advice(
  219. layouter.namespace(|| "Load Fp(1)"),
  220. config.advices[0],
  221. self.one,
  222. )?;
  223. let minus_one = assign_free_advice(
  224. layouter.namespace(|| "Load Fp(-1)"),
  225. config.advices[1],
  226. self.minus_one,
  227. )?;
  228. let factor = assign_free_advice(
  229. layouter.namespace(|| "Load Fp(factor)"),
  230. config.advices[2],
  231. self.factor,
  232. )?;
  233. let diff =
  234. arith_chip.sub(layouter.namespace(|| "one - minus_one"), &one, &minus_one)?;
  235. layouter.constrain_instance(diff.cell(), config.primary, 0)?;
  236. let zero =
  237. arith_chip.add(layouter.namespace(|| "one + minus_one"), &one, &minus_one)?;
  238. layouter.constrain_instance(zero.cell(), config.primary, 1)?;
  239. let min_1_min_1 = arith_chip.add(
  240. layouter.namespace(|| "minus_one + minus_one"),
  241. &minus_one,
  242. &minus_one,
  243. )?;
  244. layouter.constrain_instance(min_1_min_1.cell(), config.primary, 2)?;
  245. let product =
  246. arith_chip.mul(layouter.namespace(|| "minus_one * factor"), &minus_one, &factor)?;
  247. layouter.constrain_instance(product.cell(), config.primary, 3)?;
  248. Ok(())
  249. }
  250. }
  251. #[test]
  252. fn arithmetic_chip() -> crate::Result<()> {
  253. let one = pallas::Base::ONE;
  254. let minus_one = -pallas::Base::ONE;
  255. let factor = pallas::Base::from(644211);
  256. let public_inputs =
  257. vec![one - minus_one, pallas::Base::ZERO, minus_one + minus_one, minus_one * factor];
  258. let circuit = ArithCircuit {
  259. one: Value::known(one),
  260. minus_one: Value::known(minus_one),
  261. factor: Value::known(factor),
  262. };
  263. use plotters::prelude::*;
  264. let root = BitMapBackend::new("target/arithmetic_circuit_layout.png", (3840, 2160))
  265. .into_drawing_area();
  266. root.fill(&WHITE).unwrap();
  267. let root = root.titled("Arithmetic Circuit Layout", ("sans-serif", 60)).unwrap();
  268. CircuitLayout::default().render(4, &circuit, &root).unwrap();
  269. let prover = MockProver::run(4, &circuit, vec![public_inputs.clone()])?;
  270. prover.assert_satisfied();
  271. Ok(())
  272. }
  273. }