canic-root 0.266.2

Root for bounded controller-approved application canisters
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
//! Native codec for controller operations on a sharding Root.

use canic::method::Contract;
use canic::metrics::{ChildMetrics, Request};
#[cfg(feature = "sharding")]
use canic::sharding::{Allocation, BeginShardDrain, InspectShard, ShardTarget};
#[cfg(feature = "role-issuer")]
use canic::topology::attestation::CloseRoleIssuance;
use clap::{Parser, Subcommand};
#[cfg(feature = "sharding")]
use ic_platform_types::Principal;
use serde_json::{Value, json};
#[cfg(feature = "sharding")]
use std::fmt::Write as _;
use std::io::Read as _;

#[derive(Parser)]
struct Args {
    #[command(subcommand)]
    action: Action,
}

#[derive(Subcommand)]
enum Action {
    Encode {
        #[command(subcommand)]
        command: Command,
    },
    Decode,
}

#[derive(Subcommand)]
enum Command {
    /// Read Root diagnostics, newest first, optionally before a sequence in this incarnation.
    Logs { before: Option<u64> },
    /// Read one metrics source from a ready child.
    ChildMetrics {
        slot: u8,
        #[command(subcommand)]
        source: Source,
    },
    /// Retain this Root’s role-verification key for approving DB receivers.
    #[cfg(feature = "role-issuer")]
    PrepareRoleKey,
    /// End proof renewal once this exact shard generation is drained and empty.
    #[cfg(feature = "role-issuer")]
    CloseRoleIssuance {
        shard: Principal,
        #[arg(value_parser = generation)]
        generation: [u8; 32],
    },
    /// Advance an exact shard retirement using its approved Store release and balance floor (JSON).
    #[cfg(feature = "role-issuer")]
    RetireShard { approval: String },
    /// Stop new placements on the exact allocation returned by inspect-shard.
    #[cfg(feature = "sharding")]
    DrainShard {
        shard: Principal,
        slot: u32,
        #[arg(value_parser = generation)]
        generation: [u8; 32],
    },
    /// Approve the subnet ceiling from the reviewed fleet plan.
    #[cfg(feature = "sharding")]
    ConfigureCapacity { approval: String },
    /// Approve one singleton role for this registry.
    #[cfg(feature = "sharding")]
    ConfigureSingleton { approval: String },
    /// Approve recurring top-ups or inspect the original approval.
    #[cfg(feature = "sharding")]
    ConfigureChildFunding { approval: String },
    /// Stop future deposits to the named child.
    #[cfg(feature = "sharding")]
    StopChildFunding {
        child: Principal,
        #[arg(long)]
        parent: Option<Principal>,
    },
    /// Approve the reserve policy from the reviewed fleet plan.
    #[cfg(feature = "sharding")]
    ConfigureStandby { approval: String },
    /// Hand a claimable spare to the exact destination Root.
    #[cfg(feature = "sharding")]
    ExportStandby {
        principal: Principal,
        destination: Principal,
        expires_at_ns: u64,
    },
    /// Observe an exact external handoff and verify its proof quarantine.
    #[cfg(feature = "sharding")]
    ImportStandby { principal: Principal },
    /// Observe the standby inventory and the exact worker allocation holding each spare.
    #[cfg(feature = "sharding")]
    InspectStandby,
    /// Confirm the hub release of this exact worker target (JSON).
    #[cfg(feature = "sharding")]
    ConfirmWorkerRelease { target: String },
    /// Stop and uninstall an exact released worker. Resume with the original deadline.
    #[cfg(feature = "sharding")]
    ResetWorker { target: String, expires_at_ns: u64 },
    /// Authorize one new empty canister. Repeat the exact request to inspect its result.
    #[cfg(feature = "sharding")]
    RefillStandby {
        root: Principal,
        sequence: u8,
        cycles: u64,
        expires_at_ns: u64,
    },
    /// Report the allocation, drain state and live placement count.
    #[cfg(feature = "sharding")]
    InspectShard { shard: Principal },
}

#[derive(Subcommand)]
enum Source {
    Db,
    Entropy,
    Jobs,
    Timers,
    Blob,
    Endpoints { after: Option<String> },
}

#[cfg(feature = "sharding")]
fn generation(value: &str) -> Result<[u8; 32], String> {
    if value.len() != 64 || !value.bytes().all(|b| b.is_ascii_hexdigit()) {
        return Err("generation must contain 64 hex digits".into());
    }
    let mut bytes = [0; 32];
    for (i, byte) in bytes.iter_mut().enumerate() {
        *byte = u8::from_str_radix(&value[i * 2..i * 2 + 2], 16).map_err(|e| e.to_string())?;
    }

    Ok(bytes)
}

fn request<M: Contract>(input: &M::Input) -> Result<Value, String> {
    let arguments =
        M::encode_request(input).map_err(|e| format!("invalid {} request: {e:?}", M::NAME))?;

    Ok(json!({"method":M::NAME, "arguments":arguments}))
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let value = match Args::parse().action {
        Action::Encode {
            command: Command::Logs { before },
        } => request::<canic::logging::Logs>(&before)?,
        #[cfg(feature = "role-issuer")]
        Action::Encode {
            command: Command::PrepareRoleKey,
        } => request::<canic::topology::attestation::PrepareRoleKey>(&())?,
        #[cfg(feature = "role-issuer")]
        Action::Encode {
            command: Command::CloseRoleIssuance { shard, generation },
        } => request::<CloseRoleIssuance>(&(
            shard,
            ic_wire::Bytes::new(generation.to_vec()).expect("32-byte generation"),
        ))?,
        #[cfg(feature = "role-issuer")]
        Action::Encode {
            command: Command::RetireShard { approval },
        } => request::<canic_management_protocol::stored::RetireShard>(&serde_json::from_str(
            &approval,
        )?)?,
        Action::Encode {
            command: Command::ChildMetrics { slot, source },
        } => request::<ChildMetrics>(&(
            slot,
            match source {
                Source::Db => Request::Db,
                Source::Entropy => Request::Entropy,
                Source::Jobs => Request::Jobs,
                Source::Timers => Request::Timers,
                Source::Blob => Request::Blob,
                Source::Endpoints { after } => Request::Endpoints(after),
            },
        ))?,
        #[cfg(feature = "sharding")]
        Action::Encode {
            command: Command::InspectShard { shard },
        } => request::<InspectShard>(&shard)?,
        #[cfg(feature = "sharding")]
        Action::Encode {
            command:
                Command::DrainShard {
                    shard,
                    slot,
                    generation,
                },
        } => request::<BeginShardDrain>(&ShardTarget {
            shard,
            allocation: Allocation { slot, generation },
        })?,
        #[cfg(feature = "sharding")]
        Action::Encode {
            command: Command::ConfirmWorkerRelease { target },
        } => request::<canic::sharding::standby::ConfirmRelease>(&serde_json::from_str(&target)?)?,
        #[cfg(feature = "sharding")]
        Action::Encode {
            command:
                Command::ResetWorker {
                    target,
                    expires_at_ns,
                },
        } => request::<canic::sharding::standby::ResetWorker>(&(
            serde_json::from_str(&target)?,
            expires_at_ns,
        ))?,
        #[cfg(feature = "sharding")]
        Action::Encode {
            command: Command::ConfigureCapacity { approval },
        } => request::<canic_management_protocol::stored::ConfigureCapacity>(
            &serde_json::from_str(&approval)?,
        )?,
        #[cfg(feature = "sharding")]
        Action::Encode {
            command: Command::ConfigureSingleton { approval },
        } => request::<canic_management_protocol::stored::ConfigureSingleton>(
            &serde_json::from_str(&approval)?,
        )?,
        #[cfg(feature = "sharding")]
        Action::Encode {
            command: Command::ConfigureChildFunding { approval },
        } => request::<canic_management_protocol::stored::ConfigureChildFunding>(
            &serde_json::from_str(&approval)?,
        )?,
        #[cfg(feature = "sharding")]
        Action::Encode {
            command:
                Command::StopChildFunding {
                    child,
                    parent: None,
                },
        } => request::<canic_management_protocol::stored::StopChildFunding>(&child)?,
        #[cfg(feature = "sharding")]
        Action::Encode {
            command:
                Command::StopChildFunding {
                    child,
                    parent: Some(parent),
                },
        } => request::<canic_management_protocol::stored::StopApplicationChildFunding>(&(
            parent, child,
        ))?,
        #[cfg(feature = "sharding")]
        Action::Encode {
            command: Command::ConfigureStandby { approval },
        } => request::<canic_management_protocol::stored::ConfigureStandby>(
            &serde_json::from_str(&approval)?,
        )?,
        #[cfg(feature = "sharding")]
        Action::Encode {
            command:
                Command::ExportStandby {
                    principal,
                    destination,
                    expires_at_ns,
                },
        } => request::<canic::sharding::standby::ExportStandby>(&(
            principal,
            destination,
            expires_at_ns,
        ))?,
        #[cfg(feature = "sharding")]
        Action::Encode {
            command: Command::ImportStandby { principal },
        } => request::<canic::sharding::standby::ImportStandby>(&principal)?,
        #[cfg(feature = "sharding")]
        Action::Encode {
            command: Command::InspectStandby,
        } => request::<canic::sharding::standby::InspectStandby>(&())?,
        #[cfg(feature = "sharding")]
        Action::Encode {
            command:
                Command::RefillStandby {
                    root,
                    sequence,
                    cycles,
                    expires_at_ns,
                },
        } => {
            request::<canic::sharding::standby::RefillStandby>(&canic::sharding::standby::Refill {
                root,
                sequence,
                cycles,
                expires_at_ns,
            })?
        }
        Action::Decode => {
            let mut bytes = Vec::new();
            std::io::stdin()
                .take((reply_limit() + 1) as u64)
                .read_to_end(&mut bytes)?;

            decode(&bytes)?
        }
    };
    println!("{value}");

    Ok(())
}

fn reply_limit() -> usize {
    let limit = ChildMetrics::REPLY
        .bytes
        .max(canic::logging::Logs::REPLY.bytes);
    #[cfg(feature = "sharding")]
    let limit = canic::sharding::standby::InspectStandby::REPLY
        .bytes
        .max(canic::sharding::LIMITS.bytes)
        .max(limit);
    limit
}

fn decode(bytes: &[u8]) -> Result<Value, Box<dyn std::error::Error>> {
    if let Ok(page) = canic::logging::Logs::decode_reply(bytes) {
        return Ok(serde_json::to_value(page)?);
    }
    if let Ok(page) = ChildMetrics::decode_reply(bytes) {
        return Ok(serde_json::to_value(page)?);
    }
    #[cfg(feature = "role-issuer")]
    if let Ok(reply) = canic::topology::attestation::PrepareRoleKey::decode_reply(bytes) {
        return Ok(json!({"issuer_key": reply?.into_vec()}));
    }
    #[cfg(feature = "role-issuer")]
    if let Ok(reply) = CloseRoleIssuance::decode_reply(bytes) {
        return Ok(json!({"proof_deadline_ns": reply?.to_string()}));
    }
    #[cfg(feature = "sharding")]
    if let Ok(reply) = InspectShard::decode_reply(bytes) {
        let status = reply?;
        let mut generation = String::with_capacity(64);
        for b in status.target.allocation.generation {
            write!(generation, "{b:02x}")?;
        }

        return Ok(json!({
            "shard": status.target.shard.to_text(),
            "slot": status.target.allocation.slot,
            "generation": generation,
            "draining": status.draining,
            "live_placements": status.live_placements,
        }));
    }
    #[cfg(feature = "sharding")]
    if let Ok(reply) = BeginShardDrain::decode_reply(bytes) {
        return Ok(json!({"draining": true, "live_placements": reply?}));
    }
    #[cfg(feature = "sharding")]
    if let Ok(reply) = canic_management_protocol::stored::ConfigureCapacity::decode_reply(bytes) {
        reply.map_err(|e| format!("capacity: {e:?}"))?;
        return Ok(json!({"approved":true}));
    }
    #[cfg(feature = "sharding")]
    if let Ok(reply) = canic_management_protocol::stored::ConfigureSingleton::decode_reply(bytes) {
        reply.map_err(|e| format!("singleton: {e:?}"))?;
        return Ok(json!({"approved":true}));
    }
    #[cfg(feature = "sharding")]
    if let Ok(reply) = canic_management_protocol::stored::ConfigureChildFunding::decode_reply(bytes)
    {
        return Ok(serde_json::to_value(reply?)?);
    }
    #[cfg(feature = "sharding")]
    if let Ok(reply) = canic_management_protocol::stored::StopChildFunding::decode_reply(bytes) {
        return Ok(serde_json::to_value(reply?)?);
    }
    #[cfg(feature = "sharding")]
    if let Ok(reply) =
        canic_management_protocol::stored::StopApplicationChildFunding::decode_reply(bytes)
    {
        return Ok(serde_json::to_value(reply?)?);
    }
    #[cfg(feature = "sharding")]
    if let Ok(reply) = canic_management_protocol::stored::ConfigureStandby::decode_reply(bytes) {
        reply?;
        return Ok(json!({"approved":true}));
    }
    #[cfg(feature = "sharding")]
    if let Ok(reply) = canic::sharding::standby::ExportStandby::decode_reply(bytes) {
        return Ok(serde_json::to_value(reply?)?);
    }
    #[cfg(feature = "sharding")]
    if let Ok(reply) = canic::sharding::standby::ImportStandby::decode_reply(bytes) {
        return Ok(serde_json::to_value(reply?)?);
    }
    #[cfg(feature = "sharding")]
    if let Ok(reply) = canic::sharding::standby::InspectStandby::decode_reply(bytes) {
        return Ok(serde_json::to_value(reply)?);
    }
    #[cfg(feature = "sharding")]
    if let Ok(reply) = canic::sharding::standby::RefillStandby::decode_reply(bytes) {
        return Ok(serde_json::to_value(reply?)?);
    }
    #[cfg(feature = "sharding")]
    if let Ok(reply) = canic::sharding::standby::ConfirmRelease::decode_reply(bytes) {
        reply?;
        return Ok(json!({"released": true}));
    }
    #[cfg(feature = "sharding")]
    if let Ok(reply) = canic::sharding::standby::ResetWorker::decode_reply(bytes) {
        return Ok(json!({"reset": reply?}));
    }
    #[cfg(feature = "role-issuer")]
    if let Ok(reply) = canic_management_protocol::stored::RetireShard::decode_reply(bytes) {
        return Ok(json!({"retirement":reply?}));
    }
    Err("unknown Root reply".into())
}