mint_contract.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. use pasta_curves::pallas;
  2. use halo2::{
  3. circuit::{Layouter, SimpleFloorPlanner},
  4. plonk,
  5. plonk::{Advice, Circuit, Column, ConstraintSystem, Instance as InstanceColumn, Selector},
  6. poly::Rotation,
  7. };
  8. use halo2_gadgets::{
  9. ecc::{
  10. chip::{EccChip, EccConfig},
  11. FixedPoint,
  12. },
  13. poseidon::{
  14. Hash as PoseidonHash, Pow5T3Chip as PoseidonChip, Pow5T3Config as PoseidonConfig,
  15. StateWord, Word,
  16. },
  17. primitives::poseidon::{ConstantLength, P128Pow5T3},
  18. sinsemilla::{
  19. chip::{SinsemillaChip, SinsemillaConfig},
  20. merkle::chip::{MerkleChip, MerkleConfig},
  21. },
  22. utilities::{
  23. copy, lookup_range_check::LookupRangeCheckConfig, CellValue, UtilitiesInstructions, Var,
  24. },
  25. };
  26. use crate::crypto::constants::{
  27. sinsemilla::{OrchardCommitDomains, OrchardHashDomains},
  28. OrchardFixedBases,
  29. };
  30. #[derive(Clone, Debug)]
  31. pub struct MintConfig {
  32. primary: Column<InstanceColumn>,
  33. q_add: Selector,
  34. advices: [Column<Advice>; 10],
  35. ecc_config: EccConfig,
  36. merkle_config_1: MerkleConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
  37. merkle_config_2: MerkleConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
  38. sinsemilla_config_1:
  39. SinsemillaConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
  40. sinsemilla_config_2:
  41. SinsemillaConfig<OrchardHashDomains, OrchardCommitDomains, OrchardFixedBases>,
  42. poseidon_config: PoseidonConfig<pallas::Base>,
  43. }
  44. impl MintConfig {
  45. fn ecc_chip(&self) -> EccChip<OrchardFixedBases> {
  46. EccChip::construct(self.ecc_config.clone())
  47. }
  48. fn poseidon_chip(&self) -> PoseidonChip<pallas::Base> {
  49. PoseidonChip::construct(self.poseidon_config.clone())
  50. }
  51. }
  52. // The public input array offsets
  53. const MINT_COIN_OFFSET: usize = 0;
  54. const MINT_VALCOMX_OFFSET: usize = 1;
  55. const MINT_VALCOMY_OFFSET: usize = 2;
  56. const MINT_ASSCOMX_OFFSET: usize = 3;
  57. const MINT_ASSCOMY_OFFSET: usize = 4;
  58. #[derive(Default, Debug)]
  59. pub struct MintContract {
  60. pub pub_x: Option<pallas::Base>, // x coordinate for pubkey
  61. pub pub_y: Option<pallas::Base>, // y coordinate for pubkey
  62. pub value: Option<pallas::Base>, // The value of this coin
  63. pub asset: Option<pallas::Base>, // The asset ID
  64. pub serial: Option<pallas::Base>, // Unique serial number corresponding to this coin
  65. pub coin_blind: Option<pallas::Base>, // Random blinding factor for coin
  66. pub value_blind: Option<pallas::Scalar>, // Random blinding factor for value commitment
  67. pub asset_blind: Option<pallas::Scalar>, // Random blinding factor for the asset ID
  68. }
  69. impl UtilitiesInstructions<pallas::Base> for MintContract {
  70. type Var = CellValue<pallas::Base>;
  71. }
  72. impl Circuit<pallas::Base> for MintContract {
  73. type Config = MintConfig;
  74. type FloorPlanner = SimpleFloorPlanner;
  75. fn without_witnesses(&self) -> Self {
  76. Self::default()
  77. }
  78. fn configure(meta: &mut ConstraintSystem<pallas::Base>) -> Self::Config {
  79. // Advice columns used in the circuit
  80. let advices = [
  81. meta.advice_column(),
  82. meta.advice_column(),
  83. meta.advice_column(),
  84. meta.advice_column(),
  85. meta.advice_column(),
  86. meta.advice_column(),
  87. meta.advice_column(),
  88. meta.advice_column(),
  89. meta.advice_column(),
  90. meta.advice_column(),
  91. ];
  92. // Addition of two field elements
  93. /*
  94. let q_add = meta.selector();
  95. meta.create_gate("poseidon_hash(a, b) + c", |meta| {
  96. let q_add = meta.query_selector(q_add);
  97. let sum = meta.query_advice(advices[6], Rotation::cur());
  98. let hash = meta.query_advice(advices[7], Rotation::cur());
  99. let c = meta.query_advice(advices[8], Rotation::cur());
  100. vec![q_add * (hash + c - sum)]
  101. });
  102. */
  103. let q_add = meta.selector();
  104. meta.create_gate("a+b+c", |meta| {
  105. let q_add = meta.query_selector(q_add);
  106. let sum = meta.query_advice(advices[5], Rotation::cur());
  107. let a = meta.query_advice(advices[6], Rotation::cur());
  108. let b = meta.query_advice(advices[7], Rotation::cur());
  109. let c = meta.query_advice(advices[8], Rotation::cur());
  110. vec![q_add * (a + b + c - sum)]
  111. });
  112. // Fixed columns for the Sinsemilla generator lookup table
  113. let table_idx = meta.lookup_table_column();
  114. let lookup = (
  115. table_idx,
  116. meta.lookup_table_column(),
  117. meta.lookup_table_column(),
  118. );
  119. // Instance column used for public inputs
  120. let primary = meta.instance_column();
  121. meta.enable_equality(primary.into());
  122. // Permutation over all advice columns
  123. for advice in advices.iter() {
  124. meta.enable_equality((*advice).into());
  125. }
  126. // Poseidon requires four advice columns, while ECC incomplete addition
  127. // requires six. We can reduce the proof size by sharing fixed columns
  128. // between the ECC and Poseidon chips.
  129. // TODO: For multiple invocations they could/should be configured in
  130. // parallel rather than sharing perhaps?
  131. let lagrange_coeffs = [
  132. meta.fixed_column(),
  133. meta.fixed_column(),
  134. meta.fixed_column(),
  135. meta.fixed_column(),
  136. meta.fixed_column(),
  137. meta.fixed_column(),
  138. meta.fixed_column(),
  139. meta.fixed_column(),
  140. ];
  141. let rc_a = lagrange_coeffs[2..5].try_into().unwrap();
  142. let rc_b = lagrange_coeffs[5..8].try_into().unwrap();
  143. // Also use the first Lagrange coefficient column for loading global constants.
  144. meta.enable_constant(lagrange_coeffs[0]);
  145. // Use one of the right-most advice columns for all of our range checks.
  146. let range_check = LookupRangeCheckConfig::configure(meta, advices[9], table_idx);
  147. // Configuration for curve point operations.
  148. // This uses 10 advice columns and spans the whole circuit.
  149. let ecc_config = EccChip::<OrchardFixedBases>::configure(
  150. meta,
  151. advices,
  152. lagrange_coeffs,
  153. range_check.clone(),
  154. );
  155. // Configuration for the Poseidon hash
  156. let poseidon_config = PoseidonChip::configure(
  157. meta,
  158. P128Pow5T3,
  159. advices[6..9].try_into().unwrap(),
  160. advices[5],
  161. rc_a,
  162. rc_b,
  163. );
  164. // Configuration for a Sinsemilla hash instantiation and a
  165. // Merkle hash instantiation using this Sinsemilla instance.
  166. // Since the Sinsemilla config uses only 5 advice columns,
  167. // we can fit two instances side-by-side.
  168. let (sinsemilla_config_1, merkle_config_1) = {
  169. let sinsemilla_config_1 = SinsemillaChip::configure(
  170. meta,
  171. advices[..5].try_into().unwrap(),
  172. advices[6],
  173. lagrange_coeffs[0],
  174. lookup,
  175. range_check.clone(),
  176. );
  177. let merkle_config_1 = MerkleChip::configure(meta, sinsemilla_config_1.clone());
  178. (sinsemilla_config_1, merkle_config_1)
  179. };
  180. // Configuration for a Sinsemilla hash instantiation and a
  181. // Merkle hash instantiation using this Sinsemilla instance.
  182. // Since the Sinsemilla config uses only 5 advice columns,
  183. // we can fit two instances side-by-side.
  184. let (sinsemilla_config_2, merkle_config_2) = {
  185. let sinsemilla_config_2 = SinsemillaChip::configure(
  186. meta,
  187. advices[5..].try_into().unwrap(),
  188. advices[7],
  189. lagrange_coeffs[1],
  190. lookup,
  191. range_check,
  192. );
  193. let merkle_config_2 = MerkleChip::configure(meta, sinsemilla_config_2.clone());
  194. (sinsemilla_config_2, merkle_config_2)
  195. };
  196. MintConfig {
  197. primary,
  198. q_add,
  199. advices,
  200. ecc_config,
  201. merkle_config_1,
  202. merkle_config_2,
  203. sinsemilla_config_1,
  204. sinsemilla_config_2,
  205. poseidon_config,
  206. }
  207. }
  208. fn synthesize(
  209. &self,
  210. config: Self::Config,
  211. mut layouter: impl Layouter<pallas::Base>,
  212. ) -> Result<(), plonk::Error> {
  213. // Load the Sinsemilla generator lookup table used by the whole circuit.
  214. SinsemillaChip::load(config.sinsemilla_config_1.clone(), &mut layouter)?;
  215. let ecc_chip = config.ecc_chip();
  216. let pub_x = self.load_private(
  217. layouter.namespace(|| "load pubkey x"),
  218. config.advices[0],
  219. self.pub_x,
  220. )?;
  221. let pub_y = self.load_private(
  222. layouter.namespace(|| "load pubkey y"),
  223. config.advices[0],
  224. self.pub_y,
  225. )?;
  226. let value = self.load_private(
  227. layouter.namespace(|| "load value"),
  228. config.advices[0],
  229. self.value,
  230. )?;
  231. let asset = self.load_private(
  232. layouter.namespace(|| "load asset"),
  233. config.advices[0],
  234. self.asset,
  235. )?;
  236. let serial = self.load_private(
  237. layouter.namespace(|| "load serial"),
  238. config.advices[0],
  239. self.serial,
  240. )?;
  241. let coin_blind = self.load_private(
  242. layouter.namespace(|| "load coin_blind"),
  243. config.advices[0],
  244. self.coin_blind,
  245. )?;
  246. // =========
  247. // Coin hash
  248. // =========
  249. let messages = [[pub_x, pub_y], [value, asset], [serial, coin_blind]];
  250. let mut hashes = vec![];
  251. for message in messages.iter() {
  252. let hash = {
  253. let poseidon_message = layouter.assign_region(
  254. || "load message",
  255. |mut region| {
  256. let mut message_word = |i: usize| {
  257. let value = message[i].value();
  258. let var = region.assign_advice(
  259. || format!("load message_{}", i),
  260. config.poseidon_config.state()[i],
  261. 0,
  262. || value.ok_or(plonk::Error::SynthesisError),
  263. )?;
  264. region.constrain_equal(var, message[i].cell())?;
  265. Ok(Word::<_, _, P128Pow5T3, 3, 2>::from_inner(StateWord::new(
  266. var, value,
  267. )))
  268. };
  269. Ok([message_word(0)?, message_word(1)?])
  270. },
  271. )?;
  272. let poseidon_hasher = PoseidonHash::init(
  273. config.poseidon_chip(),
  274. layouter.namespace(|| "Poseidon init"),
  275. ConstantLength::<2>,
  276. )?;
  277. let poseidon_output = poseidon_hasher.hash(
  278. layouter.namespace(|| "Poseidon hash (a, b)"),
  279. poseidon_message,
  280. )?;
  281. let poseidon_output: CellValue<pallas::Base> = poseidon_output.inner().into();
  282. poseidon_output
  283. };
  284. hashes.push(hash);
  285. }
  286. let coin = layouter.assign_region(
  287. || " `coin` = hash(a,b) + hash(c, d) + hash(e, f)",
  288. |mut region| {
  289. config.q_add.enable(&mut region, 0)?;
  290. copy(&mut region, || "copy ab", config.advices[6], 0, &hashes[0])?;
  291. copy(&mut region, || "copy cd", config.advices[7], 0, &hashes[1])?;
  292. copy(&mut region, || "copy ef", config.advices[8], 0, &hashes[2])?;
  293. let scalar_val = hashes[0]
  294. .value()
  295. .zip(hashes[1].value())
  296. .zip(hashes[2].value())
  297. .map(|(abcd, ef)| abcd.0 + abcd.1 + ef);
  298. let cell = region.assign_advice(
  299. || "hash(a,b)+hash(c,d)+hash(e,f)",
  300. config.advices[5],
  301. 0,
  302. || scalar_val.ok_or(plonk::Error::SynthesisError),
  303. )?;
  304. Ok(CellValue::new(cell, scalar_val))
  305. },
  306. )?;
  307. // Constrain the coin C
  308. layouter.constrain_instance(coin.cell(), config.primary, MINT_COIN_OFFSET)?;
  309. // ================
  310. // Value commitment
  311. // ================
  312. // This constant one is used for short multiplication
  313. let one = self.load_private(
  314. layouter.namespace(|| "load constant one"),
  315. config.advices[0],
  316. Some(pallas::Base::one()),
  317. )?;
  318. // v * G_1
  319. let (commitment, _) = {
  320. let value_commit_v = OrchardFixedBases::ValueCommitV;
  321. let value_commit_v = FixedPoint::from_inner(ecc_chip.clone(), value_commit_v);
  322. value_commit_v.mul_short(layouter.namespace(|| "[value] ValueCommitV"), (value, one))?
  323. };
  324. // r_V * G_2
  325. let (blind, _rcv) = {
  326. let rcv = self.value_blind;
  327. let value_commit_r = OrchardFixedBases::ValueCommitR;
  328. let value_commit_r = FixedPoint::from_inner(ecc_chip.clone(), value_commit_r);
  329. value_commit_r.mul(layouter.namespace(|| "[value_blind] ValueCommitR"), rcv)?
  330. };
  331. // Constrain the value commitment coordinates
  332. let value_commit = commitment.add(layouter.namespace(|| "valuecommit"), &blind)?;
  333. layouter.constrain_instance(
  334. value_commit.inner().x().cell(),
  335. config.primary,
  336. MINT_VALCOMX_OFFSET,
  337. )?;
  338. layouter.constrain_instance(
  339. value_commit.inner().y().cell(),
  340. config.primary,
  341. MINT_VALCOMY_OFFSET,
  342. )?;
  343. // ================
  344. // Asset commitment
  345. // ================
  346. // a * G_1
  347. let (commitment, _) = {
  348. let asset_commit_v = OrchardFixedBases::ValueCommitV;
  349. let asset_commit_v = FixedPoint::from_inner(ecc_chip.clone(), asset_commit_v);
  350. asset_commit_v.mul_short(layouter.namespace(|| "[asset] ValueCommitV"), (asset, one))?
  351. };
  352. // r_A * G_2
  353. let (blind, _rca) = {
  354. let rca = self.asset_blind;
  355. let asset_commit_r = OrchardFixedBases::ValueCommitR;
  356. let asset_commit_r = FixedPoint::from_inner(ecc_chip, asset_commit_r);
  357. asset_commit_r.mul(layouter.namespace(|| "[asset_blind] ValueCommitR"), rca)?
  358. };
  359. // Constrain the asset commitment coordinates
  360. let asset_commit = commitment.add(layouter.namespace(|| "assetcommit"), &blind)?;
  361. layouter.constrain_instance(
  362. asset_commit.inner().x().cell(),
  363. config.primary,
  364. MINT_ASSCOMX_OFFSET,
  365. )?;
  366. layouter.constrain_instance(
  367. asset_commit.inner().y().cell(),
  368. config.primary,
  369. MINT_ASSCOMY_OFFSET,
  370. )?;
  371. // At this point we've enforced all of our public inputs.
  372. Ok(())
  373. }
  374. }