canic-core 0.26.3

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
pub mod attestation;
pub mod cycles;
pub mod install;
pub mod intent;
pub mod log;
pub mod timer;

use crate::{
    InternalError, InternalErrorOrigin, VERSION,
    config::ConfigModel,
    domain::policy::env::{EnvInput, EnvPolicyError, validate_or_default},
    dto::{abi::v1::CanisterInitPayload, subnet::SubnetIdentity},
    ids::SubnetRole,
    ops::{
        config::ConfigOps,
        ic::{IcOps, ecdsa::EcdsaOps, network::NetworkOps},
        runtime::{
            env::EnvOps,
            memory::{MemoryRegistryInitSummary, MemoryRegistryOps},
        },
        storage::{
            directory::{app::AppDirectoryOps, subnet::SubnetDirectoryOps},
            registry::subnet::SubnetRegistryOps,
            state::app::AppStateOps,
        },
    },
    workflow::{self, env::EnvWorkflow, prelude::*},
};

///
/// RuntimeWorkflow
/// Coordinates periodic background services (timers) for Canic canisters.
///

pub struct RuntimeWorkflow;

impl RuntimeWorkflow {
    /// Start timers that should run on all non-root canisters.
    pub fn start_all() {
        workflow::runtime::log::LogRetentionWorkflow::start();
        workflow::runtime::cycles::CycleTrackerWorkflow::start();
    }

    /// Start timers that should run on delegated-auth-aware non-root canisters.
    pub fn start_all_with_attestation_cache() {
        log_delegation_proof_cache_policy();
        workflow::runtime::attestation::AttestationKeyCacheWorkflow::start();
        Self::start_all();
    }

    /// Start timers that should run only on root canisters.
    pub fn start_all_root() -> Result<(), InternalError> {
        EnvOps::require_root().map_err(|err| {
            InternalError::invariant(
                InternalErrorOrigin::Workflow,
                format!("root context required: {err}"),
            )
        })?;

        // start shared timers too
        Self::start_all();

        // root-only services
        workflow::pool::scheduler::PoolSchedulerWorkflow::start();
        Ok(())
    }
}

// Log the resolved verifier proof-cache policy once during runtime startup.
fn log_delegation_proof_cache_policy() {
    match ConfigOps::delegation_proof_cache_policy() {
        Ok(policy) => crate::log!(
            Topic::Auth,
            Info,
            "delegation proof cache policy profile={} capacity={} active_window_secs={}",
            policy.profile.as_str(),
            policy.capacity,
            policy.active_window_secs
        ),
        Err(err) => crate::log!(
            Topic::Auth,
            Warn,
            "delegation proof cache policy unavailable at runtime startup: {err}"
        ),
    }
}

fn log_memory_summary(summary: &MemoryRegistryInitSummary) {
    for range in &summary.ranges {
        let used = summary
            .entries
            .iter()
            .filter(|entry| entry.id >= range.start && entry.id <= range.end)
            .count();

        crate::log!(
            Topic::Memory,
            Info,
            "💾 memory.range: {} [{}-{}] ({}/{} slots used)",
            range.crate_name,
            range.start,
            range.end,
            used,
            range.end - range.start + 1,
        );
    }
}

fn init_post_upgrade_memory_registry() -> Result<MemoryRegistryInitSummary, InternalError> {
    MemoryRegistryOps::bootstrap_registry().map_err(|err| {
        InternalError::invariant(
            InternalErrorOrigin::Workflow,
            format!("memory init failed: {err}"),
        )
    })
}

///
/// init_root_canister
/// Bootstraps the root canister runtime and environment.
///

pub fn init_root_canister(identity: SubnetIdentity) -> Result<(), InternalError> {
    // --- Phase 1: Init base systems ---
    let memory_summary = match MemoryRegistryOps::bootstrap_registry() {
        Ok(summary) => summary,
        Err(err) => {
            return Err(InternalError::invariant(
                InternalErrorOrigin::Workflow,
                format!("memory init failed: {err}"),
            ));
        }
    };
    crate::log::set_ready();

    // log header
    IcOps::println("");
    IcOps::println("");
    IcOps::println("");
    crate::log!(
        Topic::Init,
        Info,
        "🔧 --------------------- canic v{VERSION} -----------------------",
    );
    crate::log!(Topic::Init, Info, "🏁 init: root ({identity:?})");
    log_memory_summary(&memory_summary);

    // --- Phase 2: Env registration ---
    let self_pid = IcOps::canister_self();
    let (subnet_pid, subnet_role, prime_root_pid) = match identity {
        SubnetIdentity::Prime => (self_pid, SubnetRole::PRIME, self_pid),
        SubnetIdentity::Standard(params) => (self_pid, params.subnet_type, params.prime_root_pid),
        SubnetIdentity::Manual => (IcOps::canister_self(), SubnetRole::PRIME, self_pid),
    };

    let input = EnvInput {
        prime_root_pid: Some(prime_root_pid),
        subnet_role: Some(subnet_role),
        subnet_pid: Some(subnet_pid),
        root_pid: Some(self_pid),
        canister_role: Some(CanisterRole::ROOT),
        parent_pid: Some(prime_root_pid),
    };

    let network = NetworkOps::build_network().ok_or_else(|| {
        InternalError::invariant(
            InternalErrorOrigin::Workflow,
            "runtime network unavailable; set DFX_NETWORK=local|ic at build time".to_string(),
        )
    })?;
    crate::log!(Topic::Init, Info, "build network: {network}");
    let validated = match validate_or_default(network, input) {
        Ok(validated) => validated,
        Err(EnvPolicyError::MissingEnvFields(missing)) => {
            return Err(InternalError::invariant(
                InternalErrorOrigin::Workflow,
                format!("env args missing {missing}; local builds require explicit env fields"),
            ));
        }
    };

    if let Err(err) = EnvOps::import_validated(validated) {
        return Err(InternalError::invariant(
            InternalErrorOrigin::Workflow,
            format!("env import failed: {err}"),
        ));
    }

    let app_mode = ConfigOps::app_init_mode().map_err(|err| {
        InternalError::invariant(
            InternalErrorOrigin::Workflow,
            format!("app mode init failed: {err}"),
        )
    })?;
    AppStateOps::init_mode(app_mode);
    ensure_root_delegated_auth_crypto_contract()?;

    let created_at = IcOps::now_secs();
    SubnetRegistryOps::register_root(self_pid, created_at);

    // --- Phase 3: Service startup ---
    RuntimeWorkflow::start_all_root().map_err(|err| {
        InternalError::invariant(
            InternalErrorOrigin::Workflow,
            format!("root service startup failed: {err}"),
        )
    })?;

    Ok(())
}

///
/// post_upgrade_root_canister
///

pub fn post_upgrade_root_canister_after_memory_init(
    memory_summary: MemoryRegistryInitSummary,
) -> Result<(), InternalError> {
    crate::log::set_ready();
    crate::log!(Topic::Init, Info, "🏁 post_upgrade_root_canister");
    log_memory_summary(&memory_summary);

    // ---  Phase 2 intentionally omitted: post-upgrade does not re-import env or directories.
    ensure_root_delegated_auth_crypto_contract()?;

    // --- Phase 3: Service startup ---
    RuntimeWorkflow::start_all_root().map_err(|err| {
        InternalError::invariant(
            InternalErrorOrigin::Workflow,
            format!("root service startup failed: {err}"),
        )
    })?;

    Ok(())
}

///
/// init_nonroot_canister
///

pub fn init_nonroot_canister(
    canister_role: CanisterRole,
    payload: CanisterInitPayload,
) -> Result<(), InternalError> {
    init_nonroot_canister_internal(canister_role, payload, false)
}

pub fn init_nonroot_canister_with_attestation_cache(
    canister_role: CanisterRole,
    payload: CanisterInitPayload,
) -> Result<(), InternalError> {
    init_nonroot_canister_internal(canister_role, payload, true)
}

// Initialize a non-root canister and start only the runtime services it needs.
fn init_nonroot_canister_internal(
    canister_role: CanisterRole,
    payload: CanisterInitPayload,
    with_attestation_cache: bool,
) -> Result<(), InternalError> {
    // --- Phase 1: Init base systems ---
    let memory_summary = MemoryRegistryOps::bootstrap_registry().map_err(|err| {
        InternalError::invariant(
            InternalErrorOrigin::Workflow,
            format!("memory init failed: {err}"),
        )
    })?;
    crate::log::set_ready();
    crate::log!(Topic::Init, Info, "🏁 init: {}", canister_role);
    log_memory_summary(&memory_summary);

    // --- Phase 2: Payload registration ---
    EnvWorkflow::init_env_from_args(payload.env, canister_role.clone()).map_err(|err| {
        InternalError::invariant(
            InternalErrorOrigin::Workflow,
            format!("env import failed: {err}"),
        )
    })?;

    AppDirectoryOps::import_args_allow_incomplete(payload.app_directory).map_err(|err| {
        InternalError::invariant(
            InternalErrorOrigin::Workflow,
            format!("app directory import failed: {err}"),
        )
    })?;
    SubnetDirectoryOps::import_args_allow_incomplete(payload.subnet_directory).map_err(|err| {
        InternalError::invariant(
            InternalErrorOrigin::Workflow,
            format!("subnet directory import failed: {err}"),
        )
    })?;

    let app_mode = ConfigOps::app_init_mode().map_err(|err| {
        InternalError::invariant(
            InternalErrorOrigin::Workflow,
            format!("app mode init failed: {err}"),
        )
    })?;
    AppStateOps::init_mode(app_mode);
    let canister_cfg = ConfigOps::current_canister()?;
    ensure_nonroot_delegated_auth_crypto_contract(&canister_role, &canister_cfg)?;

    // --- Phase 3: Service startup ---
    if with_attestation_cache {
        RuntimeWorkflow::start_all_with_attestation_cache();
    } else {
        RuntimeWorkflow::start_all();
    }

    Ok(())
}

///
/// post_upgrade_nonroot_canister
///

pub fn post_upgrade_nonroot_canister_after_memory_init(
    canister_role: CanisterRole,
    memory_summary: MemoryRegistryInitSummary,
) {
    post_upgrade_nonroot_canister_after_memory_init_internal(canister_role, memory_summary, false);
}

pub fn post_upgrade_nonroot_canister_after_memory_init_with_attestation_cache(
    canister_role: CanisterRole,
    memory_summary: MemoryRegistryInitSummary,
) {
    post_upgrade_nonroot_canister_after_memory_init_internal(canister_role, memory_summary, true);
}

// Restore post-upgrade runtime services for a non-root canister.
fn post_upgrade_nonroot_canister_after_memory_init_internal(
    canister_role: CanisterRole,
    memory_summary: MemoryRegistryInitSummary,
    with_attestation_cache: bool,
) {
    crate::log::set_ready();
    crate::log!(
        Topic::Init,
        Info,
        "🏁 post_upgrade_nonroot_canister: {}",
        canister_role
    );
    log_memory_summary(&memory_summary);

    // ---  Phase 2 intentionally omitted: post-upgrade does not re-import env or directories.
    let canister_cfg = ConfigOps::current_canister().unwrap_or_else(|err| {
        panic!("current canister config unavailable during post-upgrade runtime init: {err}")
    });
    ensure_nonroot_delegated_auth_crypto_contract(&canister_role, &canister_cfg)
        .unwrap_or_else(|err| panic!("non-root delegated auth runtime contract failed: {err}"));

    // --- Phase 3: Service startup ---
    if with_attestation_cache {
        RuntimeWorkflow::start_all_with_attestation_cache();
    } else {
        RuntimeWorkflow::start_all();
    }
}

pub fn init_memory_registry_post_upgrade() -> Result<MemoryRegistryInitSummary, InternalError> {
    init_post_upgrade_memory_registry()
}

fn ensure_root_delegated_auth_crypto_contract() -> Result<(), InternalError> {
    let cfg = ConfigOps::get()?;
    if root_requires_auth_crypto(&cfg) && !EcdsaOps::threshold_management_enabled() {
        return Err(InternalError::invariant(
            InternalErrorOrigin::Workflow,
            "delegated auth is configured in canic.toml, but this root build does not include threshold ECDSA management support; enable the `auth-crypto` feature for the root canister build".to_string(),
        ));
    }

    Ok(())
}

fn ensure_nonroot_delegated_auth_crypto_contract(
    canister_role: &CanisterRole,
    canister_cfg: &crate::config::schema::CanisterConfig,
) -> Result<(), InternalError> {
    if nonroot_requires_auth_crypto(canister_cfg) && !EcdsaOps::threshold_management_enabled() {
        return Err(InternalError::invariant(
            InternalErrorOrigin::Workflow,
            format!(
                "canister '{canister_role}' is configured as a delegated auth signer, but this build does not include threshold ECDSA management support; enable the `auth-crypto` feature for that canister build",
            ),
        ));
    }

    Ok(())
}

fn root_requires_auth_crypto(cfg: &ConfigModel) -> bool {
    cfg.auth.delegated_tokens.enabled
        && cfg.subnets.values().any(|subnet| {
            subnet
                .canisters
                .values()
                .any(|canister| canister.delegated_auth.signer || canister.delegated_auth.verifier)
        })
}

const fn nonroot_requires_auth_crypto(
    canister_cfg: &crate::config::schema::CanisterConfig,
) -> bool {
    canister_cfg.delegated_auth.signer
}

#[cfg(test)]
mod tests {
    use super::{nonroot_requires_auth_crypto, root_requires_auth_crypto};
    use crate::{
        config::schema::{CanisterKind, DelegatedAuthCanisterConfig},
        ids::CanisterRole,
        test::config::ConfigTestBuilder,
    };

    #[test]
    fn root_requires_auth_crypto_when_any_delegated_auth_role_exists() {
        let mut verifier_cfg = ConfigTestBuilder::canister_config(CanisterKind::Singleton);
        verifier_cfg.delegated_auth = DelegatedAuthCanisterConfig {
            signer: false,
            verifier: true,
        };

        let cfg = ConfigTestBuilder::new()
            .with_prime_canister(
                CanisterRole::ROOT,
                ConfigTestBuilder::canister_config(CanisterKind::Root),
            )
            .with_prime_canister("user_hub", verifier_cfg)
            .build();

        assert!(root_requires_auth_crypto(&cfg));
    }

    #[test]
    fn root_does_not_require_auth_crypto_without_delegated_auth_roles() {
        let cfg = ConfigTestBuilder::new().build();

        assert!(!root_requires_auth_crypto(&cfg));
    }

    #[test]
    fn verifier_only_nonroot_does_not_require_auth_crypto() {
        let mut verifier_cfg = ConfigTestBuilder::canister_config(CanisterKind::Singleton);
        verifier_cfg.delegated_auth = DelegatedAuthCanisterConfig {
            signer: false,
            verifier: true,
        };

        assert!(!nonroot_requires_auth_crypto(&verifier_cfg));
    }

    #[test]
    fn signer_nonroot_requires_auth_crypto() {
        let mut signer_cfg = ConfigTestBuilder::canister_config(CanisterKind::Shard);
        signer_cfg.delegated_auth = DelegatedAuthCanisterConfig {
            signer: true,
            verifier: true,
        };

        assert!(nonroot_requires_auth_crypto(&signer_cfg));
    }
}