lib

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

checkpoint.rs (33982B)


      1 use super::*;
      2 
      3 /// Constant-memory witness of the exact protected ancestry checked before IO
      4 /// enters the write transaction. The transaction rereads every bound SQL row;
      5 /// no key-provider callback or decryption runs while it owns the SQL lock.
      6 pub(in crate::workspace::stock) struct MinimumProof {
      7     lower: u64,
      8     upper: u64,
      9     digest: [u8; 32],
     10     multipart: bool,
     11 }
     12 impl MinimumProof {
     13     pub(in crate::workspace::stock) async fn confirm(
     14         &self,
     15         connection: &mut SqliteConnection,
     16     ) -> Result<(), OperationError> {
     17         let catalog: i64 = sqlx::query_scalar("PRAGMA user_version")
     18             .fetch_one(&mut *connection)
     19             .await
     20             .map_err(|_| OperationError::RecoveryRequired)?;
     21         let mut hash = history_hash(self.multipart);
     22         for revision in (self.lower..=self.upper).rev() {
     23             let row=sqlx::query("SELECT actor,grant_id,operation_id,command_digest,transaction_id,pool_id,chain_head,CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END FROM stock_operations WHERE revision=?")
     24                 .bind(revision as i64).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?;
     25             hash.update(revision.to_be_bytes());
     26             let mut actor = [0_u8; 32];
     27             let mut operation = [0_u8; 32];
     28             for column in 0..7 {
     29                 if column == 5 {
     30                     let pool: Option<Vec<u8>> = row
     31                         .try_get(column)
     32                         .map_err(|_| OperationError::RecoveryRequired)?;
     33                     if !self.multipart && pool.is_none() {
     34                         return Err(OperationError::RecoveryRequired);
     35                     }
     36                     hash_optional(&mut hash, pool.as_deref())?;
     37                     continue;
     38                 }
     39                 let bytes: Vec<u8> = row
     40                     .try_get(column)
     41                     .map_err(|_| OperationError::RecoveryRequired)?;
     42                 if bytes.len() != 32 {
     43                     return Err(OperationError::RecoveryRequired);
     44                 }
     45                 if column == 0 {
     46                     actor.copy_from_slice(&bytes);
     47                 }
     48                 if column == 2 {
     49                     operation.copy_from_slice(&bytes);
     50                 }
     51                 hash.update(bytes);
     52             }
     53             let protected: Vec<u8> = row
     54                 .try_get::<Option<Vec<u8>>, _>(7)
     55                 .map_err(|_| OperationError::RecoveryRequired)?
     56                 .ok_or(OperationError::RecoveryRequired)?;
     57             hash.update((protected.len() as u64).to_be_bytes());
     58             hash.update(protected);
     59             if self.multipart {
     60                 let row=sqlx::query("SELECT family,order_id,related_operation,subject_grant FROM stock_operations WHERE actor=? AND operation_id=?")
     61                     .bind(actor.as_slice()).bind(operation.as_slice()).fetch_one(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?;
     62                 let family: i64 = row
     63                     .try_get(0)
     64                     .map_err(|_| OperationError::RecoveryRequired)?;
     65                 let order: Option<Vec<u8>> = row
     66                     .try_get(1)
     67                     .map_err(|_| OperationError::RecoveryRequired)?;
     68                 let related: Option<Vec<u8>> = row
     69                     .try_get(2)
     70                     .map_err(|_| OperationError::RecoveryRequired)?;
     71                 if !(0..=if catalog >= 18 {
     72                     14
     73                 } else if catalog >= 17 {
     74                     12
     75                 } else if catalog >= 16 {
     76                     10
     77                 } else if catalog >= 15 {
     78                     9
     79                 } else if catalog >= 14 {
     80                     8
     81                 } else {
     82                     7
     83                 })
     84                     .contains(&family)
     85                 {
     86                     return Err(OperationError::RecoveryRequired);
     87                 }
     88                 let subject: Option<Vec<u8>> = row
     89                     .try_get(3)
     90                     .map_err(|_| OperationError::RecoveryRequired)?;
     91                 hash.update(family.to_be_bytes());
     92                 hash_optional(&mut hash, order.as_deref())?;
     93                 hash_optional(&mut hash, related.as_deref())?;
     94                 hash_optional(&mut hash, subject.as_deref())?;
     95                 let (parts, witness) =
     96                     super::super::ledger::raw_parts_witness(connection, &actor, &operation).await?;
     97                 hash.update([parts]);
     98                 hash.update(witness);
     99                 if catalog >= 19 && family == 0 {
    100                     hash.update(b"D19");
    101                     hash.update(
    102                         super::deficit::raw_projection(connection, &actor, &operation).await?,
    103                     );
    104                 }
    105                 if matches!(family, 11 | 12) {
    106                     hash.update(
    107                         super::super::delivery::raw_projection(
    108                             connection, &actor, &operation, family,
    109                         )
    110                         .await?,
    111                     );
    112                 }
    113                 if family == 10 {
    114                     hash.update(
    115                         super::super::envelope::raw_projection(connection, &actor, &operation)
    116                             .await?,
    117                     );
    118                 }
    119                 if family == 13 {
    120                     hash.update(
    121                         super::super::envelope::raw_admission_projection(
    122                             connection, &actor, &operation,
    123                         )
    124                         .await?,
    125                     );
    126                 }
    127                 if family == 14 {
    128                     hash.update(
    129                         super::super::envelope::raw_rewrap_projection(
    130                             connection, &actor, &operation,
    131                         )
    132                         .await?,
    133                     );
    134                 }
    135                 if family == 7 {
    136                     hash.update(
    137                         super::abort::raw_projection(connection, &actor, &operation).await?,
    138                     );
    139                 }
    140                 if catalog >= 13 && family == 2 {
    141                     hash.update(b"P13");
    142                     hash.update(
    143                         super::acceptance::codec::raw_preparation(connection, &actor, &operation)
    144                             .await?,
    145                     );
    146                 }
    147                 if matches!(family, 4 | 5 | 8 | 9) {
    148                     hash.update(
    149                         super::super::issuance::raw_projection(
    150                             connection, &actor, &operation, family,
    151                         )
    152                         .await?,
    153                     );
    154                 }
    155             }
    156             if self.multipart {
    157                 let family: i64 = sqlx::query_scalar(
    158                     "SELECT family FROM stock_operations WHERE actor=? AND operation_id=?",
    159                 )
    160                 .bind(actor.as_slice())
    161                 .bind(operation.as_slice())
    162                 .fetch_one(&mut *connection)
    163                 .await
    164                 .map_err(|_| OperationError::RecoveryRequired)?;
    165                 if family == 6 {
    166                     hash.update(
    167                         super::installation::raw_projection(connection, &actor, &operation).await?,
    168                     );
    169                 }
    170             }
    171             hash_current_movements(&mut hash, connection, &actor, &operation).await?;
    172         }
    173         let actual: [u8; 32] = hash.finalize().into();
    174         if actual != self.digest {
    175             return Err(OperationError::RecoveryRequired);
    176         }
    177         Ok(())
    178     }
    179 }
    180 fn history_hash(multipart: bool) -> Sha256 {
    181     let mut hash = Sha256::new();
    182     hash.update(b"radroots.seller_stock.ancestry_snapshot.v2\0");
    183     hash.update([u8::from(multipart)]);
    184     hash
    185 }
    186 /// Authenticate current order cache data from the complete protected chain.
    187 /// The caller must retain this proof through the final SQL transaction.
    188 pub(in crate::workspace::stock) async fn authenticate_order_state(
    189     connection: &mut SqliteConnection,
    190     input: &AttachmentInput,
    191     crypto: &WorkspaceCrypto,
    192     binding: &WorkspaceBinding,
    193     authority: &Authority,
    194     order: radroots_domain::OrderId,
    195 ) -> Result<super::super::order_state::Checked, OperationError> {
    196     if !matches!(authority.catalog, 13..=20) {
    197         return Err(OperationError::UnsupportedOperation);
    198     }
    199     let current = authority
    200         .inventory
    201         .ok_or(OperationError::RecoveryRequired)?;
    202     let mut previous = current.head;
    203     let mut hash = history_hash(true);
    204     let mut chain = super::super::order_state::Chain::new(authority.catalog);
    205     for revision in (1..=current.revision.get()).rev() {
    206         let id: Vec<u8> = sqlx::query_scalar("SELECT operation_id FROM stock_operations WHERE revision=? AND length(operation_id)=32")
    207             .bind(revision as i64).fetch_optional(&mut *connection).await
    208             .map_err(|_| OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?;
    209         let entry = Box::pin(super::super::ledger::history(
    210             connection,
    211             input,
    212             crypto,
    213             binding,
    214             authority,
    215             OperationId::from_bytes(
    216                 id.try_into()
    217                     .map_err(|_| OperationError::RecoveryRequired)?,
    218             ),
    219         ))
    220         .await?
    221         .ok_or(OperationError::RecoveryRequired)?;
    222         if entry.header.revision.get() != revision || Some(entry.header.head) != previous {
    223             return Err(OperationError::RecoveryRequired);
    224         }
    225         if entry.header.order == Some(order)
    226             && let Some(marker) = super::super::order_state::Marker::from_history(&entry)?
    227         {
    228             chain.observe(marker)?;
    229         }
    230         entry.hash(&mut hash)?;
    231         previous = entry.header.previous;
    232     }
    233     if previous.is_some() {
    234         return Err(OperationError::RecoveryRequired);
    235     }
    236     chain.complete()?;
    237     let witness = super::super::order_state::Witness {
    238         order,
    239         expected: chain.latest,
    240     };
    241     witness.confirm(connection).await?;
    242     Ok(super::super::order_state::Checked {
    243         witness,
    244         ancestry: MinimumProof {
    245             lower: 1,
    246             upper: current.revision.get(),
    247             digest: hash.finalize().into(),
    248             multipart: true,
    249         },
    250     })
    251 }
    252 /// Initial decisions must prove absence through authenticated effects, rather
    253 /// than trusting the mutable order index or its current row count alone.
    254 pub(super) async fn authenticate_order_absence(
    255     connection: &mut SqliteConnection,
    256     input: &AttachmentInput,
    257     crypto: &WorkspaceCrypto,
    258     binding: &WorkspaceBinding,
    259     authority: &Authority,
    260     order: radroots_domain::OrderId,
    261 ) -> Result<MinimumProof, OperationError> {
    262     let current = authority
    263         .inventory
    264         .ok_or(OperationError::UnsupportedOperation)?;
    265     if !matches!(authority.catalog, 9..=20) {
    266         return Err(OperationError::UnsupportedOperation);
    267     }
    268     let upper = current.revision.get();
    269     let mut previous = current.head;
    270     let mut hash = history_hash(true);
    271     for revision in (1..=upper).rev() {
    272         let id: Vec<u8> = sqlx::query_scalar("SELECT operation_id FROM stock_operations WHERE revision=? AND length(operation_id)=32")
    273             .bind(revision as i64).fetch_optional(&mut *connection).await.map_err(|_| OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?;
    274         let operation = OperationId::from_bytes(
    275             id.try_into()
    276                 .map_err(|_| OperationError::RecoveryRequired)?,
    277         );
    278         let entry = Box::pin(super::super::ledger::history(
    279             connection, input, crypto, binding, authority, operation,
    280         ))
    281         .await?
    282         .ok_or(OperationError::RecoveryRequired)?;
    283         if entry.header.revision.get() != revision || Some(entry.header.head) != previous {
    284             return Err(OperationError::RecoveryRequired);
    285         }
    286         if entry.header.family == super::super::ledger::Family::Acceptance
    287             && entry.header.order == Some(order)
    288         {
    289             return Err(OperationError::StaleState);
    290         }
    291         entry.hash(&mut hash)?;
    292         previous = entry.header.previous;
    293     }
    294     if previous.is_some() {
    295         return Err(OperationError::RecoveryRequired);
    296     }
    297     Ok(MinimumProof {
    298         lower: 1,
    299         upper,
    300         digest: hash.finalize().into(),
    301         multipart: true,
    302     })
    303 }
    304 #[derive(Clone, Copy, Eq, PartialEq)]
    305 pub(in crate::workspace::stock) struct EntryIdentity {
    306     pub operation: OperationId,
    307     pub revision: Sequence,
    308     pub head: CheckpointDigest,
    309     pub protected_digest: [u8; 32],
    310 }
    311 pub(in crate::workspace::stock) enum IdentityTarget {
    312     Abort {
    313         operation: OperationId,
    314         expected: Option<EntryIdentity>,
    315     },
    316     Operation(OperationId, Option<EntryIdentity>),
    317     Consent {
    318         operation: OperationId,
    319         subject: GrantId,
    320         expected: Option<EntryIdentity>,
    321     },
    322     SigningPlan {
    323         operation: OperationId,
    324         expected: Option<EntryIdentity>,
    325     },
    326     Installation {
    327         operation: OperationId,
    328         expected: Option<EntryIdentity>,
    329     },
    330     SigningClaim {
    331         operation: OperationId,
    332         recipient: radroots_domain::PublicKey,
    333         expected: Option<EntryIdentity>,
    334     },
    335 }
    336 pub(in crate::workspace::stock) async fn authenticate_identity(
    337     connection: &mut SqliteConnection,
    338     input: &AttachmentInput,
    339     crypto: &WorkspaceCrypto,
    340     binding: &WorkspaceBinding,
    341     authority: &Authority,
    342     target: IdentityTarget,
    343 ) -> Result<MinimumProof, OperationError> {
    344     let current = authority
    345         .inventory
    346         .ok_or(OperationError::UnsupportedOperation)?;
    347     let multipart = matches!(authority.catalog, 7..=20);
    348     let upper = current.revision.get();
    349     let mut previous = current.head;
    350     let mut hash = history_hash(multipart);
    351     for revision in (1..=upper).rev() {
    352         let id:Vec<u8>=sqlx::query_scalar("SELECT operation_id FROM stock_operations WHERE revision=? AND length(operation_id)=32")
    353             .bind(revision as i64).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?;
    354         let operation = OperationId::from_bytes(
    355             id.try_into()
    356                 .map_err(|_| OperationError::RecoveryRequired)?,
    357         );
    358         let (identity, predecessor, natural, signing_plan, signing_claim, installation, aborted) =
    359             if multipart {
    360                 let entry = Box::pin(super::super::ledger::history(
    361                     connection, input, crypto, binding, authority, operation,
    362                 ))
    363                 .await?
    364                 .ok_or(OperationError::RecoveryRequired)?;
    365                 if entry.header.revision.get() != revision || Some(entry.header.head) != previous {
    366                     return Err(OperationError::RecoveryRequired);
    367                 }
    368                 entry.hash(&mut hash)?;
    369                 (
    370                     EntryIdentity {
    371                         operation,
    372                         revision: entry.header.revision,
    373                         head: entry.header.head,
    374                         protected_digest: Sha256::digest(&entry.protected).into(),
    375                     },
    376                     entry.header.previous,
    377                     if entry.header.family == super::super::ledger::Family::Consent {
    378                         entry
    379                             .header
    380                             .related_operation
    381                             .zip(entry.header.subject_grant)
    382                     } else {
    383                         None
    384                     },
    385                     if entry.header.family == super::super::ledger::Family::SigningPlan {
    386                         entry.header.related_operation
    387                     } else {
    388                         None
    389                     },
    390                     if entry.header.family == super::super::ledger::Family::SigningClaim {
    391                         entry
    392                             .signing
    393                             .map(|value| (value.operation, value.recipient))
    394                     } else {
    395                         None
    396                     },
    397                     entry.installation.map(|value| value.operation),
    398                     entry.aborted.map(|value| value.operation),
    399                 )
    400             } else {
    401                 let entry = read_operation(connection, input, crypto, binding, operation)
    402                     .await?
    403                     .ok_or(OperationError::RecoveryRequired)?;
    404                 let checkpoint = entry.receipt.checkpoint();
    405                 if checkpoint.revision().get() != revision || checkpoint.head() != previous {
    406                     return Err(OperationError::RecoveryRequired);
    407                 }
    408                 hash_retained(&mut hash, revision, binding, operation, &entry)?;
    409                 (
    410                     EntryIdentity {
    411                         operation,
    412                         revision: checkpoint.revision(),
    413                         head: checkpoint.head().ok_or(OperationError::RecoveryRequired)?,
    414                         protected_digest: Sha256::digest(&entry.protected).into(),
    415                     },
    416                     entry.previous_head,
    417                     None,
    418                     None,
    419                     None,
    420                     None,
    421                     None,
    422                 )
    423             };
    424         let (matched, expected) = match &target {
    425             IdentityTarget::Abort {
    426                 operation: wanted,
    427                 expected,
    428             } => (aborted == Some(*wanted), *expected),
    429             IdentityTarget::Operation(wanted, expected) => (*wanted == operation, *expected),
    430             IdentityTarget::Consent {
    431                 operation: wanted,
    432                 subject,
    433                 expected,
    434             } => (natural == Some((*wanted, *subject)), *expected),
    435             IdentityTarget::SigningPlan {
    436                 operation: wanted,
    437                 expected,
    438             } => (signing_plan == Some(*wanted), *expected),
    439             IdentityTarget::Installation {
    440                 operation: wanted,
    441                 expected,
    442             } => (installation == Some(*wanted), *expected),
    443             IdentityTarget::SigningClaim {
    444                 operation: wanted,
    445                 recipient,
    446                 expected,
    447             } => (signing_claim == Some((*wanted, *recipient)), *expected),
    448         };
    449         if matched {
    450             if expected != Some(identity) {
    451                 return Err(OperationError::RecoveryRequired);
    452             }
    453             return Ok(MinimumProof {
    454                 lower: revision,
    455                 upper,
    456                 digest: hash.finalize().into(),
    457                 multipart,
    458             });
    459         }
    460         previous = predecessor;
    461     }
    462     let expected = match target {
    463         IdentityTarget::Operation(_, expected)
    464         | IdentityTarget::Consent { expected, .. }
    465         | IdentityTarget::SigningPlan { expected, .. }
    466         | IdentityTarget::SigningClaim { expected, .. }
    467         | IdentityTarget::Abort { expected, .. }
    468         | IdentityTarget::Installation { expected, .. } => expected,
    469     };
    470     if previous.is_some() || expected.is_some() {
    471         return Err(OperationError::RecoveryRequired);
    472     }
    473     Ok(MinimumProof {
    474         lower: 1,
    475         upper,
    476         digest: hash.finalize().into(),
    477         multipart,
    478     })
    479 }
    480 pub(in crate::workspace::stock) async fn authenticate_minimum(
    481     connection: &mut SqliteConnection,
    482     input: &AttachmentInput,
    483     crypto: &WorkspaceCrypto,
    484     binding: &WorkspaceBinding,
    485     authority: &Authority,
    486     minimum: radroots_storage::inventory::InventoryCheckpointRef,
    487 ) -> Result<MinimumProof, OperationError> {
    488     Box::pin(authenticate_minimum_with_local(
    489         connection, input, crypto, binding, authority, minimum, None,
    490     ))
    491     .await
    492 }
    493 pub(in crate::workspace::stock) struct LocalSources<'a> {
    494     pub scope: radroots_domain::causal::CausalScope,
    495     pub records: &'a mut std::collections::BTreeMap<
    496         radroots_domain::RecordId,
    497         radroots_protocol::commerce::DecodedRecord,
    498     >,
    499 }
    500 pub(in crate::workspace::stock) async fn authenticate_minimum_with_local(
    501     connection: &mut SqliteConnection,
    502     input: &AttachmentInput,
    503     crypto: &WorkspaceCrypto,
    504     binding: &WorkspaceBinding,
    505     authority: &Authority,
    506     minimum: radroots_storage::inventory::InventoryCheckpointRef,
    507     mut local: Option<LocalSources<'_>>,
    508 ) -> Result<MinimumProof, OperationError> {
    509     let current = authority
    510         .inventory
    511         .ok_or(OperationError::UnsupportedOperation)?;
    512     if minimum.authority() != input.authority() {
    513         return Err(WorkspaceError::StaleAuthority.into());
    514     }
    515     if minimum.revision().get() > current.revision.get() {
    516         return Err(WorkspaceError::StaleCheckpoint.into());
    517     }
    518     let lower = if local.is_some() {
    519         1
    520     } else {
    521         minimum.revision().get().max(1)
    522     };
    523     let upper = current.revision.get();
    524     let multipart = matches!(authority.catalog, 7..=20);
    525     let mut hash = history_hash(multipart);
    526     let mut expected = current.head;
    527     for revision in (lower..=upper).rev() {
    528         let id:Vec<u8>=sqlx::query_scalar("SELECT operation_id FROM stock_operations WHERE revision=? AND length(operation_id)=32")
    529             .bind(revision as i64).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?;
    530         let operation = OperationId::from_bytes(
    531             id.try_into()
    532                 .map_err(|_| OperationError::RecoveryRequired)?,
    533         );
    534         if multipart {
    535             let mut retained = Box::pin(super::super::ledger::history(
    536                 connection, input, crypto, binding, authority, operation,
    537             ))
    538             .await?
    539             .ok_or(OperationError::RecoveryRequired)?;
    540             if retained.header.revision.get() != revision || Some(retained.header.head) != expected
    541             {
    542                 return Err(WorkspaceError::StaleCheckpoint.into());
    543             }
    544             if revision == minimum.revision().get() && expected != minimum.head() {
    545                 return Err(WorkspaceError::StaleCheckpoint.into());
    546             }
    547             retained.hash(&mut hash)?;
    548             if let Some(local) = &mut local
    549                 && let Some(record) = retained.local_record.take()
    550                 && local.scope.contains(record.content())
    551             {
    552                 let id = record.record_id();
    553                 if let Some(known) = local.records.get(&id) {
    554                     if known.content() != record.content() {
    555                         return Err(OperationError::RecoveryRequired);
    556                     }
    557                 } else {
    558                     local.records.insert(id, *record);
    559                     if local.records.len() > radroots_domain::causal::MAX_CAUSAL_RECORDS {
    560                         return Err(WorkspaceError::Capacity.into());
    561                     }
    562                 }
    563             }
    564             expected = retained.header.previous;
    565             continue;
    566         }
    567         let retained = read_operation(connection, input, crypto, binding, operation)
    568             .await?
    569             .ok_or(OperationError::RecoveryRequired)?;
    570         let receipt = &retained.receipt;
    571         if receipt.checkpoint().revision().get() != revision
    572             || receipt.checkpoint().head() != expected
    573         {
    574             return Err(WorkspaceError::StaleCheckpoint.into());
    575         }
    576         if revision == minimum.revision().get() && expected != minimum.head() {
    577             return Err(WorkspaceError::StaleCheckpoint.into());
    578         }
    579         hash_retained(&mut hash, revision, binding, operation, &retained)?;
    580         expected = retained.previous_head;
    581     }
    582     if (minimum.revision().get() == 0 || local.is_some()) && expected.is_some() {
    583         return Err(WorkspaceError::StaleCheckpoint.into());
    584     }
    585     Ok(MinimumProof {
    586         lower,
    587         upper,
    588         digest: hash.finalize().into(),
    589         multipart,
    590     })
    591 }
    592 
    593 fn hash_retained(
    594     hash: &mut Sha256,
    595     revision: u64,
    596     binding: &WorkspaceBinding,
    597     operation: OperationId,
    598     retained: &Retained,
    599 ) -> Result<(), OperationError> {
    600     let receipt = &retained.receipt;
    601     hash.update(revision.to_be_bytes());
    602     hash.update(binding.actor().participant().as_bytes());
    603     hash.update(retained.original_grant.as_bytes());
    604     hash.update(operation.as_bytes());
    605     hash.update(retained.digest.as_bytes());
    606     hash.update(
    607         receipt
    608             .transaction_id()
    609             .ok_or(OperationError::RecoveryRequired)?
    610             .as_bytes(),
    611     );
    612     hash_optional(hash, Some(receipt.pool().id().as_bytes()))?;
    613     hash.update(
    614         receipt
    615             .checkpoint()
    616             .head()
    617             .ok_or(OperationError::RecoveryRequired)?
    618             .as_bytes(),
    619     );
    620     hash.update((retained.protected.len() as u64).to_be_bytes());
    621     hash.update(&retained.protected);
    622     if let Some((header, parts)) = &retained.frame {
    623         hash.update(header.family.code().to_be_bytes());
    624         hash_optional(hash, header.order.as_ref().map(|v| v.as_bytes().as_slice()))?;
    625         hash_optional(
    626             hash,
    627             header
    628                 .related_operation
    629                 .as_ref()
    630                 .map(|v| v.as_bytes().as_slice()),
    631         )?;
    632         hash_optional(
    633             hash,
    634             header
    635                 .subject_grant
    636                 .as_ref()
    637                 .map(|v| v.as_bytes().as_slice()),
    638         )?;
    639         hash.update([header.parts]);
    640         hash.update(parts);
    641     }
    642     hash.update([u8::from(retained.movement.is_some())]);
    643     if let (Some(id), Some(protected)) = (retained.movement, &retained.movement_protected) {
    644         hash.update(id);
    645         hash.update(receipt.pool().id().as_bytes());
    646         hash.update(retained.original_grant.as_bytes());
    647         hash.update((protected.len() as u64).to_be_bytes());
    648         hash.update(protected);
    649     }
    650     Ok(())
    651 }
    652 fn hash_optional(hash: &mut Sha256, value: Option<&[u8]>) -> Result<(), OperationError> {
    653     hash.update([u8::from(value.is_some())]);
    654     if let Some(bytes) = value {
    655         if bytes.len() != 32 {
    656             return Err(OperationError::RecoveryRequired);
    657         }
    658         hash.update(bytes);
    659     }
    660     Ok(())
    661 }
    662 async fn hash_current_movements(
    663     hash: &mut Sha256,
    664     connection: &mut SqliteConnection,
    665     actor: &[u8; 32],
    666     operation: &[u8; 32],
    667 ) -> Result<(), OperationError> {
    668     let count: i64 =
    669         sqlx::query_scalar("SELECT count(*) FROM stock_movements WHERE actor=? AND operation_id=?")
    670             .bind(actor.as_slice())
    671             .bind(operation.as_slice())
    672             .fetch_one(&mut *connection)
    673             .await
    674             .map_err(|_| OperationError::RecoveryRequired)?;
    675     if !(0..=64).contains(&count) {
    676         return Err(OperationError::RecoveryRequired);
    677     }
    678     hash.update([count as u8]);
    679     for offset in 0..count {
    680         let row=sqlx::query("SELECT movement_id,pool_id,grant_id,CASE WHEN length(protected) BETWEEN 1 AND 262144 THEN protected END FROM stock_movements WHERE actor=? AND operation_id=? ORDER BY movement_id LIMIT 1 OFFSET ?")
    681             .bind(actor.as_slice()).bind(operation.as_slice()).bind(offset).fetch_one(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?;
    682         for column in 0..3 {
    683             let bytes: Vec<u8> = row
    684                 .try_get(column)
    685                 .map_err(|_| OperationError::RecoveryRequired)?;
    686             if bytes.len() != 32 {
    687                 return Err(OperationError::RecoveryRequired);
    688             }
    689             hash.update(bytes);
    690         }
    691         let protected: Vec<u8> = row
    692             .try_get::<Option<Vec<u8>>, _>(3)
    693             .map_err(|_| OperationError::RecoveryRequired)?
    694             .ok_or(OperationError::RecoveryRequired)?;
    695         hash.update((protected.len() as u64).to_be_bytes());
    696         hash.update(protected);
    697     }
    698     Ok(())
    699 }
    700 
    701 /// Proves the current pool projection against the latest actual protected
    702 /// effect, including every intervening link from the current root. A mutable
    703 /// SQL pool index alone cannot prove the absence of a more recent effect.
    704 pub(super) async fn authenticate_projection(
    705     connection: &mut SqliteConnection,
    706     input: &AttachmentInput,
    707     crypto: &WorkspaceCrypto,
    708     binding: &WorkspaceBinding,
    709     authority: &Authority,
    710     pool: PoolId,
    711     projected: Option<PoolSnapshot>,
    712 ) -> Result<MinimumProof, OperationError> {
    713     authenticate_projected(
    714         connection,
    715         input,
    716         crypto,
    717         binding,
    718         authority,
    719         Projection::Pool(pool, projected),
    720     )
    721     .await
    722 }
    723 pub(super) async fn authenticate_mapping_projection(
    724     connection: &mut SqliteConnection,
    725     input: &AttachmentInput,
    726     crypto: &WorkspaceCrypto,
    727     binding: &WorkspaceBinding,
    728     authority: &Authority,
    729     key: radroots_domain::stock::OptionMappingKey,
    730     projected: Option<radroots_domain::stock::OptionPoolMapping>,
    731 ) -> Result<MinimumProof, OperationError> {
    732     authenticate_projected(
    733         connection,
    734         input,
    735         crypto,
    736         binding,
    737         authority,
    738         Projection::Mapping(key, projected),
    739     )
    740     .await
    741 }
    742 enum Projection {
    743     Pool(PoolId, Option<PoolSnapshot>),
    744     Mapping(
    745         radroots_domain::stock::OptionMappingKey,
    746         Option<radroots_domain::stock::OptionPoolMapping>,
    747     ),
    748 }
    749 impl Projection {
    750     fn matches(&self, receipt: &InventoryReceipt) -> Result<bool, OperationError> {
    751         let matched = match self {
    752             Self::Pool(id, projected) if *id == receipt.pool().id() => {
    753                 Some(*projected == Some(receipt.pool()))
    754             }
    755             Self::Mapping(key, projected)
    756                 if receipt.mapping().is_some_and(|value| value.key() == *key) =>
    757             {
    758                 Some(*projected == receipt.mapping())
    759             }
    760             _ => None,
    761         };
    762         match matched {
    763             Some(true) => Ok(true),
    764             Some(false) => Err(OperationError::RecoveryRequired),
    765             None => Ok(false),
    766         }
    767     }
    768     fn present(&self) -> bool {
    769         match self {
    770             Self::Pool(_, value) => value.is_some(),
    771             Self::Mapping(_, value) => value.is_some(),
    772         }
    773     }
    774 }
    775 async fn authenticate_projected(
    776     connection: &mut SqliteConnection,
    777     input: &AttachmentInput,
    778     crypto: &WorkspaceCrypto,
    779     binding: &WorkspaceBinding,
    780     authority: &Authority,
    781     projected: Projection,
    782 ) -> Result<MinimumProof, OperationError> {
    783     let current = authority
    784         .inventory
    785         .ok_or(OperationError::UnsupportedOperation)?;
    786     let upper = current.revision.get();
    787     let mut expected = current.head;
    788     let multipart = matches!(authority.catalog, 7..=20);
    789     let mut hash = history_hash(multipart);
    790     for revision in (1..=upper).rev() {
    791         let id:Vec<u8>=sqlx::query_scalar("SELECT operation_id FROM stock_operations WHERE revision=? AND length(operation_id)=32").bind(revision as i64).fetch_optional(&mut *connection).await.map_err(|_|OperationError::RecoveryRequired)?.ok_or(OperationError::RecoveryRequired)?;
    792         let operation = OperationId::from_bytes(
    793             id.try_into()
    794                 .map_err(|_| OperationError::RecoveryRequired)?,
    795         );
    796         if multipart {
    797             let retained = Box::pin(super::super::ledger::history(
    798                 connection, input, crypto, binding, authority, operation,
    799             ))
    800             .await?
    801             .ok_or(OperationError::RecoveryRequired)?;
    802             if retained.header.revision.get() != revision || Some(retained.header.head) != expected
    803             {
    804                 return Err(OperationError::RecoveryRequired);
    805             }
    806             retained.hash(&mut hash)?;
    807             let matched = match &projected {
    808                 Projection::Pool(id, observed) => retained
    809                     .pools
    810                     .iter()
    811                     .find(|pool| pool.id() == *id)
    812                     .map(|actual| *observed == Some(*actual)),
    813                 Projection::Mapping(key, observed) => retained
    814                     .mapping
    815                     .filter(|actual| actual.key() == *key)
    816                     .map(|actual| *observed == Some(actual)),
    817             };
    818             if let Some(matched) = matched {
    819                 if !matched {
    820                     return Err(OperationError::RecoveryRequired);
    821                 }
    822                 return Ok(MinimumProof {
    823                     lower: revision,
    824                     upper,
    825                     digest: hash.finalize().into(),
    826                     multipart,
    827                 });
    828             }
    829             expected = retained.header.previous;
    830             continue;
    831         }
    832         let retained = read_operation(connection, input, crypto, binding, operation)
    833             .await?
    834             .ok_or(OperationError::RecoveryRequired)?;
    835         if retained.receipt.checkpoint().revision().get() != revision
    836             || retained.receipt.checkpoint().head() != expected
    837         {
    838             return Err(OperationError::RecoveryRequired);
    839         }
    840         hash_retained(&mut hash, revision, binding, operation, &retained)?;
    841         if projected.matches(&retained.receipt)? {
    842             return Ok(MinimumProof {
    843                 lower: revision,
    844                 upper,
    845                 digest: hash.finalize().into(),
    846                 multipart,
    847             });
    848         }
    849         expected = retained.previous_head;
    850     }
    851     if expected.is_some() || projected.present() {
    852         return Err(OperationError::RecoveryRequired);
    853     }
    854     Ok(MinimumProof {
    855         lower: 1,
    856         upper,
    857         digest: hash.finalize().into(),
    858         multipart,
    859     })
    860 }