Skip to main content

qualia_core_db/net/peer/replication/
commit_adapter.rs

1//! Recipe D commit adapter: verify payload bytes, then pair+commit.
2//!
3//! Payload SHA-384 must equal `expected_digest` before any durable staging.
4//! Mismatch is [`QdnfError::Conflict`]: nothing committed, receipt not
5//! durable. Transport ACK is never a durable receipt.
6//!
7//! Recovery [`resume_from_log`] streams CORE-03 markers and deduplicates by
8//! the 16-byte transaction key derived from operation identity. Markers do
9//! not carry the 48-byte operation id; receipt replay keys by the marker
10//! object digest (the effect digest pairing wrote). [`super::pair::recover_pair`]
11//! rebinds the real operation id when the descriptor is available.
12
13use crate::crypto::network::digest::sha384;
14use crate::net::peer::replication::operation::{OpTable, OperationDesc};
15use crate::net::peer::replication::pair::{commit_pair, stage_paired, DurablePairing};
16use crate::net::peer::replication::receipts::{self, ReceiptTable};
17use crate::net::qdnf::errors::QdnfError;
18use crate::net::qdnf::session::datagrams::DeliveryStage;
19use crate::net::qdnf::types::{Generation, StrongDigest};
20use crate::wal_intent::{ArtifactKind, IntentRecord, IntentTable, MarkerKind, MAX_INTENTS};
21
22fn verify_payload(payload: &[u8], expected: StrongDigest) -> Result<(), QdnfError> {
23    if payload.is_empty() {
24        return Err(QdnfError::Malformed);
25    }
26    if sha384(payload) != expected {
27        Err(QdnfError::Conflict)
28    } else {
29        Ok(())
30    }
31}
32
33/// Verify payload, stage the pairing, commit the intent, ACK durable applied.
34pub fn commit_verified_block(
35    intents: &mut IntentTable,
36    receipts: &mut ReceiptTable,
37    ops: &mut OpTable,
38    desc: &OperationDesc,
39    payload: &[u8],
40    expected_digest: StrongDigest,
41    writer_id: u64,
42    generation: Generation,
43) -> Result<DurablePairing, QdnfError> {
44    verify_payload(payload, expected_digest)?;
45    let pairing = stage_paired(intents, receipts, ops, desc, payload, writer_id, generation)?;
46    commit_pair(intents, receipts, pairing, generation)
47}
48
49/// Stream markers, dedupe by operation identity (`TxId`), replay receipts.
50///
51/// Duplicate markers for the same tx keep the last kind (WAL order). Torn
52/// trailing bytes are ignored by [`IntentTable::recover_into`].
53pub fn resume_from_log(
54    log_bytes: &[u8],
55    intents: &mut IntentTable,
56    receipts: &mut ReceiptTable,
57    ops: &mut OpTable,
58) -> Result<usize, QdnfError> {
59    let mut recovered = [IntentRecord::EMPTY; MAX_INTENTS];
60    let n = IntentTable::recover_into(log_bytes, &mut recovered)?;
61
62    let mut unique = [IntentRecord::EMPTY; MAX_INTENTS];
63    let mut unique_n = 0usize;
64    let mut i = 0usize;
65    while i < n {
66        let rec = recovered[i];
67        let mut found = None;
68        let mut u = 0usize;
69        while u < unique_n {
70            if unique[u].tx.bytes == rec.tx.bytes {
71                found = Some(u);
72                break;
73            }
74            u += 1;
75        }
76        match found {
77            Some(idx) => unique[idx] = rec,
78            None => {
79                if unique_n >= MAX_INTENTS {
80                    return Err(QdnfError::Capacity);
81                }
82                unique[unique_n] = rec;
83                unique_n += 1;
84            }
85        }
86        i += 1;
87    }
88
89    let mut applied = 0usize;
90    let mut u = 0usize;
91    while u < unique_n {
92        replay_unique(intents, receipts, ops, unique[u])?;
93        applied += 1;
94        u += 1;
95    }
96    Ok(applied)
97}
98
99fn replay_unique(
100    intents: &mut IntentTable,
101    receipts: &mut ReceiptTable,
102    ops: &mut OpTable,
103    rec: IntentRecord,
104) -> Result<(), QdnfError> {
105    let id = rec.object.digest;
106    if id == StrongDigest::ZERO {
107        return Err(QdnfError::Malformed);
108    }
109    let _ = ops.get_committed(&id);
110
111    let object = crate::wal_intent::ExactObjectRef {
112        kind: ArtifactKind::Evidence,
113        digest: id,
114        byte_len: rec.object.byte_len,
115    };
116    match intents.stage_intent(rec.tx, object, 0, Generation::ZERO) {
117        Ok(_) => {}
118        Err(QdnfError::Conflict) => {}
119        Err(e) => return Err(e),
120    }
121    match rec.kind {
122        MarkerKind::Commit => match intents.commit(rec.tx, Generation::ZERO) {
123            Ok(()) => {}
124            Err(QdnfError::Conflict) => {}
125            Err(e) => return Err(e),
126        },
127        MarkerKind::Abort => match intents.abort(rec.tx, Generation::ZERO) {
128            Ok(()) => {}
129            Err(QdnfError::Conflict) => {}
130            Err(e) => return Err(e),
131        },
132        MarkerKind::Intent => {}
133    }
134
135    receipts::bind_identity(receipts, id)?;
136    if rec.kind == MarkerKind::Commit {
137        receipts::bind_effect_digest(receipts, id, id)?;
138        let class = receipts::acknowledge(receipts, id, DeliveryStage::DurableApplied)?;
139        if class != receipts::ReceiptClass::DurableReceipt {
140            return Err(QdnfError::Incomplete);
141        }
142    }
143    Ok(())
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149    use crate::net::peer::replication::operation::{operation_id, MAX_PARENTS};
150    use crate::net::peer::replication::receipts::ReceiptClass;
151    use crate::wal_intent::{TxId, MARKER_LEN};
152
153    fn sample(seq: u32) -> OperationDesc {
154        OperationDesc {
155            author: StrongDigest([0x21; 48]),
156            epoch: 1,
157            sequence: seq,
158            scope: 9,
159            contract: StrongDigest([0x32; 48]),
160            purpose: StrongDigest([0x43; 48]),
161            payload_digest: StrongDigest([0x54; 48]),
162            parents: [StrongDigest::ZERO; MAX_PARENTS],
163            parent_count: 0,
164        }
165    }
166
167    #[test]
168    fn matching_bytes_and_commit_are_durable_receipt() {
169        let mut intents = IntentTable::new();
170        let mut receipts = ReceiptTable::new();
171        let mut ops = OpTable::new();
172        let desc = sample(1);
173        let payload = b"verified-block-bytes";
174        let expected = sha384(payload);
175        let gen = Generation(1);
176        let pairing = commit_verified_block(
177            &mut intents,
178            &mut receipts,
179            &mut ops,
180            &desc,
181            payload,
182            expected,
183            11,
184            gen,
185        )
186        .unwrap();
187        assert_eq!(pairing.receipt_class, ReceiptClass::DurableReceipt);
188        assert_eq!(pairing.effect_digest, expected);
189        assert_eq!(intents.commit(pairing.tx, gen), Err(QdnfError::Conflict));
190        assert_eq!(
191            receipts::class_of(&receipts, pairing.op_id).unwrap(),
192            ReceiptClass::DurableReceipt
193        );
194    }
195
196    #[test]
197    fn tampered_payload_is_conflict_and_not_committed() {
198        let mut intents = IntentTable::new();
199        let mut receipts = ReceiptTable::new();
200        let mut ops = OpTable::new();
201        let desc = sample(2);
202        let good = b"canonical-bytes";
203        let expected = sha384(good);
204        let mut bad = *good;
205        bad[0] ^= 0xFF;
206        let gen = Generation(1);
207        assert_eq!(
208            commit_verified_block(
209                &mut intents,
210                &mut receipts,
211                &mut ops,
212                &desc,
213                &bad,
214                expected,
215                12,
216                gen,
217            ),
218            Err(QdnfError::Conflict)
219        );
220        let op_id = operation_id(&desc);
221        assert_eq!(
222            receipts::class_of(&receipts, op_id),
223            Err(QdnfError::Unauthorized)
224        );
225        let tx = crate::net::peer::replication::operation::tx_from_operation_id(&op_id);
226        assert_eq!(intents.commit(tx, gen), Err(QdnfError::Incomplete));
227    }
228
229    #[test]
230    fn resume_from_log_dedupes_by_operation_identity() {
231        let payload = b"log-effect";
232        let digest = sha384(payload);
233        let tx = TxId { bytes: [0x77; 16] };
234        let mut stream = [0u8; MARKER_LEN * 3];
235        IntentTable::encode_marker(MarkerKind::Intent, tx, &digest, &mut stream[..MARKER_LEN])
236            .unwrap();
237        IntentTable::encode_marker(
238            MarkerKind::Commit,
239            tx,
240            &digest,
241            &mut stream[MARKER_LEN..MARKER_LEN * 2],
242        )
243        .unwrap();
244        IntentTable::encode_marker(
245            MarkerKind::Commit,
246            tx,
247            &digest,
248            &mut stream[MARKER_LEN * 2..MARKER_LEN * 3],
249        )
250        .unwrap();
251
252        let mut intents = IntentTable::new();
253        let mut receipts = ReceiptTable::new();
254        let mut ops = OpTable::new();
255        let n = resume_from_log(&stream, &mut intents, &mut receipts, &mut ops).unwrap();
256        assert_eq!(n, 1);
257        assert_eq!(
258            receipts::class_of(&receipts, digest).unwrap(),
259            ReceiptClass::DurableReceipt
260        );
261        assert_eq!(
262            intents.commit(tx, Generation::ZERO),
263            Err(QdnfError::Conflict)
264        );
265    }
266}