lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

issuance.rs (13676B)


      1 //! Synthetic real-signature S workflow through the actual protected host.
      2 use super::{WorkspaceFixture, copied, plans::BrowserRng};
      3 use core::num::NonZeroU64;
      4 use futures::FutureExt;
      5 use nostr::JsonUtil;
      6 use radroots_storage::command::{
      7     ArtifactEvidence, ClaimAttemptOutcome, ClaimAttemptRequest, EvidenceCaptureOutcome,
      8     EvidenceReceipt, SigningAttempt,
      9 };
     10 use wasm_bindgen::prelude::*;
     11 
     12 fn summary(attempt: &SigningAttempt) -> Vec<u8> {
     13     let mut raw = attempt.attempt_id().as_bytes().to_vec();
     14     raw.extend_from_slice(attempt.transaction_id().as_bytes());
     15     raw.extend_from_slice(attempt.binding().digest());
     16     raw.extend_from_slice(&attempt.claimed_at().get().to_be_bytes());
     17     raw.extend_from_slice(&attempt.deadline_unix_ms().get().to_be_bytes());
     18     raw.extend_from_slice(&attempt.artifact().unwrap().event_id());
     19     raw
     20 }
     21 fn receipt(value: EvidenceReceipt) -> Vec<u8> {
     22     let mut raw = value.transaction_id().as_bytes().to_vec();
     23     raw.extend_from_slice(value.digest());
     24     raw.extend_from_slice(value.attempt_id().as_bytes());
     25     raw.extend_from_slice(
     26         &value
     27             .observed_at_unix_ms()
     28             .map_or(0, NonZeroU64::get)
     29             .to_be_bytes(),
     30     );
     31     raw.extend_from_slice(value.event_id().as_bytes());
     32     raw
     33 }
     34 fn signed_output(
     35     attempt: &SigningAttempt,
     36     observed: Option<NonZeroU64>,
     37 ) -> Result<ArtifactEvidence, JsValue> {
     38     let artifact = attempt.artifact().unwrap();
     39     let fields = artifact.fields();
     40     let context = nostr::secp256k1::Secp256k1::new();
     41     let mut scalar = [0; 32];
     42     scalar[31] = 1;
     43     let keys = nostr::Keys::new_with_ctx(&context, nostr::SecretKey::from_slice(&scalar).unwrap());
     44     assert_eq!(keys.public_key().as_bytes(), fields.author.as_bytes());
     45     let signed = nostr::UnsignedEvent {
     46         id: None,
     47         pubkey: keys.public_key(),
     48         created_at: nostr::Timestamp::from_secs(fields.created_at),
     49         kind: nostr::Kind::Custom(u16::try_from(fields.kind).unwrap()),
     50         tags: nostr::Tags::from_list(
     51             fields
     52                 .tags
     53                 .iter()
     54                 .map(|tag| nostr::Tag::parse(tag).unwrap())
     55                 .collect(),
     56         ),
     57         content: fields.content.to_owned(),
     58     }
     59     .sign_with_ctx(&context, &mut BrowserRng, &keys)
     60     .unwrap();
     61     signed.verify_with_ctx(&context).unwrap();
     62     ArtifactEvidence::verify(attempt, &signed.as_json(), observed)
     63         .map_err(|e| JsValue::from_str(e.code()))
     64 }
     65 /// The test caller keeps its opaque original through failed/unknown capture.
     66 #[wasm_bindgen]
     67 pub struct ObtainedSeal {
     68     value: ArtifactEvidence,
     69     attempt: SigningAttempt,
     70 }
     71 #[wasm_bindgen]
     72 impl ObtainedSeal {
     73     pub fn original_claim(&self) -> Vec<u8> {
     74         summary(&self.attempt)
     75     }
     76     pub fn digest(&self) -> Vec<u8> {
     77         self.value.digest().to_vec()
     78     }
     79     pub fn malformed_output_refused(&self) -> bool {
     80         let original: serde_json::Value = serde_json::from_str(self.value.raw_json()).unwrap();
     81         ["sig", "pubkey", "content", "kind"]
     82             .into_iter()
     83             .all(|field| {
     84                 let mut wrong = original.clone();
     85                 wrong[field] = match field {
     86                     "sig" => serde_json::json!("00".repeat(64)),
     87                     "pubkey" => serde_json::json!("00".repeat(32)),
     88                     "content" => serde_json::json!("wrong captured body"),
     89                     "kind" => serde_json::json!(14),
     90                     _ => unreachable!(),
     91                 };
     92                 ArtifactEvidence::verify(
     93                     &self.attempt,
     94                     &serde_json::to_string(&wrong).unwrap(),
     95                     None,
     96                 )
     97                 .is_err()
     98             })
     99     }
    100 }
    101 impl WorkspaceFixture {
    102     async fn claim_request(&self, n: u8, index: u8) -> Result<ClaimAttemptRequest, JsValue> {
    103         let request = if index == 2 {
    104             self.public_request(n).await?
    105         } else {
    106             self.request(n, false).await?
    107         };
    108         let bound = self
    109             .journal()
    110             .signing_plan(
    111                 request.binding().clone(),
    112                 request.command().context().operation_id(),
    113                 request.command().digest(),
    114                 copied(&self.proof),
    115             )
    116             .await
    117             .map_err(|e| JsValue::from_str(e.code()))?
    118             .ok_or(JsValue::from_str("missing_plan"))?;
    119         let recipient = if index == 2 {
    120             radroots_storage::command::SigningTarget::PublicEvent
    121         } else {
    122             bound
    123                 .chat_plan()
    124                 .unwrap()
    125                 .seals()
    126                 .get(index as usize)
    127                 .ok_or(JsValue::from_str("invalid_recipient"))?
    128                 .recipient()
    129                 .into()
    130         };
    131         Ok(ClaimAttemptRequest::for_artifact(
    132             request.binding().clone(),
    133             request.command().context().operation_id(),
    134             request.command().digest(),
    135             *bound.plan().digest(),
    136             recipient,
    137         ))
    138     }
    139 }
    140 #[wasm_bindgen]
    141 impl WorkspaceFixture {
    142     /// Queries through the actual original request even when retained T1 is
    143     /// damaged; fixture request reconstruction must not hide the host refusal.
    144     pub async fn captured_original(&self, original: &ObtainedSeal) -> Result<Vec<u8>, JsValue> {
    145         let bound = original.attempt.bound_plan();
    146         let identity = bound.prepared().identity();
    147         let request = ClaimAttemptRequest::new(
    148             bound.prepared().request().binding().clone(),
    149             identity.operation_id(),
    150             identity.command_digest(),
    151             *bound.plan().digest(),
    152             original.attempt.seal().unwrap().recipient(),
    153         );
    154         self.journal()
    155             .obtained_evidence(request, copied(&self.proof))
    156             .await
    157             .map(|value| value.map(|v| receipt(v.receipt())).unwrap_or_default())
    158             .map_err(|e| JsValue::from_str(e.code()))
    159     }
    160     pub async fn claim(&self, n: u8, index: u8) -> Result<Vec<u8>, JsValue> {
    161         let request = self.claim_request(n, index).await?;
    162         match self
    163             .journal()
    164             .claim_attempt(request, copied(&self.proof))
    165             .await
    166             .map_err(|e| JsValue::from_str(e.code()))?
    167         {
    168             ClaimAttemptOutcome::Claimed(attempt) => {
    169                 let mut raw = vec![1];
    170                 raw.extend(summary(&attempt));
    171                 Ok(raw)
    172             }
    173             ClaimAttemptOutcome::Retained(attempt) => {
    174                 let mut raw = vec![0];
    175                 raw.extend(summary(&attempt));
    176                 Ok(raw)
    177             }
    178             ClaimAttemptOutcome::Unknown(_) => Err(JsValue::from_str("commit_unknown")),
    179         }
    180     }
    181     pub async fn claim_unknown(
    182         &self,
    183         n: u8,
    184         index: u8,
    185         hook: js_sys::Function,
    186     ) -> Result<Vec<u8>, JsValue> {
    187         let request = self.claim_request(n, index).await?;
    188         let operation = request.operation_id();
    189         let digest = request.command_digest();
    190         hook.call0(&JsValue::NULL)?;
    191         match self
    192             .journal()
    193             .claim_attempt(request, copied(&self.proof))
    194             .await
    195             .map_err(|e| JsValue::from_str(e.code()))?
    196         {
    197             ClaimAttemptOutcome::Unknown(anchor) => {
    198                 assert_eq!(anchor.operation_id(), operation);
    199                 assert_eq!(anchor.command_digest(), digest);
    200                 let mut raw = operation.as_bytes().to_vec();
    201                 raw.extend_from_slice(digest.as_bytes());
    202                 raw.extend_from_slice(anchor.transaction_id().unwrap().as_bytes());
    203                 Ok(raw)
    204             }
    205             _ => Err(JsValue::from_str("unexpected_known_claim")),
    206         }
    207     }
    208     pub async fn attempt(&self, n: u8, index: u8) -> Result<Vec<u8>, JsValue> {
    209         let request = self.claim_request(n, index).await?;
    210         self.journal()
    211             .signing_attempt(request, copied(&self.proof))
    212             .await
    213             .map(|value| value.as_ref().map(summary).unwrap_or_default())
    214             .map_err(|e| JsValue::from_str(e.code()))
    215     }
    216     pub async fn obtain(
    217         &self,
    218         n: u8,
    219         index: u8,
    220         known_time: bool,
    221     ) -> Result<ObtainedSeal, JsValue> {
    222         let request = self.claim_request(n, index).await?;
    223         let attempt = match self
    224             .journal()
    225             .claim_attempt(request, copied(&self.proof))
    226             .await
    227             .map_err(|e| JsValue::from_str(e.code()))?
    228         {
    229             ClaimAttemptOutcome::Claimed(attempt) => attempt,
    230             ClaimAttemptOutcome::Retained(_) => {
    231                 return Err(JsValue::from_str("retained_no_dispatch"));
    232             }
    233             ClaimAttemptOutcome::Unknown(_) => return Err(JsValue::from_str("commit_unknown")),
    234         };
    235         let value = signed_output(
    236             &attempt,
    237             if known_time {
    238                 NonZeroU64::new(1_000_000)
    239             } else {
    240                 None
    241             },
    242         )?;
    243         Ok(ObtainedSeal { value, attempt })
    244     }
    245     /// Constructs a second valid synthetic output solely to test the store's
    246     /// refusal to replace an original capture. It grants no claim/dispatch.
    247     pub async fn capture_alternate(&self, original: &ObtainedSeal) -> Result<(), JsValue> {
    248         let alternate = signed_output(&original.attempt, None)?;
    249         assert_ne!(alternate.raw_json(), original.value.raw_json());
    250         self.journal()
    251             .capture_evidence(self.input.clone(), &self.proof, &alternate)
    252             .await
    253             .map(|_| ())
    254             .map_err(|e| JsValue::from_str(e.code()))
    255     }
    256     pub async fn capture_reobserved(&self, original: &ObtainedSeal) -> Result<Vec<u8>, JsValue> {
    257         let evidence = ArtifactEvidence::verify(
    258             &original.attempt,
    259             original.value.raw_json(),
    260             NonZeroU64::new(1_000_100),
    261         )
    262         .unwrap();
    263         match self
    264             .journal()
    265             .capture_evidence(self.input.clone(), &self.proof, &evidence)
    266             .await
    267             .map_err(|e| JsValue::from_str(e.code()))?
    268         {
    269             EvidenceCaptureOutcome::Committed(value) => Ok(receipt(value)),
    270             EvidenceCaptureOutcome::Unknown(_) => Err(JsValue::from_str("commit_unknown")),
    271         }
    272     }
    273     pub async fn capture(&self, original: &ObtainedSeal) -> Result<Vec<u8>, JsValue> {
    274         match self
    275             .journal()
    276             .capture_evidence(self.input.clone(), &self.proof, &original.value)
    277             .await
    278             .map_err(|e| JsValue::from_str(e.code()))?
    279         {
    280             EvidenceCaptureOutcome::Committed(value) => Ok(receipt(value)),
    281             EvidenceCaptureOutcome::Unknown(_) => Err(JsValue::from_str("commit_unknown")),
    282         }
    283     }
    284     pub async fn reconcile(
    285         &self,
    286         original: &ObtainedSeal,
    287         wrong_proof: bool,
    288     ) -> Result<Vec<u8>, JsValue> {
    289         let proof = if wrong_proof {
    290             radroots_storage::workspace::AttachmentProof::from_protected_input(&[0x31; 32]).unwrap()
    291         } else {
    292             copied(&self.proof)
    293         };
    294         match self
    295             .journal()
    296             .reconcile_unknown(self.input.clone(), &proof, &original.value)
    297             .await
    298             .map_err(|e| JsValue::from_str(e.code()))?
    299         {
    300             EvidenceCaptureOutcome::Committed(value) => Ok(receipt(value)),
    301             EvidenceCaptureOutcome::Unknown(_) => Err(JsValue::from_str("commit_unknown")),
    302         }
    303     }
    304     pub fn abandon_reconcile(&self, original: &ObtainedSeal) -> Result<(), JsValue> {
    305         if self
    306             .journal()
    307             .reconcile_unknown(self.input.clone(), &self.proof, &original.value)
    308             .now_or_never()
    309             .is_some()
    310         {
    311             return Err(JsValue::from_str("unexpected_immediate_recovery"));
    312         }
    313         Ok(())
    314     }
    315     pub async fn capture_unknown(&self, original: &ObtainedSeal) -> Result<Vec<u8>, JsValue> {
    316         match self
    317             .journal()
    318             .capture_evidence(self.input.clone(), &self.proof, &original.value)
    319             .await
    320             .map_err(|e| JsValue::from_str(e.code()))?
    321         {
    322             EvidenceCaptureOutcome::Unknown(anchor) => {
    323                 assert_eq!(anchor.operation_id(), original.value.operation_id());
    324                 assert_eq!(anchor.command_digest(), original.value.command_digest());
    325                 let mut raw = anchor.operation_id().as_bytes().to_vec();
    326                 raw.extend_from_slice(anchor.command_digest().as_bytes());
    327                 raw.extend_from_slice(anchor.transaction_id().unwrap().as_bytes());
    328                 Ok(raw)
    329             }
    330             _ => Err(JsValue::from_str("unexpected_known_capture")),
    331         }
    332     }
    333     pub async fn captured(&self, n: u8, index: u8) -> Result<Vec<u8>, JsValue> {
    334         let request = self.claim_request(n, index).await?;
    335         self.journal()
    336             .obtained_evidence(request, copied(&self.proof))
    337             .await
    338             .map(|value| {
    339                 value
    340                     .map(|value| receipt(value.receipt()))
    341                     .unwrap_or_default()
    342             })
    343             .map_err(|e| JsValue::from_str(e.code()))
    344     }
    345     pub fn abandon_capture(&self, original: &ObtainedSeal) -> Result<(), JsValue> {
    346         if self
    347             .journal()
    348             .capture_evidence(self.input.clone(), &self.proof, &original.value)
    349             .now_or_never()
    350             .is_some()
    351         {
    352             return Err(JsValue::from_str("unexpected_immediate_capture"));
    353         }
    354         Ok(())
    355     }
    356 }