-
Notifications
You must be signed in to change notification settings - Fork 296
/
metadata_state.rs
2327 lines (2103 loc) · 92.8 KB
/
metadata_state.rs
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
pub mod subnet_call_context_manager;
#[cfg(test)]
mod tests;
use crate::metadata_state::subnet_call_context_manager::SubnetCallContextManager;
use crate::CanisterQueues;
use crate::{canister_state::system_state::CyclesUseCase, CheckpointLoadingMetrics};
use ic_base_types::CanisterId;
use ic_btc_types_internal::BlockBlob;
use ic_certification_version::{CertificationVersion, CURRENT_CERTIFICATION_VERSION};
use ic_constants::MAX_INGRESS_TTL;
use ic_error_types::{ErrorCode, RejectCode, UserError};
use ic_ic00_types::{EcdsaKeyId, NodeMetrics, NodeMetricsHistoryResponse};
use ic_protobuf::{
proxy::{try_from_option_field, ProxyDecodeError},
registry::subnet::v1 as pb_subnet,
state::{
canister_state_bits::v1::ConsumedCyclesByUseCase,
ingress::v1 as pb_ingress,
queues::v1 as pb_queues,
system_metadata::v1::{self as pb_metadata},
},
types::v1 as pb_types,
};
use ic_registry_routing_table::{
canister_id_into_u64, difference, intersection, CanisterIdRanges, CanisterMigrations,
RoutingTable, CANISTER_IDS_PER_SUBNET,
};
use ic_registry_subnet_features::SubnetFeatures;
use ic_registry_subnet_type::SubnetType;
use ic_types::{
batch::BlockmakerMetrics,
crypto::CryptoHash,
ingress::{IngressState, IngressStatus},
messages::{
is_subnet_id, CanisterCall, MessageId, Payload, RejectContext, RequestOrResponse, Response,
},
node_id_into_protobuf, node_id_try_from_option,
nominal_cycles::NominalCycles,
state_sync::{StateSyncVersion, CURRENT_STATE_SYNC_VERSION},
subnet_id_into_protobuf, subnet_id_try_from_protobuf,
time::{Time, UNIX_EPOCH},
xnet::{StreamHeader, StreamIndex, StreamIndexedQueue, StreamSlice},
CountBytes, CryptoHashOfPartialState, NodeId, NumBytes, PrincipalId, SubnetId,
};
use ic_wasm_types::WasmHash;
use serde::{Deserialize, Serialize};
use std::ops::Bound::{Included, Unbounded};
use std::{
collections::{BTreeMap, BTreeSet, VecDeque},
convert::{From, TryFrom, TryInto},
mem::size_of,
sync::Arc,
};
/// `BTreeMap` of streams by destination `SubnetId`.
pub type StreamMap = BTreeMap<SubnetId, Stream>;
/// Replicated system metadata. Used primarily for inter-canister messaging and
/// history queries.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SystemMetadata {
/// History of ingress messages as they traversed through the
/// system.
pub ingress_history: IngressHistoryState,
/// XNet stream state indexed by the _destination_ subnet id.
pub(super) streams: Arc<Streams>,
/// The canister ID ranges from which this subnet generates canister IDs.
canister_allocation_ranges: CanisterIdRanges,
/// The last generated canister ID; or `None` if this subnet has not
/// generated any canister IDs yet.
///
/// If present, must be within the first `CanisterIdRange` in
/// `canister_allocation_ranges` (and the latter may not be empty).
last_generated_canister_id: Option<CanisterId>,
/// The hash of the previous partial canonical state.
/// The initial state doesn't have any previous state.
pub prev_state_hash: Option<CryptoHashOfPartialState>,
/// The Consensus-determined time this batch was created.
/// NOTE: this time is monotonically increasing (and not strictly
/// increasing).
pub batch_time: Time,
pub network_topology: NetworkTopology,
pub own_subnet_id: SubnetId,
pub own_subnet_type: SubnetType,
pub own_subnet_features: SubnetFeatures,
/// DER-encoded public keys of the subnet's nodes.
pub node_public_keys: BTreeMap<NodeId, Vec<u8>>,
pub api_boundary_nodes: BTreeMap<NodeId, ApiBoundaryNodeEntry>,
/// "Subnet split in progress" marker: `Some(original_subnet_id)` if this
/// replicated state is in the process of being split from `original_subnet_id`;
/// `None` otherwise.
///
/// During a subnet split, `original_subnet_id` may be used to determine whether
/// this is subnet A' (when equal to `own_subnet_id`) or B (when different).
pub split_from: Option<SubnetId>,
/// Asynchronously handled subnet messages.
pub subnet_call_context_manager: SubnetCallContextManager,
/// The version of StateSync protocol that should be used to compute
/// manifest of this state.
pub state_sync_version: StateSyncVersion,
/// The version of certification procedure that should be used for this
/// state.
pub certification_version: CertificationVersion,
/// When canisters execute and modify their heap, we track the actual delta
/// they produced. From time to time, when consensus tells us that it is
/// fine to drop older states, the respective deltas are dropped. This field
/// tracks a deterministic estimate of the size of all the deltas that we
/// are currently maintaining.
///
/// The reason this field cannot track the actual delta precisely is because
/// consensus signals the StateManager asynchronously when it can drop older
/// states and hence the signal is handled in a non-deterministic fashion by
/// different nodes on the subnet.
///
/// We know that after MR has processed a batch with
/// "requires_full_state_hash" set, consensus will eventually deliver a
/// signal to the StateManager to drop states below that batches' height and
/// this signal will be sent at the latest before consensus sends another
/// batch with "requires_full_state_hash" set.
///
/// We also use this field to limit further execution in the scheduler when
/// the canisters have produced more delta than the subnet can handle given
/// the hardware specs of the subnet. The scheduler's configuration contains
/// relevant settings for the maximum delta capacity of the subnet.
///
/// Therefore, if we reset this field to 0 in MR when processing a batch
/// with "requires_full_state_hash" set after the canisters have executed
/// then the actual total for all the deltas that we are maintaining should
/// always be <= this field + (the maximum delta capacity of the subnet /
/// 2).
pub heap_delta_estimate: NumBytes,
pub subnet_metrics: SubnetMetrics,
/// The set of WASM modules we expect to be present in the [`Hypervisor`]'s
/// compilation cache. This allows us to deterministically decide when we
/// expect a compilation to be fast and ignore the compilation cost when
/// considering the round instruction limit.
///
/// Each time a canister is installed, its WASM is inserted and the set is
/// cleared at each checkpoint.
pub expected_compiled_wasms: BTreeSet<WasmHash>,
/// Responses to `BitcoinGetSuccessors` can be larger than the max inter-canister
/// response limit. To work around this limitation, large responses are paginated
/// and are stored here temporarily until they're fetched by the calling canister.
pub bitcoin_get_successors_follow_up_responses: BTreeMap<CanisterId, Vec<BlockBlob>>,
/// Metrics collecting blockmaker stats (block proposed and failures to propose a block)
/// by aggregating them and storing a running total over multiple days by node id and
/// timestamp. Observations of blockmaker stats are performed each time a batch is processed.
pub blockmaker_metrics_time_series: BlockmakerMetricsTimeSeries,
}
/// Full description of the IC network toplogy.
///
/// Contains [`Arc`] references, so it is only safe to serialize for read-only
/// use.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct NetworkTopology {
pub subnets: BTreeMap<SubnetId, SubnetTopology>,
#[serde(serialize_with = "ic_utils::serde_arc::serialize_arc")]
#[serde(deserialize_with = "ic_utils::serde_arc::deserialize_arc")]
pub routing_table: Arc<RoutingTable>,
#[serde(serialize_with = "ic_utils::serde_arc::serialize_arc")]
#[serde(deserialize_with = "ic_utils::serde_arc::deserialize_arc")]
pub canister_migrations: Arc<CanisterMigrations>,
pub nns_subnet_id: SubnetId,
/// Mapping from ECDSA key_id to a list of subnets which can sign with the
/// given key. Keys without any signing subnets are not included in the map.
pub ecdsa_signing_subnets: BTreeMap<EcdsaKeyId, Vec<SubnetId>>,
/// The ID of the canister to forward bitcoin testnet requests to.
pub bitcoin_testnet_canister_id: Option<CanisterId>,
/// The ID of the canister to forward bitcoin mainnet requests to.
pub bitcoin_mainnet_canister_id: Option<CanisterId>,
}
/// Full description of the API Boundary Node, which is saved in the metadata.
/// This entry is formed from two registry records - ApiBoundaryNodeRecord and NodeRecord.
/// If an ApiBoundaryNodeRecord exists, then a corresponding NodeRecord must exist.
/// The converse statement is not true.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ApiBoundaryNodeEntry {
/// Domain name, required field from NodeRecord
pub domain: String,
/// Ipv4, optional field from NodeRecord
pub ipv4_address: Option<String>,
/// Ipv6, required field from NodeRecord
pub ipv6_address: String,
pub pubkey: Option<Vec<u8>>,
}
impl Default for NetworkTopology {
fn default() -> Self {
Self {
subnets: Default::default(),
routing_table: Default::default(),
canister_migrations: Default::default(),
nns_subnet_id: SubnetId::new(PrincipalId::new_anonymous()),
ecdsa_signing_subnets: Default::default(),
bitcoin_testnet_canister_id: None,
bitcoin_mainnet_canister_id: None,
}
}
}
impl NetworkTopology {
/// Returns a list of subnets where the ecdsa feature is enabled.
pub fn ecdsa_signing_subnets(&self, key_id: &EcdsaKeyId) -> &[SubnetId] {
self.ecdsa_signing_subnets
.get(key_id)
.map(|ids| &ids[..])
.unwrap_or(&[])
}
/// Returns the size of the given subnet.
pub fn get_subnet_size(&self, subnet_id: &SubnetId) -> Option<usize> {
self.subnets
.get(subnet_id)
.map(|subnet_topology| subnet_topology.nodes.len())
}
}
impl From<&NetworkTopology> for pb_metadata::NetworkTopology {
fn from(item: &NetworkTopology) -> Self {
Self {
subnets: item
.subnets
.iter()
.map(|(subnet_id, subnet_topology)| pb_metadata::SubnetsEntry {
subnet_id: Some(subnet_id_into_protobuf(*subnet_id)),
subnet_topology: Some(subnet_topology.into()),
})
.collect(),
routing_table: Some(item.routing_table.as_ref().into()),
nns_subnet_id: Some(subnet_id_into_protobuf(item.nns_subnet_id)),
canister_migrations: Some(item.canister_migrations.as_ref().into()),
ecdsa_signing_subnets: item
.ecdsa_signing_subnets
.iter()
.map(|(key_id, subnet_ids)| {
let subnet_ids = subnet_ids
.iter()
.map(|id| subnet_id_into_protobuf(*id))
.collect();
pb_metadata::EcdsaKeyEntry {
key_id: Some(key_id.into()),
subnet_ids,
}
})
.collect(),
bitcoin_testnet_canister_ids: match item.bitcoin_testnet_canister_id {
Some(c) => vec![pb_types::CanisterId::from(c)],
None => vec![],
},
bitcoin_mainnet_canister_ids: match item.bitcoin_mainnet_canister_id {
Some(c) => vec![pb_types::CanisterId::from(c)],
None => vec![],
},
}
}
}
impl TryFrom<pb_metadata::NetworkTopology> for NetworkTopology {
type Error = ProxyDecodeError;
fn try_from(item: pb_metadata::NetworkTopology) -> Result<Self, Self::Error> {
let mut subnets = BTreeMap::new();
for entry in item.subnets {
subnets.insert(
subnet_id_try_from_protobuf(try_from_option_field(
entry.subnet_id,
"NetworkTopology::subnets::K",
)?)?,
try_from_option_field(entry.subnet_topology, "NetworkTopology::subnets::V")?,
);
}
let nns_subnet_id = subnet_id_try_from_protobuf(try_from_option_field(
item.nns_subnet_id,
"NetworkTopology::nns_subnet_id",
)?)?;
let mut ecdsa_signing_subnets = BTreeMap::new();
for entry in item.ecdsa_signing_subnets {
let mut subnet_ids = vec![];
for subnet_id in entry.subnet_ids {
subnet_ids.push(subnet_id_try_from_protobuf(subnet_id)?);
}
ecdsa_signing_subnets.insert(
try_from_option_field(entry.key_id, "EcdsaKeyEntry::key_id")?,
subnet_ids,
);
}
let bitcoin_testnet_canister_id = match item.bitcoin_testnet_canister_ids.first() {
Some(canister) => Some(CanisterId::try_from(canister.clone())?),
None => None,
};
let bitcoin_mainnet_canister_id = match item.bitcoin_mainnet_canister_ids.first() {
Some(canister) => Some(CanisterId::try_from(canister.clone())?),
None => None,
};
Ok(Self {
subnets,
routing_table: try_from_option_field(
item.routing_table,
"NetworkTopology::routing_table",
)
.map(Arc::new)?,
// `None` value needs to be allowed here because all the existing states don't have this field yet.
canister_migrations: item
.canister_migrations
.map(CanisterMigrations::try_from)
.transpose()?
.unwrap_or_default()
.into(),
nns_subnet_id,
ecdsa_signing_subnets,
bitcoin_testnet_canister_id,
bitcoin_mainnet_canister_id,
})
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SubnetTopology {
/// The public key of the subnet (a DER-encoded BLS key, see
/// https://sdk.dfinity.org/docs/interface-spec/index.html#certification)
pub public_key: Vec<u8>,
pub nodes: BTreeSet<NodeId>,
pub subnet_type: SubnetType,
pub subnet_features: SubnetFeatures,
/// ECDSA keys held by this subnet. Just because a subnet holds an ECDSA key
/// doesn't mean the subnet has been enabled to sign with that key. This
/// will happen when a key is shared with a second subnet which holds it as
/// a backup. An additional NNS proposal will be needed to allow the subnet
/// holding the key as backup to actually produce signatures.
pub ecdsa_keys_held: BTreeSet<EcdsaKeyId>,
}
impl From<&SubnetTopology> for pb_metadata::SubnetTopology {
fn from(item: &SubnetTopology) -> Self {
Self {
public_key: item.public_key.clone(),
nodes: item
.nodes
.iter()
.map(|node_id| pb_metadata::SubnetTopologyEntry {
node_id: Some(node_id_into_protobuf(*node_id)),
})
.collect(),
subnet_type: i32::from(item.subnet_type),
subnet_features: Some(pb_subnet::SubnetFeatures::from(item.subnet_features)),
ecdsa_keys_held: item.ecdsa_keys_held.iter().map(|k| k.into()).collect(),
}
}
}
impl TryFrom<pb_metadata::SubnetTopology> for SubnetTopology {
type Error = ProxyDecodeError;
fn try_from(item: pb_metadata::SubnetTopology) -> Result<Self, Self::Error> {
let mut nodes = BTreeSet::<NodeId>::new();
for entry in item.nodes {
nodes.insert(node_id_try_from_option(entry.node_id)?);
}
let mut ecdsa_keys_held = BTreeSet::new();
for key in item.ecdsa_keys_held {
ecdsa_keys_held.insert(EcdsaKeyId::try_from(key)?);
}
Ok(Self {
public_key: item.public_key,
nodes,
// It is fine to use an arbitrary value here. We always reset the
// field before we actually use it. We pick the value of least
// privilege just to be sure.
subnet_type: SubnetType::try_from(item.subnet_type).unwrap_or(SubnetType::Application),
subnet_features: item
.subnet_features
.map(SubnetFeatures::from)
.unwrap_or_default(),
ecdsa_keys_held,
})
}
}
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct SubnetMetrics {
pub consumed_cycles_by_deleted_canisters: NominalCycles,
pub consumed_cycles_http_outcalls: NominalCycles,
pub consumed_cycles_ecdsa_outcalls: NominalCycles,
consumed_cycles_by_use_case: BTreeMap<CyclesUseCase, NominalCycles>,
pub ecdsa_signature_agreements: u64,
/// The number of canisters that exist on this subnet.
pub num_canisters: u64,
/// The total size of the state taken by canisters on this subnet in bytes.
pub canister_state_bytes: NumBytes,
/// The total number of transactions processed on this subnet.
///
/// Transactions here refer to all messages processed in replicated mode.
pub update_transactions_total: u64,
}
impl SubnetMetrics {
pub fn observe_consumed_cycles_with_use_case(
&mut self,
use_case: CyclesUseCase,
cycles: NominalCycles,
) {
*self
.consumed_cycles_by_use_case
.entry(use_case)
.or_insert_with(|| NominalCycles::from(0)) += cycles;
}
pub fn get_consumed_cycles_by_use_case(&self) -> &BTreeMap<CyclesUseCase, NominalCycles> {
&self.consumed_cycles_by_use_case
}
pub fn consumed_cycles_total(&self) -> NominalCycles {
let mut total = NominalCycles::from(0);
total += self.consumed_cycles_by_deleted_canisters;
total += self.consumed_cycles_http_outcalls;
total += self.consumed_cycles_ecdsa_outcalls;
for (use_case, cycles) in self.consumed_cycles_by_use_case.iter() {
match use_case {
// For ecdsa outcalls, http outcalls and deleted canisters, skip
// updating the total using the use case specific metric as the
// update above should be sufficient (the old metric is a superset).
CyclesUseCase::ECDSAOutcalls
| CyclesUseCase::HTTPOutcalls
| CyclesUseCase::DeletedCanisters => {}
// Non consumed cycles should not be counted towards the total consumed.
CyclesUseCase::NonConsumed => {}
// For the remaining use cases simply add the values to the total.
CyclesUseCase::Memory
| CyclesUseCase::ComputeAllocation
| CyclesUseCase::IngressInduction
| CyclesUseCase::Instructions
| CyclesUseCase::RequestAndResponseTransmission
| CyclesUseCase::Uninstall
| CyclesUseCase::CanisterCreation
| CyclesUseCase::BurnedCycles => total += *cycles,
}
}
total
}
}
impl From<&SubnetMetrics> for pb_metadata::SubnetMetrics {
fn from(item: &SubnetMetrics) -> Self {
Self {
consumed_cycles_by_deleted_canisters: Some(
(&item.consumed_cycles_by_deleted_canisters).into(),
),
consumed_cycles_http_outcalls: Some((&item.consumed_cycles_http_outcalls).into()),
consumed_cycles_ecdsa_outcalls: Some((&item.consumed_cycles_ecdsa_outcalls).into()),
ecdsa_signature_agreements: Some(item.ecdsa_signature_agreements),
consumed_cycles_by_use_case: item
.consumed_cycles_by_use_case
.clone()
.into_iter()
.map(|entry| ConsumedCyclesByUseCase {
use_case: entry.0.into(),
cycles: Some((&entry.1).into()),
})
.collect(),
num_canisters: Some(item.num_canisters),
canister_state_bytes: Some(item.canister_state_bytes.get()),
update_transactions_total: Some(item.update_transactions_total),
}
}
}
impl TryFrom<pb_metadata::SubnetMetrics> for SubnetMetrics {
type Error = ProxyDecodeError;
fn try_from(item: pb_metadata::SubnetMetrics) -> Result<Self, Self::Error> {
Ok(Self {
consumed_cycles_by_deleted_canisters: try_from_option_field(
item.consumed_cycles_by_deleted_canisters,
"SubnetMetrics::consumed_cycles_by_deleted_canisters",
)?,
consumed_cycles_http_outcalls: try_from_option_field(
item.consumed_cycles_http_outcalls,
"SubnetMetrics::consumed_cycles_http_outcalls",
)
.unwrap_or_else(|_| NominalCycles::from(0_u128)),
consumed_cycles_ecdsa_outcalls: try_from_option_field(
item.consumed_cycles_ecdsa_outcalls,
"SubnetMetrics::consumed_cycles_ecdsa_outcalls",
)
.unwrap_or_else(|_| NominalCycles::from(0_u128)),
ecdsa_signature_agreements: item.ecdsa_signature_agreements.unwrap_or_default(),
consumed_cycles_by_use_case: item
.consumed_cycles_by_use_case
.into_iter()
.map(|ConsumedCyclesByUseCase { use_case, cycles }| {
(
CyclesUseCase::from(use_case),
NominalCycles::try_from(cycles.unwrap_or_default()).unwrap_or_default(),
)
})
.collect(),
num_canisters: try_from_option_field(
item.num_canisters,
"SubnetMetrics::num_canisters",
)?,
canister_state_bytes: try_from_option_field(
item.canister_state_bytes,
"SubnetMetrics::canister_state_bytes",
)?,
update_transactions_total: try_from_option_field(
item.update_transactions_total,
"SubnetMetrics::update_transactions_total",
)?,
})
}
}
impl From<&SystemMetadata> for pb_metadata::SystemMetadata {
fn from(item: &SystemMetadata) -> Self {
// We do not store the subnet type when we serialize SystemMetadata. We rely on
// `load_checkpoint()` to properly set this value.
Self {
own_subnet_id: Some(subnet_id_into_protobuf(item.own_subnet_id)),
canister_allocation_ranges: Some(item.canister_allocation_ranges.clone().into()),
last_generated_canister_id: item.last_generated_canister_id.map(Into::into),
prev_state_hash: item
.prev_state_hash
.clone()
.map(|prev_hash| prev_hash.get().0),
batch_time_nanos: item.batch_time.as_nanos_since_unix_epoch(),
streams: item
.streams
.iter()
.map(|(subnet_id, stream)| pb_queues::StreamEntry {
subnet_id: Some(subnet_id_into_protobuf(*subnet_id)),
subnet_stream: Some(stream.into()),
})
.collect(),
network_topology: Some((&item.network_topology).into()),
subnet_call_context_manager: Some((&item.subnet_call_context_manager).into()),
state_sync_version: item.state_sync_version as u32,
certification_version: item.certification_version as u32,
heap_delta_estimate: item.heap_delta_estimate.get(),
own_subnet_features: Some(item.own_subnet_features.into()),
subnet_metrics: Some((&item.subnet_metrics).into()),
bitcoin_get_successors_follow_up_responses: item
.bitcoin_get_successors_follow_up_responses
.clone()
.into_iter()
.map(
|(sender, payloads)| pb_metadata::BitcoinGetSuccessorsFollowUpResponses {
sender: Some(sender.into()),
payloads,
},
)
.collect(),
node_public_keys: item
.node_public_keys
.iter()
.map(|(node_id, public_key)| pb_metadata::NodePublicKeyEntry {
node_id: Some(node_id_into_protobuf(*node_id)),
public_key: public_key.clone(),
})
.collect(),
api_boundary_nodes: item
.api_boundary_nodes
.iter()
.map(
|(node_id, api_boundary_node_entry)| pb_metadata::ApiBoundaryNodeEntry {
node_id: Some(node_id_into_protobuf(*node_id)),
domain: api_boundary_node_entry.domain.clone(),
ipv4_address: api_boundary_node_entry.ipv4_address.clone(),
ipv6_address: api_boundary_node_entry.ipv6_address.clone(),
pubkey: api_boundary_node_entry.pubkey.clone(),
},
)
.collect(),
blockmaker_metrics_time_series: Some((&item.blockmaker_metrics_time_series).into()),
}
}
}
/// Decodes a `SystemMetadata` proto. The metrics are provided as a side-channel
/// for recording errors without being forced to return `Err(_)`.
impl TryFrom<(pb_metadata::SystemMetadata, &dyn CheckpointLoadingMetrics)> for SystemMetadata {
type Error = ProxyDecodeError;
fn try_from(
(item, metrics): (pb_metadata::SystemMetadata, &dyn CheckpointLoadingMetrics),
) -> Result<Self, Self::Error> {
let mut streams = BTreeMap::<SubnetId, Stream>::new();
for entry in item.streams {
streams.insert(
subnet_id_try_from_protobuf(try_from_option_field(
entry.subnet_id,
"SystemMetadata::streams::K",
)?)?,
try_from_option_field(entry.subnet_stream, "SystemMetadata::streams::V")?,
);
}
let canister_allocation_ranges: CanisterIdRanges = match item.canister_allocation_ranges {
Some(canister_allocation_ranges) => canister_allocation_ranges.try_into()?,
None => Default::default(),
};
let last_generated_canister_id = item
.last_generated_canister_id
.map(TryInto::try_into)
.transpose()?;
// Validate that `last_generated_canister_id` (if not `None`) is within the
// first `canister_allocation_ranges` range.
if let Some(last_generated_canister_id) = last_generated_canister_id {
match canister_allocation_ranges.iter().next() {
Some(first_allocation_range)
if first_allocation_range.contains(&last_generated_canister_id) => {}
_ => return Err(ProxyDecodeError::Other(format!(
"SystemMetadata::last_generated_canister_id ({}) not in the first SystemMetadata::canister_allocation_ranges range ({:?})",
last_generated_canister_id, canister_allocation_ranges
))),
}
}
let mut bitcoin_get_successors_follow_up_responses = BTreeMap::new();
for response in item.bitcoin_get_successors_follow_up_responses {
let sender_pb: pb_types::CanisterId = try_from_option_field(
response.sender,
"BitcoinGetSuccessorsFollowUpResponses::sender",
)?;
let sender = CanisterId::try_from(sender_pb)?;
bitcoin_get_successors_follow_up_responses.insert(sender, response.payloads);
}
let batch_time = Time::from_nanos_since_unix_epoch(item.batch_time_nanos);
let mut node_public_keys = BTreeMap::<NodeId, Vec<u8>>::new();
for entry in item.node_public_keys {
node_public_keys.insert(node_id_try_from_option(entry.node_id)?, entry.public_key);
}
let mut api_boundary_nodes = BTreeMap::<NodeId, ApiBoundaryNodeEntry>::new();
for entry in item.api_boundary_nodes {
api_boundary_nodes.insert(
node_id_try_from_option(entry.node_id)?,
ApiBoundaryNodeEntry {
domain: entry.domain,
ipv4_address: entry.ipv4_address,
ipv6_address: entry.ipv6_address,
pubkey: entry.pubkey,
},
);
}
Ok(Self {
own_subnet_id: subnet_id_try_from_protobuf(try_from_option_field(
item.own_subnet_id,
"SystemMetadata::own_subnet_id",
)?)?,
// WARNING! Setting to the default value which can be incorrect. We do not store the
// actual value when we serialize SystemMetadata. We rely on `load_checkpoint()` to
// properly set this value.
own_subnet_type: SubnetType::default(),
own_subnet_features: item.own_subnet_features.unwrap_or_default().into(),
node_public_keys,
api_boundary_nodes,
// Note: `load_checkpoint()` will set this to the contents of `split_marker.pbuf`,
// when present.
split_from: None,
canister_allocation_ranges,
last_generated_canister_id,
prev_state_hash: item.prev_state_hash.map(|b| CryptoHash(b).into()),
batch_time,
// Ingress history is persisted separately. We rely on `load_checkpoint()` to
// properly set this value.
ingress_history: Default::default(),
streams: Arc::new(Streams {
responses_size_bytes: Streams::calculate_stats(&streams),
streams,
}),
network_topology: try_from_option_field(
item.network_topology,
"SystemMetadata::network_topology",
)?,
state_sync_version: item
.state_sync_version
.try_into()
.map_err(|_| ProxyDecodeError::UnknownStateSyncVersion(item.state_sync_version))?,
certification_version: item.certification_version.try_into().map_err(|_| {
ProxyDecodeError::UnknownCertificationVersion(item.certification_version)
})?,
subnet_call_context_manager: match item.subnet_call_context_manager {
Some(manager) => SubnetCallContextManager::try_from((batch_time, manager))?,
None => Default::default(),
},
heap_delta_estimate: NumBytes::from(item.heap_delta_estimate),
subnet_metrics: match item.subnet_metrics {
Some(subnet_metrics) => subnet_metrics.try_into()?,
None => SubnetMetrics::default(),
},
expected_compiled_wasms: BTreeSet::new(),
bitcoin_get_successors_follow_up_responses,
blockmaker_metrics_time_series: match item.blockmaker_metrics_time_series {
Some(blockmaker_metrics) => (blockmaker_metrics, metrics).try_into()?,
None => BlockmakerMetricsTimeSeries::default(),
},
})
}
}
impl SystemMetadata {
/// Creates a new empty system metadata state.
pub fn new(own_subnet_id: SubnetId, own_subnet_type: SubnetType) -> Self {
Self {
own_subnet_id,
own_subnet_type,
ingress_history: Default::default(),
streams: Default::default(),
canister_allocation_ranges: Default::default(),
last_generated_canister_id: None,
batch_time: UNIX_EPOCH,
network_topology: Default::default(),
subnet_call_context_manager: Default::default(),
own_subnet_features: SubnetFeatures::default(),
node_public_keys: Default::default(),
api_boundary_nodes: Default::default(),
split_from: None,
// StateManager populates proper values of these fields before
// committing each state.
prev_state_hash: Default::default(),
state_sync_version: CURRENT_STATE_SYNC_VERSION,
// NB. State manager relies on the root hash of the hash tree
// corresponding to the initial state to be a constant. Thus we fix
// the certification version that we use for the initial state. If
// we used CURRENT_CERTIFICATION_VERSION here, the state hash would
// NOT be guaranteed to be constant, potentially leading to
// hard-to-track bugs in state manager.
certification_version: CertificationVersion::V0,
heap_delta_estimate: NumBytes::from(0),
subnet_metrics: Default::default(),
expected_compiled_wasms: BTreeSet::new(),
bitcoin_get_successors_follow_up_responses: BTreeMap::default(),
blockmaker_metrics_time_series: BlockmakerMetricsTimeSeries::default(),
}
}
pub fn time(&self) -> Time {
self.batch_time
}
/// Returns a reference to the streams.
pub fn streams(&self) -> &Streams {
&self.streams
}
/// One-off initialization: populate `canister_allocation_ranges` with the only
/// `[N * 2^20, (N+1) * 2^20 - 1]` range fully hosted by the subnet as per the
/// routing table; and initialize `last_generated_canister_id` based on
/// `generated_id_counter`.
///
/// This is done under the assumption that the registry always assigns exactly
/// 2^20 canister IDs to every newly created subnet (and at this point in time
/// no canisters have yet been migrated).
///
/// Canister ID allocation range assignment will be made explicit in a follow-up
/// change.
///
/// Returns `Ok` if `canister_allocation_ranges` is not empty (whether it was
/// populated by this call or not); `Err` if empty (and the subnet is unable
/// to generate new canister IDs).
pub fn init_allocation_ranges_if_empty(&mut self) -> Result<(), String> {
if !self.canister_allocation_ranges.is_empty() {
return Ok(());
}
let routing_table_ranges = self
.network_topology
.routing_table
.ranges(self.own_subnet_id);
for range in routing_table_ranges.iter().rev() {
let start = canister_id_into_u64(range.start);
let end = canister_id_into_u64(range.end);
if start % CANISTER_IDS_PER_SUBNET == 0 && end == start + CANISTER_IDS_PER_SUBNET - 1 {
// Found the `[N * 2^20, (N+1) * 2^20 - 1]` (sub)range, use it as allocation
// range.
//
// Unwrapping is safe because the only reason why we would fail to convert is if
// we provided set of ranges that was not well formed. This is not the case
// here, as we are creating a `CanisterIdRanges` out of one non-empty range.
self.canister_allocation_ranges = vec![*range].try_into().unwrap();
break;
}
}
if self.canister_allocation_ranges.is_empty() {
return Err("No range of length CANISTER_IDS_PER_SUBNET in routing table".into());
}
Ok(())
}
/// Generates a new canister ID.
///
/// If a canister ID from a second canister allocation range is generated, the
/// first range is dropped. The last canister allocation range is never dropped.
///
/// Returns `Err` iff no more canister IDs can be generated.
pub fn generate_new_canister_id(&mut self) -> Result<CanisterId, String> {
// Start off with
// (canister_allocation_ranges
// ∩ routing_table.ranges(own_subnet_id))
// \ canister_migrations.ranges()
let own_subnet_ranges = self
.network_topology
.routing_table
.ranges(self.own_subnet_id);
let canister_allocation_ranges = intersection(
self.canister_allocation_ranges.iter(),
own_subnet_ranges.iter(),
)
.map_err(|err| {
format!(
"intersection({:?}, {:?}) is not well formed: {:?}",
self.canister_allocation_ranges, own_subnet_ranges, err
)
})?;
let canister_allocation_ranges = difference(
canister_allocation_ranges.iter(),
self.network_topology.canister_migrations.ranges(),
)
.map_err(|err| {
format!(
"difference({:?}, {:?}) is not well formed: {:?}",
canister_allocation_ranges, self.network_topology.canister_migrations, err
)
})?;
let res = canister_allocation_ranges.generate_canister_id(self.last_generated_canister_id);
if let Some(res) = &res {
self.last_generated_canister_id = Some(*res);
while self.canister_allocation_ranges.len() > 1
&& !self
.canister_allocation_ranges
.iter()
.next()
.unwrap()
.contains(res)
{
// Drop the first canister allocation range iff consumed and more allocation
// ranges are available.
self.canister_allocation_ranges.drop_first();
}
}
res.ok_or_else(|| "Canister ID allocation was consumed".into())
}
/// Returns the number of canister IDs that can still be generated.
pub fn available_canister_ids(&self) -> u64 {
let generated_canister_ids = match (
self.canister_allocation_ranges.start(),
self.last_generated_canister_id,
) {
(Some(start), Some(last)) => {
canister_id_into_u64(last) + 1 - canister_id_into_u64(start)
}
_ => 0,
};
self.canister_allocation_ranges.total_count() as u64 - generated_canister_ids
}
/// Splits the `MetadataState` as part of subnet splitting phase 1:
/// * for the split subnet (B), produces a new `MetadataState`, with the given
/// batch time (if `Some`) or the original subnet's batch time (if `None`);
/// * for the subnet that retains the original subnet's ID (A'), returns it
/// unmodified (apart from setting the split marker).
///
/// A subnet split starts with a subnet A and results in two subnets, A' and B.
/// For the sake of clarity, comments refer to the two resulting subnets as
/// *subnet A'* and *subnet B*. And to the original subnet as *subnet A*.
/// Because subnet A' retains the subnet ID of subnet A, it is identified by
/// having `new_subnet_id == self.own_subnet_id`. Conversely, subnet B has
/// `new_subnet_id != self.own_subnet_id`.
///
/// In this first phase, the ingress history is left untouched on both subnets,
/// in order to make it trivial to verify that no tampering has occurred. A
/// split marker is added to both subnets, containing the original subnet ID.
///
/// In phase 2 (see [`Self::after_split()`]) the ingress history is pruned and
/// the split marker is reset.
pub fn split(
mut self,
subnet_id: SubnetId,
new_subnet_batch_time: Option<Time>,
) -> Result<Self, String> {
assert_eq!(0, self.heap_delta_estimate.get());
assert!(self.expected_compiled_wasms.is_empty());
// No-op for subnet A'.
if self.own_subnet_id == subnet_id {
if new_subnet_batch_time.is_some() {
return Err("Cannot apply a new batch time to the original subnet".into());
}
// Set the split marker to the original subnet ID.
self.split_from = Some(self.own_subnet_id);
return Ok(self);
}
// This is subnet B: use `subnet_id` as its subnet ID.
let mut res = SystemMetadata::new(subnet_id, self.own_subnet_type);
// Set the split marker to the original subnet ID (that of subnet A).
res.split_from = Some(self.own_subnet_id);
// Preserve ingress history.
res.ingress_history = self.ingress_history;
// Ensure monotonic time for migrated canisters: apply `new_subnet_batch_time`
// if specified and not smaller than `self.batch_time`; else, default to
// `self.batch_time`.
res.batch_time = if let Some(batch_time) = new_subnet_batch_time {
if batch_time < self.batch_time {
return Err(format!(
"Provided batch_time ({}) is before original subnet batch time ({})",
batch_time, self.batch_time
));
}
batch_time
} else {
self.batch_time
};
// All other fields have been reset to default.
Ok(res)
}
/// Adjusts the `MetadataState` as part of the second phase of subnet splitting,
/// during the new subnets' startup.
///
/// A subnet split starts with a subnet A and results in two subnets, A' and B,
/// with canisters split among the two subnets according to the routing table.
/// Because subnet A' retains the subnet ID of subnet A, it is identified by
/// having `self.split_from == Some(self.own_subnet_id)`. Conversely, subnet B
/// has `self.split_from != Some(self.own_subnet_id)`.
///
/// In the first phase (see [`Self::split()`]), the ingress history was left
/// untouched on both subnets, in order to make it trivial to verify that no
/// tampering had occurred. Streams, subnet call contexts and metrics and all
/// other metadata were preserved on subnet A' and set to default on subnet B.
///
/// In this second phase, `ingress_history` is pruned, retaining only messages
/// in terminal states and messages addressed to local canisters. Additionally,
/// on subnet A' we reject all management canister calls whose execution is in
/// progress on one of the canisters migrated to subnet B (hence the
/// `subnet_queues` argument); and silently discard the corresponding tasks and
/// roll back `Stopping` states on all subnet B canisters.
///
/// Notes:
/// * `prev_state_hash` has just been set by `take_tip()` to the checkpoint
/// hash (checked against the hash in the CUP). It must be preserved.
/// * `own_subnet_type` has just been set during `load_checkpoint()`, based on
/// the registry subnet record of the subnet that this node is part of.
/// * `batch_time`, `network_topology` and `own_subnet_features` will be set
/// by Message Routing before the start of the next round.
/// * `state_sync_version` and `certification_version` will be set by
/// `commit_and_certify()` at the end of the round; and not used before.
/// * `heap_delta_estimate` and `expected_compiled_wasms` are expected to be
/// empty/zero.
pub(crate) fn after_split<F>(
&mut self,