use grillo_manifest::{
InstructionContract, MutationContractView, RangeContract, ResolveError,
ResolvedInstructionContract,
};
use crate::touch_map::TouchMap;
#[derive(Clone, Debug)]
pub struct AccountDelta<'a> {
pub account_index: u8,
pub pre: &'a [u8],
pub post: &'a [u8],
pub pre_lamports: u64,
pub post_lamports: u64,
pub lamports_observed: bool,
}
impl<'a> AccountDelta<'a> {
pub fn new(account_index: u8, pre: &'a [u8], post: &'a [u8]) -> Self {
Self {
account_index,
pre,
post,
pre_lamports: 0,
post_lamports: 0,
lamports_observed: false,
}
}
pub fn with_lamports(mut self, pre_lamports: u64, post_lamports: u64) -> Self {
self.pre_lamports = pre_lamports;
self.post_lamports = post_lamports;
self.lamports_observed = true;
self
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Violation {
UntrackedWrite { account_index: u8, offset: u32 },
UnauthorizedAcquisition {
account_index: u8,
offset: u32,
size: u32,
},
UnauthorizedLamportDelta {
account_index: u8,
pre_lamports: u64,
post_lamports: u64,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InconclusiveReason {
DuplicateAccountSnapshot { account_index: u8 },
NoByteContract,
ParametricArgumentsRequired,
PartialTouchMap { overflowed: bool, skipped: bool },
}
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct PassEvidence {
pub observed_data_accounts: Vec<u8>,
pub observed_lamport_accounts: Vec<u8>,
pub changed: Vec<RangeContract>,
pub acquired_unchanged: Vec<RangeContract>,
pub changed_bytes: u64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Verdict {
Pass(PassEvidence),
Violation(Vec<Violation>),
Inconclusive(InconclusiveReason),
}
impl Verdict {
pub fn is_pass(&self) -> bool {
matches!(self, Verdict::Pass(_))
}
pub fn render(&self) -> String {
match self {
Verdict::Pass(ev) => {
let mut s = String::from(
"GRILLO VERDICT: SCOPED PASS (changed \u{2286} acquired \u{2286} authorized)\n",
);
s.push_str(&format!(
" observed data accounts: {:?}\n",
ev.observed_data_accounts
));
s.push_str(&format!(
" observed lamport accounts: {:?}\n",
ev.observed_lamport_accounts
));
s.push_str(&format!(
" changed: {} byte(s) in {} range(s)\n",
ev.changed_bytes,
ev.changed.len()
));
for r in &ev.changed {
s.push_str(&format!(
" - account {} [{}..{})\n",
r.account_index,
r.offset,
r.end()
));
}
if ev.acquired_unchanged.is_empty() {
s.push_str(" acquired-but-unchanged: none\n");
} else {
s.push_str(" acquired-but-unchanged (access is not modification):\n");
for r in &ev.acquired_unchanged {
s.push_str(&format!(
" - account {} [{}..{})\n",
r.account_index,
r.offset,
r.end()
));
}
}
s
}
Verdict::Violation(violations) => {
let mut s = format!(
"GRILLO VERDICT: VIOLATION ({} finding(s))\n",
violations.len()
);
for v in violations {
s.push_str(" - ");
match v {
Violation::UntrackedWrite {
account_index,
offset,
} => s.push_str(&format!(
"UntrackedWrite: account {account_index} byte {offset} changed but no \
WRITE touch record covers it (changed \u{2284} acquired)\n"
)),
Violation::UnauthorizedAcquisition {
account_index,
offset,
size,
} => s.push_str(&format!(
"UnauthorizedAcquisition: account {account_index} acquired a WRITE lease \
on [{offset}..{}) which the manifest does not authorize \
(acquired \u{2284} authorized)\n",
*offset as u64 + *size as u64
)),
Violation::UnauthorizedLamportDelta {
account_index,
pre_lamports,
post_lamports,
} => s.push_str(&format!(
"UnauthorizedLamportDelta: account {account_index} lamports \
{pre_lamports} -> {post_lamports}, not a declared lamport target\n"
)),
}
}
s
}
Verdict::Inconclusive(reason) => match reason {
InconclusiveReason::DuplicateAccountSnapshot { account_index } => format!(
"GRILLO VERDICT: INCONCLUSIVE - duplicate snapshot for account {account_index}; \
supply exactly one pre/post pair per positional index\n"
),
InconclusiveReason::NoByteContract => String::from(
"GRILLO VERDICT: INCONCLUSIVE - the instruction declares no byte-range write \
contract (strict_writes = false); nothing to verify against\n",
),
InconclusiveReason::ParametricArgumentsRequired => String::from(
"GRILLO VERDICT: INCONCLUSIVE - this instruction has parametric exact-cell \
rules; resolve the concrete invocation arguments before verification\n",
),
InconclusiveReason::PartialTouchMap {
overflowed,
skipped,
} => format!(
"GRILLO VERDICT: INCONCLUSIVE_PARTIAL_MAP - the touch map is partial \
(overflowed={overflowed}, skipped={skipped}); byte attribution is \
impossible, so no PASS may be issued\n"
),
},
}
}
}
pub fn verify(
contract: &InstructionContract,
deltas: &[AccountDelta<'_>],
touch_map: &TouchMap,
) -> Verdict {
if contract.requires_resolution() {
return Verdict::Inconclusive(InconclusiveReason::ParametricArgumentsRequired);
}
verify_contract(contract, deltas, touch_map)
}
pub fn verify_invocation(
contract: &InstructionContract,
argument_payload: &[u8],
deltas: &[AccountDelta<'_>],
touch_map: &TouchMap,
) -> Result<Verdict, ResolveError> {
let resolved = contract.resolve_effects(argument_payload)?;
Ok(verify_resolved(&resolved, deltas, touch_map))
}
pub fn verify_resolved(
contract: &ResolvedInstructionContract,
deltas: &[AccountDelta<'_>],
touch_map: &TouchMap,
) -> Verdict {
verify_contract(contract, deltas, touch_map)
}
fn verify_contract<C: MutationContractView + ?Sized>(
contract: &C,
deltas: &[AccountDelta<'_>],
touch_map: &TouchMap,
) -> Verdict {
let mut observed = [false; 256];
for delta in deltas {
if core::mem::replace(&mut observed[delta.account_index as usize], true) {
return Verdict::Inconclusive(InconclusiveReason::DuplicateAccountSnapshot {
account_index: delta.account_index,
});
}
}
if !contract.strict_writes() {
return Verdict::Inconclusive(InconclusiveReason::NoByteContract);
}
if touch_map.is_partial() {
return Verdict::Inconclusive(InconclusiveReason::PartialTouchMap {
overflowed: touch_map.overflowed,
skipped: touch_map.skipped,
});
}
let mut changed_per_account: Vec<(u8, Vec<(u32, u32)>)> = deltas
.iter()
.map(|d| (d.account_index, changed_intervals(d.pre, d.post)))
.collect();
changed_per_account.sort_unstable_by_key(|(index, _)| *index);
let mut violations = Vec::new();
let mut changed_all: Vec<RangeContract> = Vec::new();
let mut changed_bytes: u64 = 0;
for (account_index, intervals) in &changed_per_account {
let acquired: Vec<(u64, u64)> = touch_map
.records
.iter()
.filter(|r| r.write && r.slot == *account_index)
.map(|r| (r.offset as u64, r.size as u64))
.collect();
for &(offset, size) in intervals {
changed_bytes += size as u64;
changed_all.push(RangeContract {
account_index: *account_index,
offset,
size,
});
if let Some(gap) = first_gap(offset as u64, offset as u64 + size as u64, &acquired) {
violations.push(Violation::UntrackedWrite {
account_index: *account_index,
offset: gap as u32,
});
}
}
}
for rec in touch_map.records.iter().filter(|r| r.write) {
let authorized: Vec<(u64, u64)> = contract
.authorized_ranges()
.iter()
.filter(|range| range.account_index == rec.slot)
.map(|r| (r.offset as u64, r.size as u64))
.collect();
if first_gap(rec.offset as u64, rec.end(), &authorized).is_some() {
violations.push(Violation::UnauthorizedAcquisition {
account_index: rec.slot,
offset: rec.offset,
size: rec.size,
});
}
}
if contract.mutation_complete() {
for delta in deltas {
if delta.lamports_observed
&& delta.pre_lamports != delta.post_lamports
&& !contract.authorizes_lamports(delta.account_index)
{
violations.push(Violation::UnauthorizedLamportDelta {
account_index: delta.account_index,
pre_lamports: delta.pre_lamports,
post_lamports: delta.post_lamports,
});
}
}
}
if !violations.is_empty() {
return Verdict::Violation(violations);
}
let mut acquired_unchanged = Vec::new();
for rec in touch_map.records.iter().filter(|r| r.write) {
let mut observed = false;
let mut any_changed = false;
for (account_index, intervals) in &changed_per_account {
if *account_index != rec.slot {
continue;
}
observed = true;
for &(offset, size) in intervals {
let (s, e) = (offset as u64, offset as u64 + size as u64);
if s < rec.end() && (rec.offset as u64) < e {
any_changed = true;
}
}
}
if observed && !any_changed {
acquired_unchanged.push(RangeContract {
account_index: rec.slot,
offset: rec.offset,
size: rec.size,
});
}
}
let mut observed_data_accounts: Vec<u8> =
deltas.iter().map(|delta| delta.account_index).collect();
observed_data_accounts.sort_unstable();
observed_data_accounts.dedup();
let mut observed_lamport_accounts: Vec<u8> = deltas
.iter()
.filter(|delta| delta.lamports_observed)
.map(|delta| delta.account_index)
.collect();
observed_lamport_accounts.sort_unstable();
observed_lamport_accounts.dedup();
Verdict::Pass(PassEvidence {
observed_data_accounts,
observed_lamport_accounts,
changed: changed_all,
acquired_unchanged,
changed_bytes,
})
}
fn changed_intervals(pre: &[u8], post: &[u8]) -> Vec<(u32, u32)> {
let n = pre.len().max(post.len());
let mut out = Vec::new();
let mut run_start: Option<usize> = None;
for i in 0..n {
let changed = pre.get(i) != post.get(i);
match (changed, run_start) {
(true, None) => run_start = Some(i),
(false, Some(start)) => {
out.push((start as u32, (i - start) as u32));
run_start = None;
}
_ => {}
}
}
if let Some(start) = run_start {
out.push((start as u32, (n - start) as u32));
}
out
}
fn first_gap(start: u64, end: u64, cover: &[(u64, u64)]) -> Option<u64> {
let mut cursor = start;
while cursor < end {
let mut furthest = cursor;
for &(offset, size) in cover {
let cover_end = offset + size;
if offset <= cursor && cursor < cover_end && cover_end > furthest {
furthest = cover_end;
}
}
if furthest == cursor {
return Some(cursor);
}
cursor = furthest;
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn changed_intervals_coalesces_adjacent_bytes() {
let mut pre = vec![0u8; 200];
let mut post = pre.clone();
post[114] = 1;
post[115] = 1;
assert_eq!(changed_intervals(&pre, &post), vec![(114, 2)]);
pre = vec![0u8; 200];
let mut post2 = pre.clone();
post2[10] = 9;
post2[50] = 9;
assert_eq!(changed_intervals(&pre, &post2), vec![(10, 1), (50, 1)]);
}
#[test]
fn changed_intervals_flags_length_growth() {
let pre = vec![0u8; 4];
let post = vec![0u8; 8];
assert_eq!(changed_intervals(&pre, &post), vec![(4, 4)]);
}
#[test]
fn first_gap_detects_coverage_and_gaps() {
assert_eq!(first_gap(114, 123, &[(114, 1), (115, 8)]), None);
assert_eq!(first_gap(16, 17, &[(114, 1)]), Some(16));
assert_eq!(first_gap(48, 56, &[(0, u32::MAX as u64)]), None);
assert_eq!(first_gap(0, 10, &[(0, 4)]), Some(4));
}
}