decoder.rs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2025 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_serial::{deserialize_partial, VarInt};
  19. use super::{
  20. compiler::MAGIC_BYTES,
  21. constants::{MAX_K, MAX_NS_LEN, MIN_BIN_SIZE},
  22. types::HeapType,
  23. LitType, Opcode, VarType,
  24. };
  25. use crate::{Error::ZkasDecoderError as ZkasErr, Result};
  26. /// A ZkBinary decoded from compiled zkas code.
  27. /// This is used by the zkvm.
  28. #[derive(Clone, Debug)]
  29. // ANCHOR: zkbinary-struct
  30. pub struct ZkBinary {
  31. pub namespace: String,
  32. pub k: u32,
  33. pub constants: Vec<(VarType, String)>,
  34. pub literals: Vec<(LitType, String)>,
  35. pub witnesses: Vec<VarType>,
  36. pub opcodes: Vec<(Opcode, Vec<(HeapType, usize)>)>,
  37. }
  38. // ANCHOR_END: zkbinary-struct
  39. // https://stackoverflow.com/questions/35901547/how-can-i-find-a-subsequence-in-a-u8-slice
  40. fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
  41. haystack.windows(needle.len()).position(|window| window == needle)
  42. }
  43. impl ZkBinary {
  44. pub fn decode(bytes: &[u8]) -> Result<Self> {
  45. // Ensure that bytes is a certain minimum length. Otherwise the code
  46. // below will panic due to an index out of bounds error.
  47. if bytes.len() < MIN_BIN_SIZE {
  48. return Err(ZkasErr("Not enough bytes".to_string()))
  49. }
  50. let magic_bytes = &bytes[0..4];
  51. if magic_bytes != MAGIC_BYTES {
  52. return Err(ZkasErr("Magic bytes are incorrect".to_string()))
  53. }
  54. let _binary_version = &bytes[4];
  55. // Deserialize the k param
  56. let (k, _): (u32, _) = deserialize_partial(&bytes[5..9])?;
  57. // For now, we'll limit k.
  58. if k > MAX_K {
  59. return Err(ZkasErr("k param is too high, max allowed is 16".to_string()))
  60. }
  61. // After the binary version and k, we're supposed to have the witness namespace
  62. let (namespace, _): (String, _) = deserialize_partial(&bytes[9..])?;
  63. // Enforce a limit on the namespace string length
  64. if namespace.len() > MAX_NS_LEN {
  65. return Err(ZkasErr("Namespace too long".to_string()))
  66. }
  67. let constants_offset = match find_subslice(bytes, b".constant") {
  68. Some(v) => v,
  69. None => return Err(ZkasErr("Could not find .constant section".to_string())),
  70. };
  71. let literals_offset = match find_subslice(bytes, b".literal") {
  72. Some(v) => v,
  73. None => return Err(ZkasErr("Could not find .literal section".to_string())),
  74. };
  75. let witness_offset = match find_subslice(bytes, b".witness") {
  76. Some(v) => v,
  77. None => return Err(ZkasErr("Could not find .witness section".to_string())),
  78. };
  79. let circuit_offset = match find_subslice(bytes, b".circuit") {
  80. Some(v) => v,
  81. None => return Err(ZkasErr("Could not find .circuit section".to_string())),
  82. };
  83. let debug_offset = match find_subslice(bytes, b".debug") {
  84. Some(v) => v,
  85. None => bytes.len(),
  86. };
  87. if constants_offset > literals_offset {
  88. return Err(ZkasErr(".literal section appeared before .constant".to_string()))
  89. }
  90. if literals_offset > witness_offset {
  91. return Err(ZkasErr(".witness section appeared before .literal".to_string()))
  92. }
  93. if witness_offset > circuit_offset {
  94. return Err(ZkasErr(".circuit section appeared before .witness".to_string()))
  95. }
  96. if circuit_offset > debug_offset {
  97. return Err(ZkasErr(".debug section appeared before .circuit or EOF".to_string()))
  98. }
  99. let constants_section = &bytes[constants_offset + b".constant".len()..literals_offset];
  100. let literals_section = &bytes[literals_offset + b".literal".len()..witness_offset];
  101. let witness_section = &bytes[witness_offset + b".witness".len()..circuit_offset];
  102. let circuit_section = &bytes[circuit_offset + b".circuit".len()..debug_offset];
  103. let constants = ZkBinary::parse_constants(constants_section)?;
  104. let literals = ZkBinary::parse_literals(literals_section)?;
  105. let witnesses = ZkBinary::parse_witness(witness_section)?;
  106. let opcodes = ZkBinary::parse_circuit(circuit_section)?;
  107. // TODO: Debug info
  108. Ok(Self { namespace, k, constants, literals, witnesses, opcodes })
  109. }
  110. fn parse_constants(bytes: &[u8]) -> Result<Vec<(VarType, String)>> {
  111. let mut constants = vec![];
  112. let mut iter_offset = 0;
  113. while iter_offset < bytes.len() {
  114. let c_type = match VarType::from_repr(bytes[iter_offset]) {
  115. Some(v) => v,
  116. None => {
  117. return Err(ZkasErr(format!(
  118. "Could not decode constant VarType from {}",
  119. bytes[iter_offset],
  120. )))
  121. }
  122. };
  123. iter_offset += 1;
  124. let (name, offset) = deserialize_partial::<String>(&bytes[iter_offset..])?;
  125. iter_offset += offset;
  126. constants.push((c_type, name));
  127. }
  128. Ok(constants)
  129. }
  130. fn parse_literals(bytes: &[u8]) -> Result<Vec<(LitType, String)>> {
  131. let mut literals = vec![];
  132. let mut iter_offset = 0;
  133. while iter_offset < bytes.len() {
  134. let l_type = match LitType::from_repr(bytes[iter_offset]) {
  135. Some(v) => v,
  136. None => {
  137. return Err(ZkasErr(format!(
  138. "Could not decode literal LitType from {}",
  139. bytes[iter_offset],
  140. )))
  141. }
  142. };
  143. iter_offset += 1;
  144. let (name, offset) = deserialize_partial::<String>(&bytes[iter_offset..])?;
  145. iter_offset += offset;
  146. literals.push((l_type, name));
  147. }
  148. Ok(literals)
  149. }
  150. fn parse_witness(bytes: &[u8]) -> Result<Vec<VarType>> {
  151. let mut witnesses = vec![];
  152. let mut iter_offset = 0;
  153. while iter_offset < bytes.len() {
  154. let w_type = match VarType::from_repr(bytes[iter_offset]) {
  155. Some(v) => v,
  156. None => {
  157. return Err(ZkasErr(format!(
  158. "Could not decode witness VarType from {}",
  159. bytes[iter_offset],
  160. )))
  161. }
  162. };
  163. iter_offset += 1;
  164. witnesses.push(w_type);
  165. }
  166. Ok(witnesses)
  167. }
  168. #[allow(clippy::type_complexity)]
  169. fn parse_circuit(bytes: &[u8]) -> Result<Vec<(Opcode, Vec<(HeapType, usize)>)>> {
  170. let mut opcodes = vec![];
  171. let mut iter_offset = 0;
  172. while iter_offset < bytes.len() {
  173. let opcode = match Opcode::from_repr(bytes[iter_offset]) {
  174. Some(v) => v,
  175. None => {
  176. return Err(ZkasErr(format!(
  177. "Could not decode Opcode from {}",
  178. bytes[iter_offset]
  179. )))
  180. }
  181. };
  182. iter_offset += 1;
  183. // TODO: Check that the types and arg number are correct
  184. let (arg_num, offset) = deserialize_partial::<VarInt>(&bytes[iter_offset..])?;
  185. iter_offset += offset;
  186. let mut args = vec![];
  187. for _ in 0..arg_num.0 {
  188. // Check bounds each time bytes[iter_offset] is accessed to prevent panics.
  189. if iter_offset >= bytes.len() {
  190. return Err(ZkasErr(format!(
  191. "Bad offset for circuit: offset {} is >= circuit length {}",
  192. iter_offset,
  193. bytes.len()
  194. )))
  195. }
  196. let heap_type = bytes[iter_offset];
  197. iter_offset += 1;
  198. if iter_offset >= bytes.len() {
  199. return Err(ZkasErr(format!(
  200. "Bad offset for circuit: offset {} is >= circuit length {}",
  201. iter_offset,
  202. bytes.len()
  203. )))
  204. }
  205. let (heap_index, offset) = deserialize_partial::<VarInt>(&bytes[iter_offset..])?;
  206. iter_offset += offset;
  207. let heap_type = match HeapType::from_repr(heap_type) {
  208. Some(v) => v,
  209. None => {
  210. return Err(ZkasErr(format!("Could not decode HeapType from {heap_type}")))
  211. }
  212. };
  213. args.push((heap_type, heap_index.0 as usize));
  214. }
  215. opcodes.push((opcode, args));
  216. }
  217. Ok(opcodes)
  218. }
  219. }
  220. #[cfg(test)]
  221. mod tests {
  222. use crate::zkas::ZkBinary;
  223. #[test]
  224. fn panic_regression_001() {
  225. // Out-of-memory panic from string deserialization.
  226. // Read `doc/src/zkas/bincode.md` to understand the input.
  227. let data = vec![11u8, 1, 177, 53, 1, 0, 0, 0, 0, 255, 0, 204, 200, 72, 72, 72, 72, 1];
  228. let _dec = ZkBinary::decode(&data);
  229. }
  230. #[test]
  231. fn panic_regression_002() {
  232. // Index out of bounds panic in parse_circuit().
  233. // Read `doc/src/zkas/bincode.md` to understand the input.
  234. let data = vec![
  235. 11u8, 1, 177, 53, 2, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 83, 105,
  236. 109, 112, 108, 101, 46, 99, 111, 110, 115, 116, 97, 110, 116, 3, 18, 86, 65, 76, 85,
  237. 69, 95, 67, 79, 77, 77, 73, 84, 95, 86, 65, 76, 85, 69, 2, 19, 86, 65, 76, 85, 69, 95,
  238. 67, 79, 77, 77, 73, 84, 95, 82, 65, 77, 68, 79, 77, 46, 108, 105, 116, 101, 114, 97,
  239. 108, 46, 119, 105, 116, 110, 101, 115, 115, 16, 18, 46, 99, 105, 114, 99, 117, 105,
  240. 116, 4, 2, 0, 2, 0, 0, 2, 2, 0, 3, 0, 1, 8, 2, 0, 4, 0, 5, 8, 1, 0, 6, 9, 1, 0, 6, 240,
  241. 1, 0, 7, 240, 41, 0, 0, 0, 1, 0, 8,
  242. ];
  243. let _dec = ZkBinary::decode(&data);
  244. }
  245. }