use serde::Deserialize;
use crate::touch_map::decode_touch_map;
use crate::verify::{verify, verify_invocation, AccountDelta, Verdict};
use grillo_manifest::{MutationManifest, ResolveError};
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BundleAccount {
pub index: u8,
pub pre: String,
pub post: String,
#[serde(rename = "preLamports", default)]
pub pre_lamports: Option<u64>,
#[serde(rename = "postLamports", default)]
pub post_lamports: Option<u64>,
}
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EvidenceBundle {
pub instruction: String,
#[serde(rename = "argumentPayload", default)]
pub argument_payload: Option<String>,
#[serde(rename = "touchMap")]
pub touch_map: String,
pub accounts: Vec<BundleAccount>,
}
#[derive(Debug)]
pub enum BundleError {
Json(String),
Hex { field: String, message: String },
UnknownInstruction(String),
TouchMap(String),
LamportsHalfObserved { index: u8 },
DuplicateAccountSnapshot { index: u8 },
Resolve(ResolveError),
}
impl core::fmt::Display for BundleError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
BundleError::Json(m) => write!(f, "bundle JSON error: {m}"),
BundleError::Hex { field, message } => {
write!(f, "bundle field `{field}` is not valid hex: {message}")
}
BundleError::UnknownInstruction(name) => {
write!(f, "manifest has no instruction named `{name}`")
}
BundleError::TouchMap(m) => write!(f, "touch map blob rejected: {m}"),
BundleError::LamportsHalfObserved { index } => write!(
f,
"account {index}: preLamports/postLamports must be provided together or not at all"
),
BundleError::Resolve(e) => write!(f, "parametric resolution failed: {e}"),
BundleError::DuplicateAccountSnapshot { index } => {
write!(f, "account {index}: duplicate snapshot index")
}
}
}
}
impl std::error::Error for BundleError {}
fn decode_hex(field: &str, s: &str) -> Result<Vec<u8>, BundleError> {
let s = s.trim();
if !s.len().is_multiple_of(2) {
return Err(BundleError::Hex {
field: field.to_string(),
message: "odd number of hex digits".to_string(),
});
}
let mut out = Vec::with_capacity(s.len() / 2);
let bytes = s.as_bytes();
let nibble = |c: u8| -> Result<u8, BundleError> {
match c {
b'0'..=b'9' => Ok(c - b'0'),
b'a'..=b'f' => Ok(c - b'a' + 10),
b'A'..=b'F' => Ok(c - b'A' + 10),
other => Err(BundleError::Hex {
field: field.to_string(),
message: format!("invalid hex character `{}`", other as char),
}),
}
};
let mut i = 0;
while i < bytes.len() {
out.push((nibble(bytes[i])? << 4) | nibble(bytes[i + 1])?);
i += 2;
}
Ok(out)
}
pub fn parse_bundle(json: &str) -> Result<EvidenceBundle, BundleError> {
serde_json::from_str(json).map_err(|e| BundleError::Json(e.to_string()))
}
pub fn verify_bundle(
manifest: &MutationManifest,
bundle: &EvidenceBundle,
) -> Result<Verdict, BundleError> {
let contract = manifest
.instruction(&bundle.instruction)
.ok_or_else(|| BundleError::UnknownInstruction(bundle.instruction.clone()))?;
let map_bytes = decode_hex("touchMap", &bundle.touch_map)?;
let touch_map =
decode_touch_map(&map_bytes).map_err(|e| BundleError::TouchMap(format!("{e:?}")))?;
type DecodedAccount = (u8, Vec<u8>, Vec<u8>, Option<(u64, u64)>);
let mut observed = [false; 256];
for account in &bundle.accounts {
if core::mem::replace(&mut observed[account.index as usize], true) {
return Err(BundleError::DuplicateAccountSnapshot {
index: account.index,
});
}
}
let mut decoded: Vec<DecodedAccount> = Vec::with_capacity(bundle.accounts.len());
for account in &bundle.accounts {
let pre = decode_hex(&format!("accounts[{}].pre", account.index), &account.pre)?;
let post = decode_hex(&format!("accounts[{}].post", account.index), &account.post)?;
let lamports = match (account.pre_lamports, account.post_lamports) {
(Some(a), Some(b)) => Some((a, b)),
(None, None) => None,
_ => {
return Err(BundleError::LamportsHalfObserved {
index: account.index,
})
}
};
decoded.push((account.index, pre, post, lamports));
}
let deltas: Vec<AccountDelta<'_>> = decoded
.iter()
.map(|(index, pre, post, lamports)| {
let delta = AccountDelta::new(*index, pre, post);
match lamports {
Some((a, b)) => delta.with_lamports(*a, *b),
None => delta,
}
})
.collect();
match &bundle.argument_payload {
Some(payload_hex) => {
let payload = decode_hex("argumentPayload", payload_hex)?;
verify_invocation(contract, &payload, &deltas, &touch_map).map_err(BundleError::Resolve)
}
None => Ok(verify(contract, &deltas, &touch_map)),
}
}