codec.rs (8873B)
1 use super::*; 2 use zeroize::Zeroizing; 3 const MAGIC: &[u8] = b"radroots.stock.signing_plan.v1\0"; 4 pub(super) const PREFIX_BYTES: usize = MAGIC.len() + 32 * 5 + 8 * 2; 5 pub(in crate::workspace::stock) struct Retained { 6 pub frame: ledger::Retained, 7 pub bound: StockBoundSigningPlan, 8 } 9 pub(super) fn encode( 10 original: &acceptance::codec::Retained, 11 plan: &CommerceSigningPlan, 12 at: UnixSeconds, 13 ) -> Result<Zeroizing<Vec<u8>>, OperationError> { 14 if at < original.receipt.prepared_at() || at >= original.receipt.first_issue_deadline() { 15 return Err(OperationError::DeadlineExceeded); 16 } 17 let length = PREFIX_BYTES + plan.protected_wire().len(); 18 if length > ledger::BODY_MAX_BYTES { 19 return Err(WorkspaceError::Capacity.into()); 20 } 21 let mut body = Zeroizing::new(Vec::with_capacity(length)); 22 body.extend_from_slice(MAGIC); 23 body.extend_from_slice(original.frame.header.operation.as_bytes()); 24 body.extend_from_slice(original.frame.header.transaction.as_bytes()); 25 body.extend_from_slice(original.frame.header.head.as_bytes()); 26 body.extend_from_slice(&original.receipt.first_issue_deadline().get().to_be_bytes()); 27 body.extend_from_slice(&at.get().to_be_bytes()); 28 for intent in intents(plan, original.receipt.first_issue_deadline())? { 29 body.extend_from_slice(&intent); 30 } 31 body.extend_from_slice(plan.protected_wire()); 32 Ok(body) 33 } 34 pub(super) fn head(header: &ledger::Header, body: &[u8]) -> CheckpointDigest { 35 let mut hash = Sha256::new(); 36 hash.update(b"radroots.seller_stock.signing_plan_chain.v1\0"); 37 hash.update(header.namespace.workspace_id().as_bytes()); 38 hash.update(header.namespace.authority().executor_id().as_bytes()); 39 hash.update( 40 header 41 .namespace 42 .authority() 43 .generation() 44 .get() 45 .to_be_bytes(), 46 ); 47 hash.update(header.namespace.route_digest().as_bytes()); 48 hash.update(header.actor.participant().as_bytes()); 49 hash.update( 50 header 51 .actor 52 .grant_id() 53 .map(|value| *value.as_bytes()) 54 .unwrap_or([0; 32]), 55 ); 56 hash.update(header.operation.as_bytes()); 57 hash.update(header.digest.as_bytes()); 58 hash.update(header.transaction.as_bytes()); 59 hash.update(header.revision.get().to_be_bytes()); 60 hash.update([u8::from(header.previous.is_some())]); 61 hash.update( 62 header 63 .previous 64 .map(|value| *value.as_bytes()) 65 .unwrap_or([0; 32]), 66 ); 67 hash.update(Sha256::digest(body)); 68 CheckpointDigest::from_bytes(hash.finalize().into()) 69 } 70 pub(in crate::workspace::stock) async fn read_entry( 71 connection: &mut SqliteConnection, 72 input: &AttachmentInput, 73 crypto: &WorkspaceCrypto, 74 operation: OperationId, 75 ) -> Result<Option<Retained>, OperationError> { 76 let Some(frame) = ledger::read(connection, input, crypto, operation).await? else { 77 return Ok(None); 78 }; 79 let header = &frame.header; 80 if header.family != ledger::Family::SigningPlan 81 || frame.body.len() <= PREFIX_BYTES 82 || &frame.body[..MAGIC.len()] != MAGIC 83 { 84 return Err(OperationError::RecoveryRequired); 85 } 86 let mut offset = MAGIC.len(); 87 fn take<const N: usize>(bytes: &[u8], offset: &mut usize) -> Result<[u8; N], OperationError> { 88 let value = bytes 89 .get(*offset..*offset + N) 90 .ok_or(OperationError::RecoveryRequired)?; 91 *offset += N; 92 value 93 .try_into() 94 .map_err(|_| OperationError::RecoveryRequired) 95 } 96 let related = OperationId::from_bytes(take(&frame.body, &mut offset)?); 97 let transaction = TransactionId::from_bytes(take(&frame.body, &mut offset)?); 98 let original_head = CheckpointDigest::from_bytes(take(&frame.body, &mut offset)?); 99 let deadline = u64::from_be_bytes(take(&frame.body, &mut offset)?); 100 let at = UnixSeconds::new(u64::from_be_bytes(take(&frame.body, &mut offset)?)) 101 .map_err(|_| OperationError::RecoveryRequired)?; 102 let expected_intents: [[u8; 32]; 2] = [ 103 take(&frame.body, &mut offset)?, 104 take(&frame.body, &mut offset)?, 105 ]; 106 let original = Box::pin(acceptance::codec::read(connection, input, crypto, related)) 107 .await? 108 .ok_or(OperationError::RecoveryRequired)?; 109 if header.related_operation != Some(related) 110 || header.digest != original.frame.header.digest 111 || header.order != original.frame.header.order 112 || header.actor != original.frame.header.actor 113 || header.revision <= original.frame.header.revision 114 || transaction != original.frame.header.transaction 115 || original_head != original.frame.header.head 116 || deadline != original.receipt.first_issue_deadline().get() 117 || at < original.receipt.prepared_at() 118 || at >= original.receipt.first_issue_deadline() 119 || head(header, &frame.body) != header.head 120 { 121 return Err(OperationError::RecoveryRequired); 122 } 123 let plan = CommerceSigningPlan::parse( 124 related, 125 header.digest, 126 original.receipt.rumor(), 127 &frame.body[offset..], 128 ) 129 .map_err(|_| OperationError::RecoveryRequired)?; 130 let intents = intents(&plan, original.receipt.first_issue_deadline())?; 131 if expected_intents != intents { 132 return Err(OperationError::RecoveryRequired); 133 } 134 let checkpoint = InventoryCheckpointRef::from_host_metadata( 135 input.authority(), 136 header.revision, 137 Some(header.head), 138 )? 139 .with_optional_authorization(original.receipt.checkpoint().authorization()); 140 let bound = StockBoundSigningPlan { 141 intents, 142 attempt: CommitAttempt::new( 143 input.workspace_id(), 144 related, 145 header.digest, 146 Some(header.transaction), 147 ), 148 preparation: original.receipt, 149 plan, 150 bound_at: at, 151 checkpoint, 152 }; 153 let retained = Retained { frame, bound }; 154 retained.confirm(connection).await?; 155 Ok(Some(retained)) 156 } 157 impl Retained { 158 pub(in crate::workspace::stock) fn identity(&self) -> EntryIdentity { 159 EntryIdentity { 160 operation: self.frame.header.operation, 161 revision: self.frame.header.revision, 162 head: self.frame.header.head, 163 protected_digest: Sha256::digest(&self.frame.protected).into(), 164 } 165 } 166 pub(in crate::workspace::stock) async fn confirm( 167 &self, 168 connection: &mut SqliteConnection, 169 ) -> Result<(), OperationError> { 170 ledger::confirm_header(connection, &self.frame.header, &self.frame.protected).await?; 171 ledger::confirm_parts( 172 connection, 173 self.frame.header.actor, 174 self.frame.header.operation, 175 self.frame.parts_witness, 176 self.frame.header.parts, 177 ) 178 .await?; 179 let count: i64 = sqlx::query_scalar( 180 "SELECT count(*) FROM stock_movements WHERE actor=? AND operation_id=?", 181 ) 182 .bind(self.frame.header.actor.participant().as_bytes().as_slice()) 183 .bind(self.frame.header.operation.as_bytes().as_slice()) 184 .fetch_one(connection) 185 .await 186 .map_err(|_| OperationError::RecoveryRequired)?; 187 if count != 0 { 188 return Err(OperationError::RecoveryRequired); 189 } 190 Ok(()) 191 } 192 pub(in crate::workspace::stock) fn into_history(self) -> ledger::HistoryEntry { 193 ledger::HistoryEntry { 194 deficit: None, 195 delivery: None, 196 envelope: None, 197 aborted: None, 198 preparation: None, 199 local_record: None, 200 installation: None, 201 signing: None, 202 header: self.frame.header, 203 protected: self.frame.protected, 204 parts_witness: self.frame.parts_witness, 205 pools: vec![], 206 mapping: None, 207 movements: vec![], 208 } 209 } 210 } 211 212 pub(super) fn intents( 213 plan: &CommerceSigningPlan, 214 deadline: UnixSeconds, 215 ) -> Result<[[u8; 32]; 2], OperationError> { 216 let deadline = std::num::NonZeroU64::new( 217 deadline 218 .get() 219 .checked_mul(1000) 220 .ok_or(OperationError::RecoveryRequired)?, 221 ) 222 .ok_or(OperationError::RecoveryRequired)?; 223 let mut result = [[0; 32]; 2]; 224 for (index, seal) in plan.seals().iter().enumerate() { 225 let call = radroots_signing::provider::ProviderCall::new( 226 seal.fields().author, 227 deadline, 228 radroots_signing::request::CancellationSignal::new(), 229 ); 230 result[index] = *radroots_signing::issuance::SigningIntent::from_commerce_seal(seal, call) 231 .map_err(|_| OperationError::InvalidEvidence)? 232 .binding() 233 .digest(); 234 } 235 Ok(result) 236 }