import{ok,err}from"./_deps/shared/index.js";import{signMlDsa65,verifyMlDsa65}from"./identity.js";export async function createCheckpoint(e,r,t,n,o){const i=Date.now(),c=Buffer.from(r).toString("base64"),u=`DIDStateCheckpoint||1.0||${e}||${c}||${t}||${n}||${i}`,a=(new TextEncoder).encode(u),s=await signMlDsa65(o,a);return s.ok?ok({type:"DIDStateCheckpoint",version:"1.0",subject:e,current_public_key:c,revoked:t,rotation_sequence:n,timestamp:i,checkpoint_signature_algorithm:"ML-DSA-65",checkpoint_signature:Buffer.from(s.value).toString("base64")}):err("SIGN_FAILED")}export async function verifyCheckpoint(e,r){if("DIDStateCheckpoint"!==e.type)return err("INVALID_FORMAT");if("1.0"!==e.version)return err("INVALID_FORMAT");if(!e.subject||!e.current_public_key)return err("INVALID_FORMAT");if("number"!=typeof e.rotation_sequence||e.rotation_sequence<0)return err("INVALID_FORMAT");if("number"!=typeof e.timestamp||e.timestamp<=0)return err("INVALID_TIMESTAMP");if("ML-DSA-65"!==e.checkpoint_signature_algorithm)return err("INVALID_FORMAT");const t=`DIDStateCheckpoint||1.0||${e.subject}||${e.current_public_key}||${e.revoked}||${e.rotation_sequence}||${e.timestamp}`,n=(new TextEncoder).encode(t);let o;try{o=Buffer.from(e.checkpoint_signature,"base64")}catch{return err("INVALID_SIGNATURE")}const i=await verifyMlDsa65(r,o,n);return i.ok?ok(i.value):err("VERIFY_FAILED")}export function isCacheStale(e,r){if(r.rotation_sequence>e.rotationSequence)return!0;if(r.revoked!==e.revoked)return!0;const t=Buffer.from(r.current_public_key,"base64");return!Buffer.from(e.publicKey).equals(t)}export function encodeCheckpoint(e){return JSON.stringify(e)}export function decodeCheckpoint(e){try{const r=JSON.parse(e);return"DIDStateCheckpoint"!==r.type||"1.0"!==r.version?err("INVALID_FORMAT"):r.subject&&r.current_public_key&&r.checkpoint_signature?ok(r):err("INVALID_FORMAT")}catch{return err("INVALID_FORMAT")}}