canic-core 0.69.4

Canic — a canister orchestration and management toolkit for the Internet Computer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//! Module: model::replay
//!
//! Responsibility: define pure shared replay receipt identifiers and state.
//! Does not own: storage mutation, replay reservation, or command execution.
//! Boundary: consumed by replay ops and stable replay storage records.
#![expect(dead_code)]

use crate::{cdk::types::Principal, ids::CanisterRole};
use std::{fmt, str::FromStr};

use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

pub const REPLAY_RECEIPT_SCHEMA_VERSION: u32 = 1;
pub const REPLAY_PAYLOAD_HASH_SCHEMA_VERSION: u32 = 1;
pub const MAX_REPLAY_TERMINAL_ERROR_BYTES: usize = 4096;

const REPLAY_PAYLOAD_HASH_DOMAIN: &[u8] = b"canic-replay-payload-hash:v1";

///
/// OperationId
///
/// Stable operation identifier shared by replay-protected commands.
/// Owned by the replay model and serialized into stable replay receipts.
///

#[derive(Clone, Copy, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct OperationId([u8; 32]);

impl OperationId {
    /// Build an operation id from its canonical 32-byte representation.
    #[must_use]
    pub const fn from_bytes(bytes: [u8; 32]) -> Self {
        Self(bytes)
    }

    /// Return the canonical 32-byte operation id representation.
    #[must_use]
    pub const fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }

    /// Consume the operation id and return its canonical bytes.
    #[must_use]
    pub const fn into_bytes(self) -> [u8; 32] {
        self.0
    }
}

impl fmt::Debug for OperationId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "OperationId({self})")
    }
}

impl fmt::Display for OperationId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for byte in self.0 {
            write!(f, "{byte:02x}")?;
        }
        Ok(())
    }
}

impl From<[u8; 32]> for OperationId {
    fn from(value: [u8; 32]) -> Self {
        Self::from_bytes(value)
    }
}

impl From<OperationId> for [u8; 32] {
    fn from(value: OperationId) -> Self {
        value.into_bytes()
    }
}

impl TryFrom<&[u8]> for OperationId {
    type Error = OperationIdParseError;

    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        let bytes: [u8; 32] =
            value
                .try_into()
                .map_err(|_| OperationIdParseError::InvalidByteLength {
                    actual: value.len(),
                })?;
        Ok(Self(bytes))
    }
}

impl FromStr for OperationId {
    type Err = OperationIdParseError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        if value.len() != 64 {
            return Err(OperationIdParseError::InvalidHexLength {
                actual: value.len(),
            });
        }

        let mut bytes = [0u8; 32];
        for (index, chunk) in value.as_bytes().chunks_exact(2).enumerate() {
            let high = decode_hex_nibble(chunk[0])?;
            let low = decode_hex_nibble(chunk[1])?;
            bytes[index] = (high << 4) | low;
        }
        Ok(Self(bytes))
    }
}

///
/// OperationIdParseError
///
/// Typed parse failure for operation id byte and hex conversions.
/// Owned by the replay model and returned by `OperationId` constructors.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum OperationIdParseError {
    InvalidByteLength { actual: usize },
    InvalidHexLength { actual: usize },
    InvalidHexCharacter { byte: u8 },
}

///
/// CommandKind
///
/// Validated replay command namespace.
/// Owned by the replay model and used to partition replay receipts.
///

#[derive(Clone, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct CommandKind(String);

impl CommandKind {
    /// Validate and create a replay command namespace.
    pub fn new(value: impl Into<String>) -> Result<Self, CommandKindError> {
        let value = value.into();
        if value.is_empty() {
            return Err(CommandKindError::Empty);
        }
        if !value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'))
        {
            return Err(CommandKindError::InvalidCharacter);
        }
        Ok(Self(value))
    }

    /// Return the validated command namespace as text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

///
/// CommandKindError
///
/// Typed validation failure for replay command namespaces.
/// Owned by the replay model and returned by `CommandKind::new`.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CommandKindError {
    Empty,
    InvalidCharacter,
}

///
/// AuthKind
///
/// Authentication class bound into replay actor identity.
/// Owned by the replay model and included in payload hashes.
///

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum AuthKind {
    DirectCaller,
    DelegatedToken,
    RoleAttestation,
}

///
/// ReplayActor
///
/// Effective actor identity bound to replay receipts and payload hashes.
/// Owned by the replay model and consumed by replay guards.
///

#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ReplayActor {
    pub effective_principal: Principal,
    pub auth_kind: AuthKind,
}

impl ReplayActor {
    /// Build a replay actor for direct caller authentication.
    #[must_use]
    pub const fn direct_caller(caller: Principal) -> Self {
        Self {
            effective_principal: caller,
            auth_kind: AuthKind::DirectCaller,
        }
    }
}

///
/// ReplayReceiptKey
///
/// Logical replay receipt key before storage-specific hashing.
/// Owned by the replay model and used by replay storage adapters.
///

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ReplayReceiptKey {
    pub command_kind: CommandKind,
    pub operation_id: OperationId,
}

///
/// ReplayReceipt
///
/// Canonical replay receipt state independent of stable-memory encoding.
/// Owned by the replay model and persisted through storage record adapters.
///

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ReplayReceipt {
    pub schema_version: u32,
    pub command_kind: CommandKind,
    pub operation_id: OperationId,
    pub actor: ReplayActor,
    pub payload_hash_schema_version: u32,
    pub payload_hash: [u8; 32],
    pub status: ReplayReceiptStatus,
    pub created_at_ns: u64,
    pub updated_at_ns: u64,
    pub expires_at_ns: Option<u64>,
    pub response_schema_version: Option<u32>,
    pub response_bytes: Option<Vec<u8>>,
    pub effect: Option<ExternalEffectDescriptor>,
}

///
/// ReplayReceiptStatus
///
/// Lifecycle state for a replay receipt.
/// Owned by the replay model and interpreted by replay guards.
///

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum ReplayReceiptStatus {
    Reserved,
    ExternalEffectInFlight,
    Committed,
    TerminalFailed {
        error_code: ReplayTerminalErrorCode,
        error_bytes: Vec<u8>,
        error_bytes_truncated: bool,
    },
    RecoveryRequired {
        reason: RecoveryReason,
    },
}

///
/// ReplayTerminalErrorCode
///
/// Stable terminal replay failure classification.
/// Owned by the replay model and stored with bounded error bytes.
///

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum ReplayTerminalErrorCode {
    ValidationRejected,
    ExecutionFailed,
    ResponseEncodeFailed,
    Other(String),
}

///
/// RecoveryReason
///
/// Stable replay recovery reason after uncertain external effects.
/// Owned by the replay model and exposed through replay decisions.
///

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum RecoveryReason {
    ExternalEffectStatusUnknown,
    ResponseCommitFailed,
    Other(String),
}

///
/// ExternalEffectDescriptor
///
/// Replay-visible description of an external side effect boundary.
/// Owned by the replay model and persisted while effects are in flight.
///

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub enum ExternalEffectDescriptor {
    ManagementCreateCanister { command_kind: CommandKind },
    ManagementCall { canister: Principal, method: String },
    IcpTransfer { operation_id: OperationId },
}

///
/// ReplayError
///
/// Shared replay-domain error classification.
/// Owned by the replay model and used by higher-level replay workflows.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ReplayError {
    OperationIdRequired,
    OperationAlreadyCommittedPayloadMismatch,
    OperationAlreadyCommittedActorMismatch,
    OperationInProgress,
    OperationRecoveryRequired,
    OperationIdInvalid,
    ReceiptDecodeFailed,
    ReceiptSchemaUnsupported,
}

///
/// ReplayPayloadHasher
///
/// Deterministic hasher for replay command payloads.
/// Owned by the replay model and used by workflow replay adapters.
///

pub struct ReplayPayloadHasher {
    inner: Sha256,
}

impl ReplayPayloadHasher {
    /// Start a deterministic replay payload hash for a command and actor.
    #[must_use]
    pub fn new(command_kind: &CommandKind, actor: &ReplayActor) -> Self {
        let mut inner = Sha256::new();
        hash_bytes(&mut inner, REPLAY_PAYLOAD_HASH_DOMAIN);
        hash_u32(&mut inner, REPLAY_PAYLOAD_HASH_SCHEMA_VERSION);
        hash_str(&mut inner, command_kind.as_str());
        hash_replay_actor(&mut inner, actor);
        Self { inner }
    }

    /// Add a boolean field to the replay payload hash.
    pub fn hash_bool(&mut self, value: bool) {
        hash_bool(&mut self.inner, value);
    }

    /// Add a `u64` field to the replay payload hash.
    pub fn hash_u64(&mut self, value: u64) {
        hash_u64(&mut self.inner, value);
    }

    /// Add a `u128` field to the replay payload hash.
    pub fn hash_u128(&mut self, value: u128) {
        hash_u128(&mut self.inner, value);
    }

    /// Add byte string data to the replay payload hash.
    pub fn hash_bytes(&mut self, value: &[u8]) {
        hash_bytes(&mut self.inner, value);
    }

    /// Add UTF-8 string data to the replay payload hash.
    pub fn hash_str(&mut self, value: &str) {
        hash_str(&mut self.inner, value);
    }

    /// Add a principal to the replay payload hash.
    pub fn hash_principal(&mut self, value: &Principal) {
        hash_principal(&mut self.inner, value);
    }

    /// Add an optional principal to the replay payload hash.
    pub fn hash_optional_principal(&mut self, value: Option<Principal>) {
        hash_bool(&mut self.inner, value.is_some());
        if let Some(value) = value {
            hash_principal(&mut self.inner, &value);
        }
    }

    /// Add a canister role to the replay payload hash.
    pub fn hash_role(&mut self, value: &CanisterRole) {
        hash_str(&mut self.inner, value.as_str());
    }

    /// Finish and return the canonical replay payload hash.
    #[must_use]
    pub fn finish(self) -> [u8; 32] {
        self.inner.finalize().into()
    }
}

///
/// BoundedTerminalError
///
/// Bounded terminal replay error bytes plus truncation metadata.
/// Owned by the replay model and produced before receipt persistence.
///

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BoundedTerminalError {
    pub bytes: Vec<u8>,
    pub truncated: bool,
}

/// Bound terminal replay error bytes to the stable receipt limit.
#[must_use]
pub fn bounded_terminal_error_bytes(bytes: &[u8]) -> BoundedTerminalError {
    if bytes.len() <= MAX_REPLAY_TERMINAL_ERROR_BYTES {
        return BoundedTerminalError {
            bytes: bytes.to_vec(),
            truncated: false,
        };
    }

    BoundedTerminalError {
        bytes: bytes[..MAX_REPLAY_TERMINAL_ERROR_BYTES].to_vec(),
        truncated: true,
    }
}

const fn decode_hex_nibble(byte: u8) -> Result<u8, OperationIdParseError> {
    match byte {
        b'0'..=b'9' => Ok(byte - b'0'),
        b'a'..=b'f' => Ok(byte - b'a' + 10),
        b'A'..=b'F' => Ok(byte - b'A' + 10),
        _ => Err(OperationIdParseError::InvalidHexCharacter { byte }),
    }
}

fn hash_replay_actor(hasher: &mut Sha256, actor: &ReplayActor) {
    hash_principal(hasher, &actor.effective_principal);
    hash_str(
        hasher,
        match actor.auth_kind {
            AuthKind::DirectCaller => "DirectCaller",
            AuthKind::DelegatedToken => "DelegatedToken",
            AuthKind::RoleAttestation => "RoleAttestation",
        },
    );
    // Preserve the retired actor-extension marker in the payload-hash layout.
    hash_bool(hasher, false);
}

fn hash_bool(hasher: &mut Sha256, value: bool) {
    hasher.update([u8::from(value)]);
}

fn hash_u32(hasher: &mut Sha256, value: u32) {
    hasher.update(value.to_be_bytes());
}

fn hash_u64(hasher: &mut Sha256, value: u64) {
    hasher.update(value.to_be_bytes());
}

fn hash_u128(hasher: &mut Sha256, value: u128) {
    hasher.update(value.to_be_bytes());
}

fn hash_bytes(hasher: &mut Sha256, bytes: &[u8]) {
    hasher.update((bytes.len() as u64).to_be_bytes());
    hasher.update(bytes);
}

fn hash_str(hasher: &mut Sha256, value: &str) {
    hash_bytes(hasher, value.as_bytes());
}

fn hash_principal(hasher: &mut Sha256, principal: &Principal) {
    hash_bytes(hasher, principal.as_slice());
}

// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    fn p(id: u8) -> Principal {
        Principal::from_slice(&[id; 29])
    }

    #[test]
    fn operation_id_is_exactly_32_bytes_and_hex_round_trips() {
        let raw = [0xabu8; 32];
        let id = OperationId::from_bytes(raw);
        let text = id.to_string();

        assert_eq!(text.len(), 64);
        assert_eq!(text.parse::<OperationId>().expect("hex parses"), id);
        assert_eq!(OperationId::try_from(&raw[..]).expect("bytes parse"), id);
    }

    #[test]
    fn operation_id_rejects_wrong_widths() {
        assert!(matches!(
            OperationId::try_from(&[1u8; 31][..]),
            Err(OperationIdParseError::InvalidByteLength { actual: 31 })
        ));
        assert!(matches!(
            "aa".parse::<OperationId>(),
            Err(OperationIdParseError::InvalidHexLength { actual: 2 })
        ));
    }

    #[test]
    fn operation_id_rejects_invalid_hex() {
        let text = format!("{}zz", "00".repeat(31));

        assert!(matches!(
            text.parse::<OperationId>(),
            Err(OperationIdParseError::InvalidHexCharacter { byte: b'z' })
        ));
    }

    #[test]
    fn command_kind_rejects_empty_and_space_values() {
        assert_eq!(CommandKind::new(""), Err(CommandKindError::Empty));
        assert_eq!(
            CommandKind::new("pool create"),
            Err(CommandKindError::InvalidCharacter)
        );
        assert_eq!(
            CommandKind::new("pool.create_empty.v1")
                .expect("kind")
                .as_str(),
            "pool.create_empty.v1"
        );
    }

    #[test]
    fn payload_hash_binds_command_kind_actor_and_payload() {
        let command = CommandKind::new("proof.issue.v1").expect("kind");
        let actor = ReplayActor::direct_caller(p(1));

        let mut first = ReplayPayloadHasher::new(&command, &actor);
        first.hash_str("payload");
        let first = first.finish();

        let mut changed_payload = ReplayPayloadHasher::new(&command, &actor);
        changed_payload.hash_str("other");
        assert_ne!(first, changed_payload.finish());

        let other_command = CommandKind::new("proof.issue.v2").expect("kind");
        let mut changed_command = ReplayPayloadHasher::new(&other_command, &actor);
        changed_command.hash_str("payload");
        assert_ne!(first, changed_command.finish());

        let other_actor = ReplayActor::direct_caller(p(2));
        let mut changed_actor = ReplayPayloadHasher::new(&command, &other_actor);
        changed_actor.hash_str("payload");
        assert_ne!(first, changed_actor.finish());
    }

    #[test]
    fn bounded_terminal_error_bytes_caps_large_payloads() {
        let small = bounded_terminal_error_bytes(b"error");
        assert_eq!(small.bytes, b"error");
        assert!(!small.truncated);

        let large = vec![7u8; MAX_REPLAY_TERMINAL_ERROR_BYTES + 12];
        let bounded = bounded_terminal_error_bytes(&large);
        assert_eq!(bounded.bytes.len(), MAX_REPLAY_TERMINAL_ERROR_BYTES);
        assert!(bounded.truncated);
    }
}