grillo_verifier/touch_map.rs
1//! Decoder for the Hopper **touch-map wire format v1**, the public,
2//! versioned record a Hopper program emits (one `sol_log_data` segment)
3//! describing the `(account, offset, size, R/W)` ranges recorded during an
4//! instruction. Overflow and skipped-record flags identify partial maps.
5//!
6//! This decodes the same format used by `hopper tx explain`
7//! (`tools/hopper-cli/src/cmd/tx_explain.rs`), the generated TypeScript
8//! client, and the runtime's own tests. The format is documented in
9//! `hopper-runtime/src/segment_borrow.rs`:
10//!
11//! ```text
12//! byte 0 magic = 0x7A
13//! byte 1 version = 0x01
14//! byte 2 flags bit0 = overflowed (log truncated, map is PARTIAL)
15//! bit1 = skipped (a record could not be represented)
16//! byte 3 count number of records (each 9 bytes)
17//! then per record (9 bytes):
18//! +0 slot u8 account index into the instruction's account list
19//! +1..+5 packed u32 LE; bit31 = write, low 31 bits = byte offset
20//! +5..+9 size u32 LE
21//! ```
22//!
23//! A decoder MUST verify magic, version, AND the exact-length equation
24//! `len == 4 + 9 * count`. These checks reject unrelated `Program data:`
25//! payloads that do not satisfy the touch-map framing.
26
27/// Magic byte of the touch-map wire format v1 (`'z'`).
28pub const TOUCH_MAP_MAGIC: u8 = 0x7A;
29/// Touch-map wire format version.
30pub const TOUCH_MAP_VERSION: u8 = 0x01;
31/// Flags bit0: the on-chain touch log overflowed; the map is partial.
32pub const TOUCH_MAP_FLAG_OVERFLOWED: u8 = 1 << 0;
33/// Flags bit1: the encoder skipped at least one record it could not
34/// represent (unmappable address, or offset beyond 31 bits).
35pub const TOUCH_MAP_FLAG_SKIPPED: u8 = 1 << 1;
36/// Fixed header length (magic, version, flags, count).
37pub const TOUCH_MAP_HEADER_LEN: usize = 4;
38/// Encoded length of one touch record.
39pub const TOUCH_MAP_RECORD_LEN: usize = 9;
40/// Capacity of the on-chain touch log. This caps *slots*, not coverage:
41/// at capacity the runtime coalesces records whose union is exactly the
42/// touched byte set (contiguous same-kind workloads stay complete and unflagged);
43/// the overflow flag means the instruction touched more than this many
44/// pairwise-unmergeable ranges and the map is genuinely partial.
45pub const MAX_TOUCH_RECORDS: usize = 32;
46
47/// One decoded touch record: a single `(account, offset, size, R/W)` range
48/// the instruction touched.
49///
50/// `slot` is the account's index in the instruction's account list, the
51/// same index a manifest [`RangeContract`](grillo_manifest::RangeContract)
52/// and the runtime `Context` use, so the three join directly.
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub struct TouchRecord {
55 /// Account slot index into the instruction's account list.
56 pub slot: u8,
57 /// Byte offset within the account data.
58 pub offset: u32,
59 /// Byte length of the touched range.
60 pub size: u32,
61 /// Write access (`true`) or read access (`false`).
62 pub write: bool,
63}
64
65impl TouchRecord {
66 /// Exclusive end offset, widened to `u64` so it cannot overflow.
67 pub fn end(&self) -> u64 {
68 self.offset as u64 + self.size as u64
69 }
70}
71
72/// A decoded touch map, with its honesty flags preserved.
73#[derive(Clone, Debug, PartialEq, Eq)]
74pub struct TouchMap {
75 /// The touch log overflowed [`MAX_TOUCH_RECORDS`]; the map is a partial
76 /// view of the instruction's effects.
77 pub overflowed: bool,
78 /// The encoder dropped at least one touched range it could not
79 /// represent; the map is partial.
80 pub skipped: bool,
81 /// The decoded records, in first-touch order.
82 pub records: Vec<TouchRecord>,
83}
84
85impl TouchMap {
86 /// A partial map (`overflowed` or `skipped`) does NOT enumerate the
87 /// instruction's complete effect set, so byte attribution against it is
88 /// impossible, a verifier must return `INCONCLUSIVE`, never `PASS`.
89 pub fn is_partial(&self) -> bool {
90 self.overflowed || self.skipped
91 }
92
93 /// The WRITE records only (the `acquired` write-set).
94 pub fn writes(&self) -> impl Iterator<Item = &TouchRecord> {
95 self.records.iter().filter(|r| r.write)
96 }
97}
98
99/// Why a byte slice is not a valid touch-map v1 payload.
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101pub enum DecodeError {
102 /// Fewer than the 4-byte header.
103 TooShort { len: usize },
104 /// First byte was not [`TOUCH_MAP_MAGIC`].
105 BadMagic(u8),
106 /// Second byte was not [`TOUCH_MAP_VERSION`].
107 BadVersion(u8),
108 /// The exact-length equation `len == 4 + 9 * count` did not hold. This
109 /// is what keeps foreign `Program data:` payloads out.
110 LengthMismatch {
111 declared_count: usize,
112 expected_len: usize,
113 actual_len: usize,
114 },
115}
116
117impl core::fmt::Display for DecodeError {
118 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
119 match self {
120 DecodeError::TooShort { len } => {
121 write!(
122 f,
123 "touch map too short: {len} bytes (need >= {TOUCH_MAP_HEADER_LEN})"
124 )
125 }
126 DecodeError::BadMagic(b) => {
127 write!(
128 f,
129 "bad touch-map magic: 0x{b:02x} (expected 0x{TOUCH_MAP_MAGIC:02x})"
130 )
131 }
132 DecodeError::BadVersion(b) => {
133 write!(
134 f,
135 "bad touch-map version: 0x{b:02x} (expected 0x{TOUCH_MAP_VERSION:02x})"
136 )
137 }
138 DecodeError::LengthMismatch {
139 declared_count,
140 expected_len,
141 actual_len,
142 } => write!(
143 f,
144 "touch-map length mismatch: count {declared_count} implies {expected_len} bytes, \
145 got {actual_len}"
146 ),
147 }
148 }
149}
150
151impl std::error::Error for DecodeError {}
152
153/// Decode a touch-map `sol_log_data` payload. Returns an error unless the
154/// magic, version, and exact-length equation all hold.
155pub fn decode_touch_map(bytes: &[u8]) -> Result<TouchMap, DecodeError> {
156 if bytes.len() < TOUCH_MAP_HEADER_LEN {
157 return Err(DecodeError::TooShort { len: bytes.len() });
158 }
159 if bytes[0] != TOUCH_MAP_MAGIC {
160 return Err(DecodeError::BadMagic(bytes[0]));
161 }
162 if bytes[1] != TOUCH_MAP_VERSION {
163 return Err(DecodeError::BadVersion(bytes[1]));
164 }
165 let flags = bytes[2];
166 let count = bytes[3] as usize;
167 let expected_len = TOUCH_MAP_HEADER_LEN + count * TOUCH_MAP_RECORD_LEN;
168 if bytes.len() != expected_len {
169 return Err(DecodeError::LengthMismatch {
170 declared_count: count,
171 expected_len,
172 actual_len: bytes.len(),
173 });
174 }
175
176 let mut records = Vec::with_capacity(count);
177 for i in 0..count {
178 let base = TOUCH_MAP_HEADER_LEN + i * TOUCH_MAP_RECORD_LEN;
179 // Infallible slicing: the length equation above guarantees these
180 // ranges are in bounds.
181 let packed = u32::from_le_bytes(bytes[base + 1..base + 5].try_into().unwrap());
182 let size = u32::from_le_bytes(bytes[base + 5..base + 9].try_into().unwrap());
183 records.push(TouchRecord {
184 slot: bytes[base],
185 offset: packed & 0x7FFF_FFFF,
186 size,
187 write: packed & 0x8000_0000 != 0,
188 });
189 }
190
191 Ok(TouchMap {
192 overflowed: flags & TOUCH_MAP_FLAG_OVERFLOWED != 0,
193 skipped: flags & TOUCH_MAP_FLAG_SKIPPED != 0,
194 records,
195 })
196}