use super::{METHOD, PACKET_LIMIT, Target, original};
use crate::{files, network::Client, overview::hex};
use clap::Args;
use ic_host_fs::Directory;
use ic_platform::native::{Dispatch as NativeDispatch, PreparedUpdate, RequestStatus};
use ic_platform_protocol::caffeine as c;
use ic_platform_types::Principal;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::path::PathBuf;
const LIMITS: usize = 8192;
const INTENT_PREFIX: [u8; 17] = *b"blob-certificate\x01";
#[derive(Args)]
pub(crate) struct Input {
#[command(flatten)]
pub(super) target: Target,
#[arg(long)]
custody: PathBuf,
}
#[derive(Args)]
pub(crate) struct Dispatch {
#[command(flatten)]
input: Input,
#[arg(long)]
checkout: PathBuf,
}
#[derive(Deserialize, Serialize)]
struct Intent {
format: [u8; INTENT_PREFIX.len()],
url: String,
canister: Principal,
uploader: Principal,
root: String,
root_key_hash: [u8; 32],
packet_hash: [u8; 32],
}
impl Input {
pub(super) fn directory(&self, agent: &Client) -> PathBuf {
self.custody
.join(hex(&Sha256::digest(&agent.root)))
.join(self.target.canister.to_text())
.join(&self.target.root[7..])
}
}
pub(crate) fn prepare(input: &Input) -> Result<String, String> {
let agent = input.target.client()?;
let signed = agent.prepare(
input.target.canister,
input.target.canister,
METHOD,
&c::encode_root(&input.target.root, 1024).map_err(|_| "cannot encode root")?,
)?;
if signed.envelope_bytes().len() > PACKET_LIMIT {
return Err("signed request exceeds custody budget".into());
}
let intent = Intent {
format: INTENT_PREFIX,
url: input.target.network.url.to_string(),
canister: input.target.canister,
uploader: input.target.uploader,
root: input.target.root.clone(),
root_key_hash: Sha256::digest(&agent.root).into(),
packet_hash: Sha256::digest(signed.envelope_bytes()).into(),
};
let bytes = ic_blob_storage::storage_codec::encode(&intent, LIMITS)
.map_err(|_| "cannot encode certificate intent")?;
let directory = input.directory(&agent);
let parent = files::directory(directory.parent().ok_or("missing custody parent")?, true)
.map_err(|_| "cannot admit certificate custody")?;
let claim = parent.create_directory(directory.file_name().ok_or("missing root name")?, 0o700, 0o077)
.map_err(|_| "certificate root already claimed or custody unavailable; preserve it, do not reprepare")?;
files::publish(&claim, "intent.wire".as_ref(), &bytes)?;
files::publish(&claim, "request.cbor".as_ref(), signed.envelope_bytes())?;
Ok(format!(
"Prepared original request={} without submission.\nRetain request at {:?}; expires in 120 seconds, never renew it.",
hex(signed.request_id()),
directory.join("request.cbor")
))
}
pub(super) fn load(input: &Input, agent: &Client) -> Result<(Directory, PreparedUpdate), String> {
let target = &input.target;
let directory = input.directory(agent);
let held = files::directory(&directory, false)?;
let intent: Intent = ic_blob_storage::storage_codec::decode_with_prefix(
&files::read_at(&held, "intent.wire".as_ref(), LIMITS)?,
LIMITS,
&INTENT_PREFIX,
)
.map_err(|_| "invalid retained certificate intent")?;
let packet = files::read_at(&held, "request.cbor".as_ref(), PACKET_LIMIT)?;
if intent.url != target.network.url.as_str()
|| intent.canister != target.canister
|| intent.uploader != target.uploader
|| intent.root != target.root
|| intent.root_key_hash != <[u8; 32]>::from(Sha256::digest(&agent.root))
|| intent.packet_hash != <[u8; 32]>::from(Sha256::digest(&packet))
{
return Err("certificate custody does not match original bindings and packet".into());
}
let signed = original(&packet, target.uploader, target.canister, &target.root)?;
Ok((held, signed))
}
pub(crate) async fn dispatch(input: Dispatch) -> Result<String, String> {
let agent = input.input.target.client()?;
let target = &input.input.target;
let (held, prepared) = load(&input.input, &agent)?;
crate::management::admit_tooling(&input.checkout).await?;
crate::network::require_unexpired(prepared.expiry())?;
files::publish(&held, "dispatch.claim".as_ref(), prepared.request_id())?;
let result = agent.transport.dispatch(&prepared, crate::network::policy(false)?).await
.map_err(|_| "certificate dispatch outcome uncertain; preserve custody and recover the original request, never resubmit")?;
match result {
NativeDispatch::UncertifiedRejection { .. } => {
return Err(
"uncertified dispatch rejection; preserve custody and recover the original request"
.into(),
);
}
NativeDispatch::Observed(observed) => match observed.status() {
RequestStatus::Replied(bytes) => super::admit_reply(bytes, &target.root)?,
RequestStatus::Rejected { .. } => {
return Err("original request rejected; preserve custody, no resubmission".into());
}
RequestStatus::Done | RequestStatus::Unavailable => {
return Err(
"original outcome unavailable; preserve custody, no resubmission".into(),
);
}
RequestStatus::Unknown | RequestStatus::Received | RequestStatus::Processing => {}
},
NativeDispatch::Accepted => {}
}
Ok(format!(
"Original request={} dispatched; preserve custody and use blob certificate recover.\nNo provider acceptance or availability is established.",
hex(prepared.request_id())
))
}