From ea47d4a67c6a18e4a7d3a49079d9eb24a1026a25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=81lvaro=20Rodr=C3=ADguez?= Date: Tue, 13 Feb 2024 16:17:27 +0100 Subject: [PATCH] fix: Brillig range check with consistent bit size (#4357) # Description ## Problem\* Partial work towards #4275 ## Summary\* ## Additional Context Tested in aztec-packages here https://github.com/AztecProtocol/aztec-packages/pull/4556 ## Documentation\* Check one: - [x] No documentation needed. - [ ] Documentation included in this PR. - [ ] **[Exceptional Case]** Documentation to be submitted in a separate PR. # PR Checklist\* - [x] I have tested the changes locally. - [x] I have formatted the changes with [Prettier](https://prettier.io/) and/or `cargo fmt` on default settings. --- .../src/brillig/brillig_gen/brillig_block.rs | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_block.rs b/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_block.rs index 84b719f29aa..7697d7e65fa 100644 --- a/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_block.rs +++ b/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_block.rs @@ -619,23 +619,29 @@ impl<'block> BrilligBlock<'block> { ); } Instruction::RangeCheck { value, max_bit_size, assert_message } => { - let left = self.convert_ssa_register_value(*value, dfg); - let max = BigUint::from(2_u128).pow(*max_bit_size); - let right = self.brillig_context.allocate_register(); - self.brillig_context.const_instruction( - right, + let value = self.convert_ssa_register_value(*value, dfg); + // Cast original value to field + let left = self.brillig_context.allocate_register(); + self.convert_cast(left, value, &Type::field()); + + // Create a field constant with the max + let max = BigUint::from(2_u128).pow(*max_bit_size) - BigUint::from(1_u128); + let right = self.brillig_context.make_constant( FieldElement::from_be_bytes_reduce(&max.to_bytes_be()).into(), FieldElement::max_num_bits(), ); + // Check if lte max let brillig_binary_op = BrilligBinaryOp::Integer { - op: BinaryIntOp::LessThan, - bit_size: max_bit_size + 1, + op: BinaryIntOp::LessThanEquals, + bit_size: FieldElement::max_num_bits(), }; let condition = self.brillig_context.allocate_register(); self.brillig_context.binary_instruction(left, right, condition, brillig_binary_op); + self.brillig_context.constrain_instruction(condition, assert_message.clone()); self.brillig_context.deallocate_register(condition); + self.brillig_context.deallocate_register(left); self.brillig_context.deallocate_register(right); } Instruction::IncrementRc { value } => {