decoder.rs 10 KB

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