Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Limit ReceiptsCtx to u16::MAX receipts #633

Merged
merged 4 commits into from
Nov 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
- If the `max_fee > policies.max_fee`, then transaction will be rejected.
- If the `witnessses_size > policies.witness_limit`, then transaction will be rejected.
- GTF opcode changed its hardcoded constants for fields. It should be updated according to the values from the specification on the Sway side.
- [#633](https://github.com/FuelLabs/fuel-vm/pull/633): Limit receipt count to `u16::MAX`.

## [Version 0.41.0]

Expand Down
2 changes: 2 additions & 0 deletions fuel-asm/src/panic_reason.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,8 @@ enum_from! {
PolicyIsNotSet = 0x28,
/// The policy is not found across policies.
PolicyNotFound = 0x29,
/// Receipt context is full
TooManyReceipts = 0x2a,
}
}

Expand Down
4 changes: 4 additions & 0 deletions fuel-vm/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,10 @@ pub enum BugVariant {
/// Refund cannot be computed in the current vm state.
#[strum(message = "Refund cannot be computed in the current vm state.")]
UncomputableRefund,

/// Receipts context is full, but there's an attempt to add more receipts.
#[strum(message = "Receipts context is full, cannot add new receipts.")]
ReceiptsCtxFull,
}

impl fmt::Display for BugVariant {
Expand Down
6 changes: 3 additions & 3 deletions fuel-vm/src/interpreter/blockchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -622,7 +622,7 @@ where

let receipt = Receipt::burn(*sub_id, *contract_id, a, *self.pc, *self.is);

append_receipt(self.append, receipt);
append_receipt(self.append, receipt)?;

Ok(inc_pc(self.pc)?)
}
Expand Down Expand Up @@ -660,7 +660,7 @@ where

let receipt = Receipt::mint(*sub_id, *contract_id, a, *self.pc, *self.is);

append_receipt(self.append, receipt);
append_receipt(self.append, receipt)?;

Ok(inc_pc(self.pc)?)
}
Expand Down Expand Up @@ -1021,7 +1021,7 @@ where
memory: self.memory,
},
receipt,
);
)?;

Ok(inc_pc(self.pc)?)
}
Expand Down
4 changes: 2 additions & 2 deletions fuel-vm/src/interpreter/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ impl<'vm, S, Tx> TransferCtx<'vm, S, Tx> {
memory: self.memory,
},
receipt,
);
)?;

Ok(inc_pc(self.pc)?)
}
Expand Down Expand Up @@ -340,7 +340,7 @@ impl<'vm, S, Tx> TransferCtx<'vm, S, Tx> {
memory: self.memory,
},
receipt,
);
)?;

Ok(inc_pc(self.pc)?)
}
Expand Down
2 changes: 1 addition & 1 deletion fuel-vm/src/interpreter/diff/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ fn reset_vm_state_receipts() {
Default::default(),
Default::default(),
);
b.receipts.push(receipt);
b.receipts.push(receipt).expect("not full");
assert_ne!(a.receipts, b.receipts);
let diff: Diff<InitialVmState> = a.diff(&b).into();
b.reset_vm_state(&diff);
Expand Down
2 changes: 1 addition & 1 deletion fuel-vm/src/interpreter/executors/instruction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -600,7 +600,7 @@ where
self.gas_charge(self.gas_costs().rvrt)?;
let a = rvrt.unpack();
let ra = r!(a);
self.revert(ra);
self.revert(ra)?;
return Ok(ExecuteState::Revert(ra))
}

Expand Down
2 changes: 1 addition & 1 deletion fuel-vm/src/interpreter/executors/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -560,7 +560,7 @@ where

let receipt = Receipt::script_result(status, gas_used);

self.append_receipt(receipt);
self.append_receipt(receipt)?;

if program.is_debug() {
self.debugger_set_last_state(program);
Expand Down
13 changes: 7 additions & 6 deletions fuel-vm/src/interpreter/flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ where
input.ret_data(a, b)
}

pub(crate) fn revert(&mut self, a: Word) {
pub(crate) fn revert(&mut self, a: Word) -> SimpleResult<()> {
let current_contract =
current_contract(&self.context, self.registers.fp(), self.memory.as_ref())
.map_or_else(|_| Some(ContractId::zeroed()), Option::<&_>::copied);
Expand Down Expand Up @@ -172,7 +172,8 @@ where
};
self.panic_context = PanicContext::None;

self.append_receipt(receipt);
self.append_receipt(receipt)
.expect("Appending a panic receipt cannot fail");
}
}

Expand Down Expand Up @@ -227,7 +228,7 @@ impl RetCtx<'_> {
set_frame_pointer(context, registers.fp_mut(), fp);
}

append_receipt(self.append, receipt);
append_receipt(self.append, receipt)?;

Ok(inc_pc(self.registers.pc_mut())?)
}
Expand Down Expand Up @@ -261,15 +262,15 @@ pub(crate) fn revert(
pc: Reg<PC>,
is: Reg<IS>,
a: Word,
) {
) -> SimpleResult<()> {
let receipt = Receipt::revert(
current_contract.unwrap_or_else(ContractId::zeroed),
a,
*pc,
*is,
);

append_receipt(append, receipt);
append_receipt(append, receipt)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
Expand Down Expand Up @@ -628,7 +629,7 @@ where
memory: self.memory.memory,
},
receipt,
);
)?;

self.frames.push(frame);

Expand Down
2 changes: 1 addition & 1 deletion fuel-vm/src/interpreter/flow/ret_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ fn test_revert() {
};
let pc = 10;
let is = 20;
revert(append, None, Reg::new(&pc), Reg::new(&is), 99);
revert(append, None, Reg::new(&pc), Reg::new(&is), 99).expect("should be ok");
assert_eq!(
*receipts.as_ref().last().unwrap(),
Receipt::revert(ContractId::default(), 99, pc, is)
Expand Down
8 changes: 5 additions & 3 deletions fuel-vm/src/interpreter/internal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ where
update_memory_output(&mut self.tx, &mut self.memory, tx_offset, idx)
}

pub(crate) fn append_receipt(&mut self, receipt: Receipt) {
pub(crate) fn append_receipt(&mut self, receipt: Receipt) -> SimpleResult<()> {
let tx_offset = self.tx_offset();
append_receipt(
AppendReceipt {
Expand Down Expand Up @@ -128,14 +128,14 @@ pub(crate) struct AppendReceipt<'vm> {
pub memory: &'vm mut [u8; MEM_SIZE],
}

pub(crate) fn append_receipt(input: AppendReceipt, receipt: Receipt) {
pub(crate) fn append_receipt(input: AppendReceipt, receipt: Receipt) -> SimpleResult<()> {
let AppendReceipt {
receipts,
script,
tx_offset,
memory,
} = input;
receipts.push(receipt);
receipts.push(receipt)?;

if let Some(script) = script {
let offset = tx_offset + script.receipts_root_offset();
Expand All @@ -151,6 +151,8 @@ pub(crate) fn append_receipt(input: AppendReceipt, receipt: Receipt) {
// guaranteed to fit
memory[offset..offset + Bytes32::LEN].copy_from_slice(&root[..]);
}

Ok(())
}

impl<S, Tx, Ecal> Interpreter<S, Tx, Ecal> {
Expand Down
4 changes: 2 additions & 2 deletions fuel-vm/src/interpreter/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ impl LogInput<'_> {
memory: self.memory,
},
receipt,
);
)?;

Ok(inc_pc(self.pc)?)
}
Expand All @@ -128,7 +128,7 @@ impl LogInput<'_> {
memory: self.memory,
},
receipt,
);
)?;

Ok(inc_pc(self.pc)?)
}
Expand Down
43 changes: 38 additions & 5 deletions fuel-vm/src/interpreter/receipts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use core::{
mem,
ops::Index,
};
use fuel_asm::PanicReason;

use fuel_merkle::binary::root_calculator::MerkleRootCalculator as MerkleTree;
use fuel_tx::Receipt;
Expand All @@ -11,6 +12,14 @@ use fuel_types::{
Bytes32,
};

use crate::{
error::SimpleResult,
prelude::{
Bug,
BugVariant,
},
};

/// Receipts and the associated Merkle tree
#[derive(Debug, Default, Clone)]
pub struct ReceiptsCtx {
Expand All @@ -19,10 +28,33 @@ pub struct ReceiptsCtx {
}

impl ReceiptsCtx {
/// Add a new receipt, updating the Merkle tree as well
pub fn push(&mut self, receipt: Receipt) {
/// The maximum number of receipts that can be stored in a single context.
/// https://github.com/FuelLabs/fuel-specs/blob/master/src/fuel-vm/instruction-set.md#Receipts
pub const MAX_RECEIPTS: usize = u16::MAX as usize;

/// Add a new receipt, updating the Merkle tree as well.
/// Returns a panic if the context is full.
pub fn push(&mut self, receipt: Receipt) -> SimpleResult<()> {
if self.receipts.len() == Self::MAX_RECEIPTS {
return Err(Bug::new(BugVariant::ReceiptsCtxFull).into())
}

// Last two slots can be only used for ending the script,
// with a script result optinally preceded by a panic
if (self.receipts.len() == Self::MAX_RECEIPTS - 1
&& !matches!(receipt, Receipt::ScriptResult { .. }))
|| (self.receipts.len() == Self::MAX_RECEIPTS - 2
&& !matches!(
receipt,
Receipt::ScriptResult { .. } | Receipt::Panic { .. }
))
{
return Err(PanicReason::TooManyReceipts.into())
}

self.receipts_tree.push(receipt.to_bytes().as_slice());
self.receipts.push(receipt)
self.receipts.push(receipt);
Ok(())
}

/// Reset the context to an empty state
Expand Down Expand Up @@ -83,11 +115,12 @@ impl PartialEq for ReceiptsCtx {

impl Eq for ReceiptsCtx {}

#[cfg(any(test, feature = "test-helpers"))]
impl From<Vec<Receipt>> for ReceiptsCtx {
fn from(receipts: Vec<Receipt>) -> Self {
let mut ctx = Self::default();
for receipt in receipts {
ctx.push(receipt)
ctx.push(receipt).expect("Too many receipts");
}
ctx
}
Expand Down Expand Up @@ -158,7 +191,7 @@ mod tests {
let mut ctx = ReceiptsCtx::default();
let receipts = iter::repeat(create_receipt()).take(5);
for receipt in receipts.clone() {
ctx.push(receipt)
ctx.push(receipt).expect("context not full");
}

let root = ctx.root();
Expand Down
1 change: 1 addition & 0 deletions fuel-vm/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ mod metadata;
mod outputs;
mod predicate;
mod profile_gas;
mod receipts;
mod serde_profile;
mod spec;
mod validation;
Expand Down
70 changes: 70 additions & 0 deletions fuel-vm/src/tests/receipts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
use fuel_asm::{
op,
PanicReason,
RegId,
};
use fuel_tx::{
Receipt,
ScriptExecutionResult,
};

use alloc::vec;

use crate::interpreter::ReceiptsCtx;

use super::test_helpers::run_script;

#[test]
fn too_many_receipts_panics() {
let receipts = run_script(vec![
op::log(RegId::ZERO, RegId::ZERO, RegId::ZERO, RegId::ZERO),
op::jmpb(RegId::ZERO, 0),
]);

assert_eq!(receipts.len(), ReceiptsCtx::MAX_RECEIPTS);

// The panic receipt should have still been pushed correctly
let Receipt::Panic { reason, .. } = receipts[ReceiptsCtx::MAX_RECEIPTS - 2] else {
panic!("Expect panic receipt");
};
assert_eq!(*reason.reason(), PanicReason::TooManyReceipts);
}

#[test]
fn can_panic_just_before_max_receipts() {
let receipts = run_script(vec![
op::movi(0x10, ReceiptsCtx::MAX_RECEIPTS as u32 - 2),
op::log(RegId::ZERO, RegId::ZERO, RegId::ZERO, RegId::ZERO),
op::subi(0x10, 0x10, 1),
op::jnzb(0x10, RegId::ZERO, 1),
op::div(0x10, RegId::ZERO, RegId::ZERO), // Divide by zero
]);

assert_eq!(receipts.len(), ReceiptsCtx::MAX_RECEIPTS);

// The panic receipt should have still been pushed correctly
let Receipt::Panic { reason, .. } = receipts[ReceiptsCtx::MAX_RECEIPTS - 2] else {
panic!("Expect panic receipt");
};
assert_eq!(*reason.reason(), PanicReason::ArithmeticError);
}

#[test]
fn can_return_successfully_just_below_max_receipts() {
let receipts = run_script(vec![
op::movi(0x10, ReceiptsCtx::MAX_RECEIPTS as u32 - 3),
op::log(RegId::ZERO, RegId::ZERO, RegId::ZERO, RegId::ZERO),
op::subi(0x10, 0x10, 1),
op::jnzb(0x10, RegId::ZERO, 1),
op::ret(RegId::ONE),
]);

assert_eq!(receipts.len(), ReceiptsCtx::MAX_RECEIPTS - 1);

// The panic receipt should have still been pushed correctly
let Receipt::ScriptResult { result, .. } = receipts[ReceiptsCtx::MAX_RECEIPTS - 2]
else {
panic!("Expect result receipt");
};
assert_eq!(result, ScriptExecutionResult::Success);
}
Loading