debug.rs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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 darkfi_sdk::pasta::pallas;
  19. use log::error;
  20. #[cfg(feature = "tinyjson")]
  21. use {
  22. std::{collections::HashMap, fs::File, io::Write, path::Path},
  23. tinyjson::JsonValue::{Array as JsonArray, Object as JsonObj, String as JsonStr},
  24. };
  25. use super::{Witness, ZkCircuit};
  26. use crate::{zkas, Error, Result};
  27. #[cfg(feature = "tinyjson")]
  28. /// Export witness.json which can be used by zkrunner for debugging circuits
  29. pub fn export_witness_json<P: AsRef<Path>>(
  30. output_path: P,
  31. prover_witnesses: &Vec<Witness>,
  32. public_inputs: &Vec<pallas::Base>,
  33. ) {
  34. let mut witnesses = Vec::new();
  35. for witness in prover_witnesses {
  36. let mut value_json = HashMap::new();
  37. match witness {
  38. Witness::Base(value) => {
  39. value.map(|w1| {
  40. value_json.insert("Base".to_string(), JsonStr(format!("{:?}", w1)));
  41. w1
  42. });
  43. }
  44. Witness::Scalar(value) => {
  45. value.map(|w1| {
  46. value_json.insert("Scalar".to_string(), JsonStr(format!("{:?}", w1)));
  47. w1
  48. });
  49. }
  50. _ => unimplemented!(),
  51. }
  52. witnesses.push(JsonObj(value_json));
  53. }
  54. let mut instances = Vec::new();
  55. for instance in public_inputs {
  56. instances.push(JsonStr(format!("{:?}", instance)));
  57. }
  58. let witnesses_json = JsonArray(witnesses);
  59. let instances_json = JsonArray(instances);
  60. let witness_json = JsonObj(HashMap::from([
  61. ("witnesses".to_string(), witnesses_json),
  62. ("instances".to_string(), instances_json),
  63. ]));
  64. // This is a debugging method. We don't care about .expect() crashing.
  65. let json = witness_json.format().expect("cannot create debug json");
  66. let mut output = File::create(output_path).expect("cannot write file");
  67. output.write_all(json.as_bytes()).expect("write failed");
  68. }
  69. /// Call this before `Proof::create()` to perform type checks on the witnesses and check
  70. /// the amount of provided instances are correct.
  71. pub fn zkas_type_checks(
  72. circuit: &ZkCircuit,
  73. binary: &zkas::ZkBinary,
  74. instances: &[pallas::Base],
  75. ) -> Result<()> {
  76. if circuit.witnesses.len() != binary.witnesses.len() {
  77. error!(
  78. "Wrong number of witnesses. Should be {}, but instead got {}.",
  79. binary.witnesses.len(),
  80. circuit.witnesses.len()
  81. );
  82. return Err(Error::WrongWitnessesCount)
  83. }
  84. for (i, (circuit_witness, binary_witness)) in
  85. circuit.witnesses.iter().zip(binary.witnesses.iter()).enumerate()
  86. {
  87. let is_pass = match circuit_witness {
  88. Witness::EcPoint(_) => *binary_witness == zkas::VarType::EcPoint,
  89. Witness::EcNiPoint(_) => *binary_witness == zkas::VarType::EcNiPoint,
  90. Witness::EcFixedPoint(_) => *binary_witness == zkas::VarType::EcFixedPoint,
  91. Witness::Base(_) => *binary_witness == zkas::VarType::Base,
  92. Witness::Scalar(_) => *binary_witness == zkas::VarType::Scalar,
  93. Witness::MerklePath(_) => *binary_witness == zkas::VarType::MerklePath,
  94. Witness::Uint32(_) => *binary_witness == zkas::VarType::Uint32,
  95. Witness::Uint64(_) => *binary_witness == zkas::VarType::Uint64,
  96. };
  97. if !is_pass {
  98. error!(
  99. "Wrong witness type at index {}. Expected '{}', but instead got '{}'.",
  100. i,
  101. binary_witness.name(),
  102. circuit_witness.name()
  103. );
  104. return Err(Error::WrongWitnessType(i))
  105. }
  106. }
  107. // Count number of public instances
  108. let mut instances_count = 0;
  109. for opcode in &circuit.opcodes {
  110. if let (zkas::Opcode::ConstrainInstance, _) = opcode {
  111. instances_count += 1;
  112. }
  113. }
  114. if instances.len() != instances_count {
  115. error!(
  116. "Wrong number of public inputs. Should be {}, but instead got {}.",
  117. instances_count,
  118. instances.len()
  119. );
  120. return Err(Error::WrongPublicInputsCount)
  121. }
  122. Ok(())
  123. }