lib

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

rewrap.rs (14580B)


      1 //! Additional obtained outers reference immutable original F10/S/T2.
      2 use super::*;
      3 use nostr::JsonUtil;
      4 use radroots_storage::inventory::{StockRewrapPage, StockRewrapRequest, StockRewrapState};
      5 use std::num::NonZeroU64;
      6 #[path = "rewrap_capture.rs"]
      7 mod capture;
      8 #[path = "rewrap_selection.rs"]
      9 pub(super) mod selection;
     10 pub(super) use capture::capture;
     11 use selection::SelectionWitness;
     12 const MAGIC: &[u8; 8] = b"RDSTRW1\0";
     13 const PREFIX: usize = 117;
     14 const COUNT_MAX: i64 = 192;
     15 
     16 fn head(header: &ledger::Header, body: &[u8]) -> CheckpointDigest {
     17     let mut hash = Sha256::new();
     18     hash.update(b"radroots.seller_stock.rewrap_chain.v1\0");
     19     hash.update([14]);
     20     hash.update(codec::head(header, body).as_bytes());
     21     CheckpointDigest::from_bytes(hash.finalize().into())
     22 }
     23 fn encode(
     24     original: &rewrap_admission::Admitted,
     25     request: &StockEnvelopeRequest,
     26     raw: &str,
     27 ) -> Zeroizing<Vec<u8>> {
     28     let mut body = Zeroizing::new(Vec::with_capacity(PREFIX + raw.len()));
     29     body.extend_from_slice(MAGIC);
     30     body.extend_from_slice(original.frame.header.operation.as_bytes());
     31     body.extend_from_slice(original.frame.header.transaction.as_bytes());
     32     body.extend_from_slice(original.frame.header.head.as_bytes());
     33     body.push(u8::from(request.observed_at_unix_ms().is_some()));
     34     body.extend_from_slice(
     35         &request
     36             .observed_at_unix_ms()
     37             .map(NonZeroU64::get)
     38             .unwrap_or(0)
     39             .to_be_bytes(),
     40     );
     41     body.extend_from_slice(&(raw.len() as u32).to_be_bytes());
     42     body.extend_from_slice(raw.as_bytes());
     43     body
     44 }
     45 pub(super) async fn lookup(
     46     turn: &mut Turn<'_>,
     47     request: &StockEnvelopeRequest,
     48     event: EnvelopeEventId,
     49 ) -> Result<Option<Retained>, OperationError> {
     50     let catalog: i64 = sqlx::query_scalar("PRAGMA user_version")
     51         .fetch_one(&mut *turn.connection)
     52         .await
     53         .map_err(|_| OperationError::RecoveryRequired)?;
     54     if !matches!(catalog, 18 | 19) {
     55         return Err(OperationError::UnsupportedOperation);
     56     }
     57     let entry: Option<Vec<u8>> = sqlx::query_scalar("SELECT CASE WHEN length(entry_id)=32 THEN entry_id END FROM stock_rewraps WHERE actor=? AND operation_id=? AND recipient=? AND event_id=?")
     58         .bind(turn.selected.participant().as_bytes().as_slice())
     59         .bind(request.operation_id().as_bytes().as_slice()).bind(request.recipient().as_bytes().as_slice())
     60         .bind(event.as_bytes().as_slice()).fetch_optional(&mut *turn.connection).await.map_err(|_| OperationError::RecoveryRequired)?;
     61     let Some(entry) = entry else { return Ok(None) };
     62     let entry = OperationId::from_bytes(
     63         entry
     64             .try_into()
     65             .map_err(|_| OperationError::RecoveryRequired)?,
     66     );
     67     let retained = Box::pin(read_entry(
     68         turn.connection,
     69         turn.selected,
     70         turn.crypto,
     71         request.binding(),
     72         entry,
     73     ))
     74     .await?
     75     .ok_or(OperationError::RecoveryRequired)?;
     76     let receipt = retained.source.receipt();
     77     if retained.frame.header.family != ledger::Family::RewrappedEnvelope
     78         || receipt.attempt().operation_id() != request.operation_id()
     79         || receipt.attempt().command_digest() != request.command_digest()
     80         || receipt.recipient() != request.recipient()
     81         || receipt.event_id() != event
     82     {
     83         return Err(OperationError::RecoveryRequired);
     84     }
     85     Ok(Some(retained))
     86 }
     87 pub(super) async fn decode_entry(
     88     connection: &mut SqliteConnection,
     89     input: &AttachmentInput,
     90     crypto: &WorkspaceCrypto,
     91     binding: &WorkspaceBinding,
     92     frame: ledger::Retained,
     93 ) -> Result<Retained, OperationError> {
     94     let catalog: i64 = sqlx::query_scalar("PRAGMA user_version")
     95         .fetch_one(&mut *connection)
     96         .await
     97         .map_err(|_| OperationError::RecoveryRequired)?;
     98     let body = frame.body.as_slice();
     99     if !matches!(catalog, 18 | 19)
    100         || frame.header.family != ledger::Family::RewrappedEnvelope
    101         || !(PREFIX..=PREFIX + 65536).contains(&body.len())
    102         || &body[..8] != MAGIC
    103     {
    104         return Err(OperationError::RecoveryRequired);
    105     }
    106     let array = |start, end| -> Result<[u8; 32], OperationError> {
    107         body[start..end]
    108             .try_into()
    109             .map_err(|_| OperationError::RecoveryRequired)
    110     };
    111     // F14 references a strict F13, whose strict F10 link cannot recurse.
    112     let admission = Box::pin(rewrap_admission::read_entry(
    113         connection,
    114         input,
    115         crypto,
    116         binding,
    117         OperationId::from_bytes(array(8, 40)?),
    118     ))
    119     .await?;
    120     let h = &frame.header;
    121     let original_header = &admission.frame.header;
    122     if original_header.transaction != TransactionId::from_bytes(array(40, 72)?)
    123         || original_header.head != CheckpointDigest::from_bytes(array(72, 104)?)
    124         || h.actor != original_header.actor
    125         || h.digest != original_header.digest
    126         || h.related_operation != original_header.related_operation
    127         || h.order != original_header.order
    128         || h.revision <= original_header.revision
    129         || head(h, body) != h.head
    130     {
    131         return Err(OperationError::RecoveryRequired);
    132     }
    133     let at = u64::from_be_bytes(
    134         body[105..113]
    135             .try_into()
    136             .map_err(|_| OperationError::RecoveryRequired)?,
    137     );
    138     let observed = match (body[104], at) {
    139         (0, 0) => None,
    140         (1, value) if value > 0 => NonZeroU64::new(value),
    141         _ => return Err(OperationError::RecoveryRequired),
    142     };
    143     let length = u32::from_be_bytes(
    144         body[113..117]
    145             .try_into()
    146             .map_err(|_| OperationError::RecoveryRequired)?,
    147     ) as usize;
    148     if length != body.len() - PREFIX {
    149         return Err(OperationError::RecoveryRequired);
    150     }
    151     let raw = std::str::from_utf8(&body[PREFIX..]).map_err(|_| OperationError::RecoveryRequired)?;
    152     let event = nostr::Event::from_json(raw).map_err(|_| OperationError::RecoveryRequired)?;
    153     let event = EnvelopeEventId::from_bytes(event.id.to_bytes());
    154     let first = admission.report.original();
    155     if first.event_id() == event {
    156         return Err(OperationError::RecoveryRequired);
    157     }
    158     let operation = h
    159         .related_operation
    160         .ok_or(OperationError::RecoveryRequired)?;
    161     let request = StockEnvelopeRequest::new(
    162         binding.clone(),
    163         first.checkpoint(),
    164         operation,
    165         h.digest,
    166         first.recipient(),
    167         observed,
    168     )?
    169     .with_envelope(event);
    170     let receipt = StockEnvelopeReceipt::from_committed_store(
    171         &request,
    172         CommitAttempt::new(
    173             input.workspace_id(),
    174             operation,
    175             h.digest,
    176             Some(h.transaction),
    177         ),
    178         first.evidence(),
    179         first.installation_transaction_id(),
    180         event,
    181         Sha256::digest(raw.as_bytes()).into(),
    182         InventoryCheckpointRef::from_host_metadata(input.authority(), h.revision, Some(h.head))?,
    183     )?
    184     .with_rewrap_admission(&admission.report)?;
    185     let source = StockEnvelopeSource::from_retained_wire(receipt, raw)
    186         .map_err(|_| OperationError::RecoveryRequired)?;
    187     let retained = Retained {
    188         installation: codec::read_original_entry(
    189             connection,
    190             input,
    191             crypto,
    192             binding,
    193             admission.original_entry,
    194         )
    195         .await?
    196         .installation_entry(),
    197         projection: Projection::Rewrap {
    198             operation,
    199             recipient: receipt.recipient(),
    200             admission: admission.frame.header.operation,
    201             event,
    202         },
    203         frame,
    204         source,
    205     };
    206     retained.confirm(connection).await?;
    207     Ok(retained)
    208 }
    209 pub(in crate::workspace) async fn page(
    210     turn: &mut Turn<'_>,
    211     request: StockEnvelopeRequest,
    212     after: Option<Sequence>,
    213     proof: AttachmentProof,
    214 ) -> Result<StockRewrapPage, OperationError> {
    215     let (entries, more, checkpoint) = query(turn, &request, after, None, &proof).await?;
    216     StockRewrapPage::from_store_report(&request, entries, more, checkpoint)
    217 }
    218 pub(in crate::workspace) async fn attempt(
    219     turn: &mut Turn<'_>,
    220     request: StockRewrapRequest,
    221     proof: AttachmentProof,
    222 ) -> Result<Option<StockRewrapState>, OperationError> {
    223     let (mut entries, _, _) = query(
    224         turn,
    225         request.source(),
    226         None,
    227         Some(request.rewrap_id()),
    228         &proof,
    229     )
    230     .await?;
    231     Ok(entries.pop())
    232 }
    233 async fn state(
    234     turn: &mut Turn<'_>,
    235     binding: &WorkspaceBinding,
    236     admission: rewrap_admission::Admitted,
    237 ) -> Result<StockRewrapState, OperationError> {
    238     let entry: Option<Vec<u8>> = sqlx::query_scalar(
    239         "SELECT CASE WHEN length(entry_id)=32 THEN entry_id END FROM stock_rewraps WHERE actor=? AND admission_entry=?",
    240     )
    241     .bind(turn.selected.participant().as_bytes().as_slice())
    242     .bind(admission.frame.header.operation.as_bytes().as_slice())
    243     .fetch_optional(&mut *turn.connection)
    244     .await
    245     .map_err(|_| OperationError::RecoveryRequired)?;
    246     let captured = if let Some(entry) = entry {
    247         let retained = Box::pin(read_entry(
    248             turn.connection,
    249             turn.selected,
    250             turn.crypto,
    251             binding,
    252             OperationId::from_bytes(
    253                 entry
    254                     .try_into()
    255                     .map_err(|_| OperationError::RecoveryRequired)?,
    256             ),
    257         ))
    258         .await?
    259         .ok_or(OperationError::RecoveryRequired)?;
    260         if retained.frame.header.family != ledger::Family::RewrappedEnvelope {
    261             return Err(OperationError::RecoveryRequired);
    262         }
    263         Some(retained.source.receipt())
    264     } else {
    265         None
    266     };
    267     StockRewrapState::from_store_report(admission.report, captured)
    268 }
    269 async fn query(
    270     turn: &mut Turn<'_>,
    271     request: &StockEnvelopeRequest,
    272     after: Option<Sequence>,
    273     id: Option<OperationId>,
    274     proof: &AttachmentProof,
    275 ) -> Result<(Vec<StockRewrapState>, bool, InventoryCheckpointRef), OperationError> {
    276     if *turn.uncertain {
    277         return Err(OperationError::RecoveryRequired);
    278     }
    279     if request.envelope_event_id().is_some() {
    280         return Err(OperationError::InvalidCommand);
    281     }
    282     let catalog: i64 = sqlx::query_scalar("PRAGMA user_version")
    283         .fetch_one(&mut *turn.connection)
    284         .await
    285         .map_err(|_| OperationError::RecoveryRequired)?;
    286     if !matches!(catalog, 18 | 19) {
    287         return Err(OperationError::UnsupportedOperation);
    288     }
    289     let auth = Box::pin(super::super::signing_plan::load(
    290         turn,
    291         request.binding(),
    292         request.minimum_checkpoint(),
    293         request.operation_id(),
    294         request.command_digest(),
    295         proof,
    296     ))
    297     .await?;
    298     if !matches!(auth.access.authority.catalog, 18 | 19)
    299         || !auth
    300             .original
    301             .receipt
    302             .rumor()
    303             .recipients()
    304             .contains(&request.recipient())
    305     {
    306         return Err(OperationError::InvalidEvidence);
    307     }
    308     let current = auth
    309         .access
    310         .authority
    311         .inventory
    312         .ok_or(OperationError::RecoveryRequired)?;
    313     if after.is_some_and(|cursor| cursor > current.revision) {
    314         return Err(OperationError::StaleState);
    315     }
    316     let witness = Box::pin(full_proof(turn, request, &auth.access.authority)).await?;
    317     let selection = SelectionWitness::read(turn.connection, request).await?;
    318     let rows = if let Some(id) = id {
    319         sqlx::query("SELECT CASE WHEN length(entry_id)=32 THEN entry_id END FROM stock_rewrap_admissions WHERE actor=? AND operation_id=? AND recipient=? AND request_id=?")
    320             .bind(turn.selected.participant().as_bytes().as_slice()).bind(request.operation_id().as_bytes().as_slice()).bind(request.recipient().as_bytes().as_slice())
    321             .bind(id.as_bytes().as_slice()).fetch_all(&mut *turn.connection).await
    322     } else {
    323         sqlx::query("SELECT CASE WHEN length(r.entry_id)=32 THEN r.entry_id END FROM stock_rewrap_admissions r JOIN stock_operations o ON o.actor=r.actor AND o.operation_id=r.entry_id WHERE r.actor=? AND r.operation_id=? AND r.recipient=? AND o.revision>? ORDER BY o.revision LIMIT 17")
    324             .bind(turn.selected.participant().as_bytes().as_slice()).bind(request.operation_id().as_bytes().as_slice()).bind(request.recipient().as_bytes().as_slice())
    325             .bind(after.map(|value| value.get() as i64).unwrap_or(0)).fetch_all(&mut *turn.connection).await
    326     }.map_err(|_| OperationError::RecoveryRequired)?;
    327     let more = rows.len() > 16;
    328     let mut entries = Vec::with_capacity(rows.len().min(16));
    329     for row in rows.into_iter().take(16) {
    330         let entry: Vec<u8> = row
    331             .try_get(0)
    332             .map_err(|_| OperationError::RecoveryRequired)?;
    333         let admission = Box::pin(rewrap_admission::read_entry(
    334             turn.connection,
    335             turn.selected,
    336             turn.crypto,
    337             request.binding(),
    338             OperationId::from_bytes(
    339                 entry
    340                     .try_into()
    341                     .map_err(|_| OperationError::RecoveryRequired)?,
    342             ),
    343         ))
    344         .await?;
    345         let first = admission.report.original();
    346         if first.recipient() != request.recipient()
    347             || first.attempt().operation_id() != request.operation_id()
    348             || first.attempt().command_digest() != request.command_digest()
    349         {
    350             return Err(OperationError::RecoveryRequired);
    351         }
    352         entries.push(Box::pin(state(turn, request.binding(), admission)).await?);
    353     }
    354     let mut tx = turn
    355         .connection
    356         .begin_with("BEGIN IMMEDIATE")
    357         .await
    358         .map_err(|_| OperationError::StorageFailure)?;
    359     let checked: Result<(), OperationError> = async {
    360         auth.confirm(&mut tx, turn.namespace, turn.clock, proof, false)
    361             .await?;
    362         inventory::check_head(&mut tx, current).await?;
    363         witness.confirm(&mut tx).await?;
    364         selection.confirm(&mut tx, request).await?;
    365         turn.namespace.validate()?;
    366         Ok(())
    367     }
    368     .await;
    369     if let Err(error) = checked {
    370         if tx.rollback().await.is_err() {
    371             *turn.uncertain = true;
    372         }
    373         return Err(error);
    374     }
    375     if tx.rollback().await.is_err() {
    376         *turn.uncertain = true;
    377         return Err(OperationError::RecoveryRequired);
    378     }
    379     Ok((
    380         entries,
    381         more,
    382         InventoryCheckpointRef::from_host_metadata(
    383             turn.selected.authority(),
    384             current.revision,
    385             current.head,
    386         )?
    387         .with_optional_authorization(auth.access.authority.authorization),
    388     ))
    389 }