1use ahash::{AHashMap, AHashSet};
2use async_trait::async_trait;
3use candid::Principal;
4use futures::StreamExt;
5use ic_agent::{Agent, AgentError, agent::SubnetType, hash_tree::SubtreeLookupResult};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub struct CanisterRange {
11 pub start: Principal,
12 pub end: Principal,
13}
14
15#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct SubnetData {
18 pub subnet_type: SubnetType,
19 pub ranges: Vec<CanisterRange>,
20}
21
22#[async_trait]
24pub trait AgentExt {
25 async fn fetch_subnet_ids(
27 &self,
28 root_subnet_id: Principal,
29 ) -> Result<AHashSet<Principal>, AgentError>;
30
31 async fn fetch_subnet_data(&self, subnet_id: &Principal) -> Result<SubnetData, AgentError>;
33
34 async fn fetch_all_subnets_data(
38 &self,
39 root_subnet_id: Principal,
40 concurrency: Option<usize>,
41 ) -> Result<AHashMap<Principal, Result<SubnetData, AgentError>>, AgentError>;
42}
43
44#[async_trait]
45impl AgentExt for Agent {
46 async fn fetch_subnet_ids(
48 &self,
49 root_subnet_id: Principal,
50 ) -> Result<AHashSet<Principal>, AgentError> {
51 let cert = self
52 .read_subnet_state_raw(vec![vec!["subnet".into()]], root_subnet_id)
53 .await
54 .map_err(|e| {
55 AgentError::MessageError(format!("failed to read /subnet from NNS: {e:#}"))
56 })?;
57
58 let SubtreeLookupResult::Found(subnet_tree) =
59 cert.tree.lookup_subtree([b"subnet".as_ref()])
60 else {
61 return Err(AgentError::MessageError(
62 "/subnet subtree not found in NNS state tree".into(),
63 ));
64 };
65
66 let subnet_ids = subnet_tree
70 .list_paths()
71 .iter()
72 .filter(|p| !p.is_empty())
73 .map(|p| {
74 Principal::try_from_slice(p[0].as_bytes()).map_err(|e| {
75 AgentError::MessageError(format!(
76 "Malformed subnet ID in the NNS state tree: {e:#}"
77 ))
78 })
79 })
80 .collect::<Result<_, _>>()?;
81
82 Ok(subnet_ids)
83 }
84
85 async fn fetch_subnet_data(&self, subnet_id: &Principal) -> Result<SubnetData, AgentError> {
86 let subnet = self
87 .fetch_subnet_by_id(subnet_id)
88 .await
89 .map_err(|e| AgentError::MessageError(format!("Failed to fetch subnet info: {e:#}")))?;
90
91 let ranges = subnet
92 .iter_canister_ranges()
93 .map(|r| CanisterRange {
94 start: *r.start(),
95 end: *r.end(),
96 })
97 .collect();
98
99 let Some(subnet_type) = subnet.subnet_type().cloned() else {
100 return Err(AgentError::MessageError("Missing subnet type".into()));
101 };
102
103 Ok(SubnetData {
104 ranges,
105 subnet_type,
106 })
107 }
108
109 async fn fetch_all_subnets_data(
110 &self,
111 root_subnet_id: Principal,
112 concurrency: Option<usize>,
113 ) -> Result<AHashMap<Principal, Result<SubnetData, AgentError>>, AgentError> {
114 let subnet_ids = self
115 .fetch_subnet_ids(root_subnet_id)
116 .await
117 .map_err(|e| AgentError::MessageError(format!("Failed to fetch subnet IDs: {e:#}")))?;
118
119 let futures = subnet_ids
120 .into_iter()
121 .map(|x| async move { (x, self.fetch_subnet_data(&x).await) });
122
123 let stream = futures::stream::iter(futures).buffer_unordered(concurrency.unwrap_or(1));
124 let results = AHashMap::from_iter(stream.collect::<Vec<_>>().await);
125
126 Ok(results)
127 }
128}
129
130pub const DEFAULT_MAX_INGRESS_MESSAGE_SIZE: usize = 2 * 1024 * 1024; #[cfg(test)]
142mod test {
143 use std::time::{SystemTime, UNIX_EPOCH};
144
145 use axum::Router;
146 use ic_agent::{
147 Certificate,
148 export::serde_bytes,
149 hash_tree::{HashTree, empty, fork, label, leaf},
150 };
151 use ic_verify_bls_signature::PrivateKey;
152 use tokio::net::TcpListener;
153
154 use super::*;
155
156 type Tree = HashTree<Vec<u8>>;
157
158 const DER_PREFIX: &[u8; 37] = b"\x30\x81\x82\x30\x1d\x06\x0d\x2b\x06\x01\x04\x01\x82\xdc\x7c\x05\x03\x01\x02\x01\x06\x0c\x2b\x06\x01\x04\x01\x82\xdc\x7c\x05\x03\x02\x01\x03\x61\x00";
162 const DOMAIN_SEPARATOR: &[u8; 14] = b"\x0dic-state-root";
163
164 fn leb128(mut v: u64) -> Vec<u8> {
165 let mut buf = vec![];
166 loop {
167 let byte = (v & 0x7f) as u8;
168 v >>= 7;
169 if v == 0 {
170 buf.push(byte);
171 return buf;
172 }
173 buf.push(byte | 0x80);
174 }
175 }
176
177 fn tree_of(mut entries: Vec<(Vec<u8>, Tree)>) -> Tree {
181 entries.sort_by(|a, b| a.0.cmp(&b.0));
182 let mut iter = entries.into_iter().map(|(l, t)| label(l, t));
183 let first = iter.next().expect("at least one entry");
184 iter.fold(first, fork)
185 }
186
187 fn certify(tree: Tree) -> (Vec<u8>, Certificate) {
191 let sk = PrivateKey::random(&mut rand::thread_rng());
192
193 let mut root_key = DER_PREFIX.to_vec();
194 root_key.extend_from_slice(&sk.public_key().serialize());
195
196 let mut msg = DOMAIN_SEPARATOR.to_vec();
197 msg.extend_from_slice(&tree.digest());
198 let signature = sk.sign(&msg).serialize().to_vec();
199
200 (
201 root_key,
202 Certificate {
203 tree,
204 signature,
205 delegation: None,
206 },
207 )
208 }
209
210 fn read_state_response_body(cert: &Certificate) -> Vec<u8> {
213 #[derive(serde::Serialize)]
214 struct ReadStateResponse {
215 #[serde(with = "serde_bytes")]
216 certificate: Vec<u8>,
217 }
218
219 serde_cbor::to_vec(&ReadStateResponse {
220 certificate: serde_cbor::to_vec(cert).unwrap(),
221 })
222 .unwrap()
223 }
224
225 async fn spawn_fake_replica(body: Vec<u8>) -> String {
228 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
229 let addr = listener.local_addr().unwrap();
230
231 let app = Router::new().fallback(move || {
232 let body = body.clone();
233 async move { body }
234 });
235
236 tokio::spawn(async move {
237 axum::serve(listener, app).await.unwrap();
238 });
239
240 format!("http://{addr}")
241 }
242
243 #[tokio::test]
244 async fn fetch_subnet_ids_verifies_against_fake_root_key() {
245 let root_subnet_id = Principal::from_slice(&[0xaa; 10]);
246 let subnet_a = Principal::from_slice(&[0x01; 10]);
247 let subnet_b = Principal::from_slice(&[0x02; 10]);
248
249 let now_ns = SystemTime::now()
250 .duration_since(UNIX_EPOCH)
251 .unwrap()
252 .as_nanos() as u64;
253
254 let subnet_tree = tree_of(vec![
255 (subnet_a.as_slice().to_vec(), leaf(vec![1])),
256 (subnet_b.as_slice().to_vec(), leaf(vec![1])),
257 ]);
258 let tree = tree_of(vec![
259 (b"subnet".to_vec(), subnet_tree),
260 (b"time".to_vec(), leaf(leb128(now_ns))),
261 ]);
262
263 let (root_key, cert) = certify(tree);
264 let url = spawn_fake_replica(read_state_response_body(&cert)).await;
265
266 let agent = Agent::builder().with_url(&url).build().unwrap();
267 agent.set_root_key(root_key);
268
269 let ids = agent.fetch_subnet_ids(root_subnet_id).await.unwrap();
270 assert_eq!(ids, AHashSet::from_iter([subnet_a, subnet_b]));
271 }
272
273 #[tokio::test]
274 async fn fetch_subnet_data_verifies_against_fake_root_key() {
275 let subnet_id = Principal::from_slice(&[0x03; 10]);
276 let range_start = Principal::from_slice(&[0x00; 10]);
277 let range_end = Principal::from_slice(&[0xff; 10]);
278
279 let now_ns = SystemTime::now()
280 .duration_since(UNIX_EPOCH)
281 .unwrap()
282 .as_nanos() as u64;
283
284 let subnet_inner = tree_of(vec![
285 (b"node".to_vec(), empty()),
286 (b"public_key".to_vec(), leaf(vec![9, 9, 9])),
287 (b"type".to_vec(), leaf(b"application".to_vec())),
288 ]);
289
290 let ranges_cbor = serde_cbor::to_vec(&vec![(range_start, range_end)]).unwrap();
291 let shard_tree = tree_of(vec![(b"shard".to_vec(), leaf(ranges_cbor))]);
292
293 let tree = tree_of(vec![
294 (
295 b"canister_ranges".to_vec(),
296 tree_of(vec![(subnet_id.as_slice().to_vec(), shard_tree)]),
297 ),
298 (
299 b"subnet".to_vec(),
300 tree_of(vec![(subnet_id.as_slice().to_vec(), subnet_inner)]),
301 ),
302 (b"time".to_vec(), leaf(leb128(now_ns))),
303 ]);
304
305 let (root_key, cert) = certify(tree);
306 let url = spawn_fake_replica(read_state_response_body(&cert)).await;
307
308 let agent = Agent::builder().with_url(&url).build().unwrap();
309 agent.set_root_key(root_key);
310
311 let data = agent.fetch_subnet_data(&subnet_id).await.unwrap();
312 assert_eq!(data.subnet_type, SubnetType::Application);
313 assert_eq!(
314 data.ranges,
315 vec![CanisterRange {
316 start: range_start,
317 end: range_end
318 }]
319 );
320 }
321
322 #[tokio::test]
323 async fn fetch_all_subnets_data_verifies_against_fake_root_key() {
324 let root_subnet_id = Principal::from_slice(&[0xaa; 10]);
325 let subnet_a = Principal::from_slice(&[0x01; 10]);
326 let subnet_b = Principal::from_slice(&[0x02; 10]);
327
328 let range_a = (
329 Principal::from_slice(&[0x00; 10]),
330 Principal::from_slice(&[0x7f; 10]),
331 );
332 let range_b = (
333 Principal::from_slice(&[0x80; 10]),
334 Principal::from_slice(&[0xff; 10]),
335 );
336
337 let now_ns = SystemTime::now()
338 .duration_since(UNIX_EPOCH)
339 .unwrap()
340 .as_nanos() as u64;
341
342 let subnet_inner = |subnet_type: &str| {
343 tree_of(vec![
344 (b"node".to_vec(), empty()),
345 (b"public_key".to_vec(), leaf(vec![9, 9, 9])),
346 (b"type".to_vec(), leaf(subnet_type.as_bytes().to_vec())),
347 ])
348 };
349
350 let ranges_tree = |range: (Principal, Principal)| {
351 let ranges_cbor = serde_cbor::to_vec(&vec![range]).unwrap();
352 tree_of(vec![(b"shard".to_vec(), leaf(ranges_cbor))])
353 };
354
355 let tree = tree_of(vec![
356 (
357 b"canister_ranges".to_vec(),
358 tree_of(vec![
359 (subnet_a.as_slice().to_vec(), ranges_tree(range_a)),
360 (subnet_b.as_slice().to_vec(), ranges_tree(range_b)),
361 ]),
362 ),
363 (
364 b"subnet".to_vec(),
365 tree_of(vec![
366 (subnet_a.as_slice().to_vec(), subnet_inner("application")),
367 (subnet_b.as_slice().to_vec(), subnet_inner("system")),
368 ]),
369 ),
370 (b"time".to_vec(), leaf(leb128(now_ns))),
371 ]);
372
373 let (root_key, cert) = certify(tree);
374 let url = spawn_fake_replica(read_state_response_body(&cert)).await;
375
376 let agent = Agent::builder().with_url(&url).build().unwrap();
377 agent.set_root_key(root_key);
378
379 let results = agent
381 .fetch_all_subnets_data(root_subnet_id, Some(4))
382 .await
383 .unwrap();
384
385 assert_eq!(results.len(), 2);
386 assert_eq!(
387 results.get(&subnet_a).unwrap().as_ref().unwrap(),
388 &SubnetData {
389 subnet_type: SubnetType::Application,
390 ranges: vec![CanisterRange {
391 start: range_a.0,
392 end: range_a.1
393 }],
394 }
395 );
396 assert_eq!(
397 results.get(&subnet_b).unwrap().as_ref().unwrap(),
398 &SubnetData {
399 subnet_type: SubnetType::System,
400 ranges: vec![CanisterRange {
401 start: range_b.0,
402 end: range_b.1
403 }],
404 }
405 );
406 }
407}