-
Notifications
You must be signed in to change notification settings - Fork 85
/
state_machine.rs
1267 lines (1127 loc) · 42.5 KB
/
state_machine.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
//! This module contains a pure implementation of the certified assets state machine.
// NB. This module should not depend on ic_cdk, it contains only pure state transition functions.
// All the environment (time, certificates, etc.) is passed to the state transition functions
// as formal arguments. This approach makes it very easy to test the state machine.
use crate::{
asset_certification::{
types::{
certification::{
AssetKey, AssetPath, CertificateExpression, HashTreePath, NestedTreeKey,
RequestHash, ResponseHash, WitnessResult,
},
http::{
build_ic_certificate_expression_from_headers_and_encoding,
build_ic_certificate_expression_header, response_hash, CallbackFunc, HttpRequest,
HttpResponse, StreamingCallbackHttpResponse, StreamingCallbackToken, FALLBACK_FILE,
},
rc_bytes::RcBytes,
},
CertifiedResponses,
},
evidence::{EvidenceComputation, EvidenceComputation::Computed},
types::*,
url_decode::url_decode,
};
use candid::{CandidType, Deserialize, Int, Nat, Principal};
use ic_certification::{AsHashTree, Hash};
use ic_representation_independent_hash::Value;
use num_traits::ToPrimitive;
use serde::Serialize;
use serde_bytes::ByteBuf;
use sha2::Digest;
use std::collections::{BTreeSet, HashMap};
use std::convert::TryInto;
/// The amount of time a batch is kept alive. Modifying the batch
/// delays the expiry further.
pub const BATCH_EXPIRY_NANOS: u64 = 300_000_000_000;
/// The order in which we pick encodings for certification.
const ENCODING_CERTIFICATION_ORDER: &[&str] = &["identity", "gzip", "compress", "deflate", "br"];
// Order of encodings is relevant for v1. Follow ENCODING_CERTIFICATION_ORDER,
// then follow the order of existing encodings.
// For v2, it is important to certify all encodings, therefore all encodings are added to the list.
pub fn encoding_certification_order<'a>(
actual_encodings: impl Iterator<Item = &'a String>,
) -> Vec<String> {
let mut encoding_order: Vec<String> = ENCODING_CERTIFICATION_ORDER
.iter()
.map(|enc| enc.to_string())
.collect();
encoding_order.append(
&mut actual_encodings
.filter(|encoding| !ENCODING_CERTIFICATION_ORDER.contains(&encoding.as_str()))
.map(|s| s.into())
.collect(),
);
encoding_order
}
/// Default aliasing behavior.
const DEFAULT_ALIAS_ENABLED: bool = true;
const STATUS_CODES_TO_CERTIFY: [u16; 2] = [200, 304];
const DEFAULT_MAX_COMPUTE_EVIDENCE_ITERATIONS: u16 = 20;
type Timestamp = Int;
#[derive(Default, Clone, Debug, CandidType, Deserialize)]
pub struct AssetEncoding {
pub modified: Timestamp,
pub content_chunks: Vec<RcBytes>,
pub total_length: usize,
/// Valid as-is for v2.
/// For v1, also make sure that encoding name == asset.most_important_encoding_v1()
pub certified: bool,
pub sha256: [u8; 32],
pub certificate_expression: Option<CertificateExpression>,
pub response_hashes: Option<HashMap<u16, [u8; 32]>>,
}
impl AssetEncoding {
fn asset_hash_path_v2(&self, path: &AssetPath, status_code: u16) -> Option<HashTreePath> {
self.certificate_expression.as_ref().and_then(|ce| {
self.response_hashes.as_ref().and_then(|hashes| {
hashes.get(&status_code).map(|response_hash| {
path.hash_tree_path(ce, &RequestHash::default(), response_hash.into())
})
})
})
}
fn not_found_hash_path(&self) -> Option<HashTreePath> {
self.certificate_expression.as_ref().and_then(|ce| {
self.response_hashes
.as_ref()
.and_then(|hashes| hashes.get(&200))
.map(|response_hash| {
HashTreePath::from(Vec::<NestedTreeKey>::from([
"http_expr".into(),
"<*>".into(), // 404 not found wildcard segment
ce.expression_hash.as_slice().into(),
"".into(), // no request certification - use empty node
response_hash.as_slice().into(),
]))
})
})
}
fn compute_response_hashes(
&self,
headers: &Option<HashMap<String, String>>,
max_age: &Option<u64>,
content_type: &str,
encoding_name: &str,
) -> HashMap<u16, [u8; 32]> {
// Collect all user-defined headers
let base_headers: Vec<(String, Value)> = build_headers(
headers.as_ref().map(|h| h.iter()),
max_age,
content_type,
encoding_name,
self.certificate_expression.as_ref(),
)
.into_iter()
.map(|(k, v)| (k, Value::String(v)))
.collect();
// HTTP 200
let ResponseHash(response_hash_200) = response_hash(&base_headers, 200, &self.sha256);
// HTTP 304
let empty_body_hash: [u8; 32] = sha2::Sha256::digest([]).into();
let ResponseHash(response_hash_304) = response_hash(&base_headers, 304, &empty_body_hash);
let mut response_hashes = HashMap::new();
response_hashes.insert(200, response_hash_200);
response_hashes.insert(304, response_hash_304);
debug_assert!(STATUS_CODES_TO_CERTIFY
.iter()
.all(|code| response_hashes.contains_key(code)));
response_hashes
}
}
#[derive(Default, Clone, Debug, CandidType, Deserialize)]
pub struct Asset {
pub content_type: String,
pub encodings: HashMap<String, AssetEncoding>,
pub max_age: Option<u64>,
pub headers: Option<HashMap<String, String>>,
pub is_aliased: Option<bool>,
pub allow_raw_access: Option<bool>,
}
#[derive(Clone, Debug, CandidType, Deserialize)]
pub struct EncodedAsset {
pub content: RcBytes,
pub content_type: String,
pub content_encoding: String,
pub total_length: Nat,
pub sha256: Option<ByteBuf>,
}
#[derive(Clone, Debug, CandidType, Deserialize)]
pub struct AssetDetails {
pub key: String,
pub content_type: String,
pub encodings: Vec<AssetEncodingDetails>,
}
#[derive(Clone, Debug, CandidType, Deserialize)]
pub struct AssetEncodingDetails {
pub content_encoding: String,
pub sha256: Option<ByteBuf>,
pub length: Nat,
pub modified: Timestamp,
}
#[derive(Clone, Debug, CandidType, Deserialize)]
pub struct CertifiedTree {
pub certificate: Vec<u8>,
pub tree: Vec<u8>,
}
pub struct Chunk {
pub batch_id: BatchId,
pub content: RcBytes,
}
pub struct Batch {
pub expires_at: Timestamp,
pub commit_batch_arguments: Option<CommitBatchArguments>,
pub evidence_computation: Option<EvidenceComputation>,
pub chunk_content_total_size: usize,
}
#[derive(Clone, Debug, Default, CandidType, Deserialize)]
pub struct Configuration {
pub max_batches: Option<u64>,
pub max_chunks: Option<u64>,
pub max_bytes: Option<u64>,
}
#[derive(Default)]
pub struct State {
assets: HashMap<AssetKey, Asset>,
configuration: Configuration,
chunks: HashMap<ChunkId, Chunk>,
next_chunk_id: ChunkId,
batches: HashMap<BatchId, Batch>,
next_batch_id: BatchId,
// permissions
commit_principals: BTreeSet<Principal>,
prepare_principals: BTreeSet<Principal>,
manage_permissions_principals: BTreeSet<Principal>,
asset_hashes: CertifiedResponses,
}
#[derive(Clone, Debug, CandidType, Deserialize)]
pub struct StableStatePermissions {
commit: BTreeSet<Principal>,
prepare: BTreeSet<Principal>,
manage_permissions: BTreeSet<Principal>,
}
#[derive(Clone, Debug, CandidType, Deserialize)]
pub struct StableState {
authorized: Vec<Principal>, // ignored if permissions is Some(_)
permissions: Option<StableStatePermissions>,
stable_assets: HashMap<String, Asset>,
next_batch_id: Option<BatchId>,
configuration: Option<Configuration>,
}
impl Asset {
fn allow_raw_access(&self) -> bool {
self.allow_raw_access.unwrap_or(true)
}
fn update_ic_certificate_expressions(&mut self) {
// gather all headers
let mut headers: Vec<(String, Value)> = vec![];
if self.max_age.is_some() {
headers.push(("cache-control".to_string(), Value::String("".to_string())));
}
if let Some(custom_headers) = &self.headers {
for h in custom_headers.iter() {
headers.push((h.0.into(), Value::String(h.1.into())));
}
}
// update
for (enc_name, encoding) in self.encodings.iter_mut() {
encoding.certificate_expression = Some(
build_ic_certificate_expression_from_headers_and_encoding(&headers, Some(enc_name)),
);
}
}
pub fn get_headers_for_asset(
&self,
encoding_name: &str,
cert_version: u16,
) -> HashMap<String, String> {
let ce = if cert_version != 1 {
self.encodings
.get(encoding_name)
.and_then(|e| e.certificate_expression.as_ref())
} else {
None
};
build_headers(
self.headers.as_ref().map(|h| h.iter()),
&self.max_age,
&self.content_type,
encoding_name.to_owned(),
ce,
)
}
// certification v1 only certifies the most important encoding
pub fn most_important_encoding_v1(&self) -> String {
for enc in encoding_certification_order(self.encodings.keys()).into_iter() {
if self.encodings.contains_key(&enc) {
return enc;
}
}
"no encoding found".to_string()
}
}
impl State {
fn get_asset(&self, key: &AssetKey) -> Result<&Asset, String> {
self.assets
.get(key)
.or_else(|| {
let aliased = aliases_of(key)
.into_iter()
.find_map(|alias_key| self.assets.get(&alias_key));
if let Some(asset) = aliased {
if asset.is_aliased.unwrap_or(DEFAULT_ALIAS_ENABLED) {
aliased
} else {
None
}
} else {
None
}
})
.ok_or_else(|| "asset not found".to_string())
}
pub fn set_permissions(
&mut self,
SetPermissions {
prepare,
commit,
manage_permissions,
}: SetPermissions,
) {
*self.get_mut_permission_list(&Permission::Prepare) = prepare.into_iter().collect();
*self.get_mut_permission_list(&Permission::Commit) = commit.into_iter().collect();
*self.get_mut_permission_list(&Permission::ManagePermissions) =
manage_permissions.into_iter().collect();
}
pub fn grant_permission(&mut self, principal: Principal, permission: &Permission) {
let permitted = self.get_mut_permission_list(permission);
permitted.insert(principal);
}
pub fn revoke_permission(&mut self, principal: Principal, permission: &Permission) {
let permitted = self.get_mut_permission_list(permission);
permitted.remove(&principal);
}
pub fn list_permitted(&self, permission: &Permission) -> &BTreeSet<Principal> {
self.get_permission_list(permission)
}
pub fn take_ownership(&mut self, controller: Principal) {
self.commit_principals.clear();
self.prepare_principals.clear();
self.manage_permissions_principals.clear();
self.commit_principals.insert(controller);
}
pub fn root_hash(&self) -> Hash {
self.asset_hashes.root_hash()
}
pub fn create_asset(&mut self, arg: CreateAssetArguments) -> Result<(), String> {
if self.assets.contains_key(&arg.key) {
return Err("asset already exists".to_string());
}
self.assets.insert(
arg.key,
Asset {
content_type: arg.content_type,
encodings: HashMap::new(),
max_age: arg.max_age,
headers: arg.headers,
is_aliased: arg.enable_aliasing,
allow_raw_access: arg.allow_raw_access,
},
);
Ok(())
}
pub fn set_asset_content(
&mut self,
arg: SetAssetContentArguments,
now: u64,
) -> Result<(), String> {
if arg.chunk_ids.is_empty() {
return Err("encoding must have at least one chunk".to_string());
}
let dependent_keys = self.dependent_keys(&arg.key);
let asset = self
.assets
.get_mut(&arg.key)
.ok_or_else(|| "asset not found".to_string())?;
let now = Int::from(now);
let mut content_chunks = vec![];
for chunk_id in arg.chunk_ids.iter() {
let chunk = self.chunks.remove(chunk_id).expect("chunk not found");
content_chunks.push(chunk.content);
}
let sha256: [u8; 32] = match arg.sha256 {
Some(bytes) => bytes
.into_vec()
.try_into()
.map_err(|_| "invalid SHA-256".to_string())?,
None => {
let mut hasher = sha2::Sha256::new();
for chunk in content_chunks.iter() {
hasher.update(chunk);
}
hasher.finalize().into()
}
};
let total_length: usize = content_chunks.iter().map(|c| c.len()).sum();
let enc = AssetEncoding {
modified: now,
content_chunks,
certified: false,
total_length,
sha256,
certificate_expression: None, // set by on_asset_change
response_hashes: None, // set by on_asset_change
};
asset.encodings.insert(arg.content_encoding, enc);
on_asset_change(&mut self.asset_hashes, &arg.key, asset, dependent_keys);
Ok(())
}
pub fn unset_asset_content(&mut self, arg: UnsetAssetContentArguments) -> Result<(), String> {
let dependent_keys = self.dependent_keys(&arg.key);
let asset = self
.assets
.get_mut(&arg.key)
.ok_or_else(|| "asset not found".to_string())?;
if asset.encodings.remove(&arg.content_encoding).is_some() {
on_asset_change(&mut self.asset_hashes, &arg.key, asset, dependent_keys);
}
Ok(())
}
pub fn delete_asset(&mut self, arg: DeleteAssetArguments) {
if self.assets.contains_key(&arg.key) {
for dependent in self.dependent_keys(&arg.key) {
self.asset_hashes.remove_responses_for_path(&dependent);
self.asset_hashes.remove_responses_for_path_v1(&dependent);
if dependent == FALLBACK_FILE {
self.asset_hashes.remove_fallback_responses();
self.asset_hashes.remove_fallback_responses_v1();
}
}
self.assets.remove(&arg.key);
}
for key in aliases_of(&arg.key) {
// if an existing file can be aliased to the deleted file it has to become a valid alias again
if self.assets.contains_key(&key) {
let dependent_keys = self.dependent_keys(&key);
if let Some(asset) = self.assets.get_mut(&key) {
on_asset_change(&mut self.asset_hashes, &key, asset, dependent_keys);
}
}
}
}
pub fn clear(&mut self) {
self.assets.clear();
self.batches.clear();
self.chunks.clear();
self.next_batch_id = Nat::from(1_u8);
self.next_chunk_id = Nat::from(1_u8);
}
pub fn has_permission(&self, principal: &Principal, permission: &Permission) -> bool {
let list = self.get_permission_list(permission);
list.contains(principal)
}
pub fn can(&self, principal: &Principal, permission: &Permission) -> bool {
self.has_permission(principal, permission)
|| (*permission == Permission::Prepare
&& self.has_permission(principal, &Permission::Commit))
}
fn get_permission_list(&self, permission: &Permission) -> &BTreeSet<Principal> {
match permission {
Permission::Commit => &self.commit_principals,
Permission::Prepare => &self.prepare_principals,
Permission::ManagePermissions => &self.manage_permissions_principals,
}
}
fn get_mut_permission_list(&mut self, permission: &Permission) -> &mut BTreeSet<Principal> {
match permission {
Permission::Commit => &mut self.commit_principals,
Permission::Prepare => &mut self.prepare_principals,
Permission::ManagePermissions => &mut self.manage_permissions_principals,
}
}
pub fn retrieve(&self, key: &AssetKey) -> Result<RcBytes, String> {
let asset = self.get_asset(key)?;
let id_enc = asset
.encodings
.get("identity")
.ok_or_else(|| "no identity encoding".to_string())?;
if id_enc.content_chunks.len() > 1 {
return Err("Asset too large. Use get() and get_chunk() instead.".to_string());
}
Ok(id_enc.content_chunks[0].clone())
}
pub fn store(&mut self, arg: StoreArg, time: u64) -> Result<(), String> {
let dependent_keys = self.dependent_keys(&arg.key);
let asset = self.assets.entry(arg.key.clone()).or_default();
asset.content_type = arg.content_type;
asset.is_aliased = arg.aliased;
let hash = sha2::Sha256::digest(&arg.content).into();
if let Some(provided_hash) = arg.sha256 {
if hash != provided_hash.as_ref() {
return Err("sha256 mismatch".to_string());
}
}
let encoding = asset.encodings.entry(arg.content_encoding).or_default();
encoding.total_length = arg.content.len();
encoding.content_chunks = vec![RcBytes::from(arg.content)];
encoding.modified = Int::from(time);
encoding.sha256 = hash;
on_asset_change(&mut self.asset_hashes, &arg.key, asset, dependent_keys);
Ok(())
}
pub fn create_batch(&mut self, now: u64) -> Result<BatchId, String> {
self.batches.retain(|_, b| {
b.expires_at > now || matches!(b.evidence_computation, Some(Computed(_)))
});
self.chunks
.retain(|_, c| self.batches.contains_key(&c.batch_id));
if let Some((batch_id, batch)) = self
.batches
.iter()
.find(|(_batch_id, batch)| batch.commit_batch_arguments.is_some())
{
let message = match batch.evidence_computation {
Some(Computed(_)) => format!("Batch {} is already proposed. Delete or execute it to propose another.", batch_id),
_ => format!("Batch {} has not completed evidence computation. Wait for it to expire or delete it to propose another.", batch_id),
};
return Err(message);
}
if let Some(max_batches) = self.configuration.max_batches {
if self.batches.len() as u64 >= max_batches {
return Err("batch limit exceeded".to_string());
}
}
let batch_id = self.next_batch_id.clone();
self.next_batch_id += 1_u8;
self.batches.insert(
batch_id.clone(),
Batch {
expires_at: Int::from(now + BATCH_EXPIRY_NANOS),
commit_batch_arguments: None,
evidence_computation: None,
chunk_content_total_size: 0,
},
);
Ok(batch_id)
}
pub fn create_chunk(&mut self, arg: CreateChunkArg, now: u64) -> Result<ChunkId, String> {
if let Some(max_chunks) = self.configuration.max_chunks {
if self.chunks.len() + 1 > max_chunks as usize {
return Err("chunk limit exceeded".to_string());
}
}
if let Some(max_bytes) = self.configuration.max_bytes {
let current_total_bytes = &self.batches.iter().fold(0, |acc, (_batch_id, batch)| {
acc + batch.chunk_content_total_size
});
if current_total_bytes + arg.content.as_ref().len() > max_bytes as usize {
return Err("byte limit exceeded".to_string());
}
}
let batch = self
.batches
.get_mut(&arg.batch_id)
.ok_or_else(|| "batch not found".to_string())?;
if batch.commit_batch_arguments.is_some() {
return Err("batch has been proposed".to_string());
}
batch.expires_at = Int::from(now + BATCH_EXPIRY_NANOS);
let chunk_id = self.next_chunk_id.clone();
self.next_chunk_id += 1_u8;
batch.chunk_content_total_size += arg.content.as_ref().len();
self.chunks.insert(
chunk_id.clone(),
Chunk {
batch_id: arg.batch_id,
content: RcBytes::from(arg.content),
},
);
Ok(chunk_id)
}
pub fn commit_batch(&mut self, arg: CommitBatchArguments, now: u64) -> Result<(), String> {
let batch_id = arg.batch_id;
for op in arg.operations {
match op {
BatchOperation::CreateAsset(arg) => self.create_asset(arg)?,
BatchOperation::SetAssetContent(arg) => self.set_asset_content(arg, now)?,
BatchOperation::UnsetAssetContent(arg) => self.unset_asset_content(arg)?,
BatchOperation::DeleteAsset(arg) => self.delete_asset(arg),
BatchOperation::Clear(_) => self.clear(),
BatchOperation::SetAssetProperties(arg) => self.set_asset_properties(arg)?,
}
}
self.batches.remove(&batch_id);
self.certify_404_if_required();
Ok(())
}
pub fn propose_commit_batch(&mut self, arg: CommitBatchArguments) -> Result<(), String> {
let batch = self
.batches
.get_mut(&arg.batch_id)
.expect("batch not found");
if batch.commit_batch_arguments.is_some() {
return Err("batch already has proposed CommitBatchArguments".to_string());
};
batch.commit_batch_arguments = Some(arg);
Ok(())
}
pub fn commit_proposed_batch(
&mut self,
arg: CommitProposedBatchArguments,
now: u64,
) -> Result<(), String> {
self.validate_commit_proposed_batch_args(&arg)?;
let batch = self.batches.get_mut(&arg.batch_id).unwrap();
let proposed_batch_arguments = batch.commit_batch_arguments.take().unwrap();
self.commit_batch(proposed_batch_arguments, now)
}
pub fn validate_commit_proposed_batch(
&self,
arg: CommitProposedBatchArguments,
) -> Result<String, String> {
self.validate_commit_proposed_batch_args(&arg)?;
Ok(format!(
"commit proposed batch {} with evidence {}",
arg.batch_id,
hex::encode(arg.evidence)
))
}
fn validate_commit_proposed_batch_args(
&self,
arg: &CommitProposedBatchArguments,
) -> Result<(), String> {
let batch = self.batches.get(&arg.batch_id).ok_or("batch not found")?;
if batch.commit_batch_arguments.is_none() {
return Err("batch does not have CommitBatchArguments".to_string());
};
let evidence = if let Some(Computed(evidence)) = &batch.evidence_computation {
evidence.clone()
} else {
return Err("batch does not have computed evidence".to_string());
};
if evidence != arg.evidence {
return Err(format!(
"batch computed evidence {} does not match presented evidence {}",
hex::encode(evidence),
hex::encode(&arg.evidence)
));
}
Ok(())
}
pub fn compute_evidence(
&mut self,
arg: ComputeEvidenceArguments,
) -> Result<Option<ByteBuf>, String> {
let batch = self
.batches
.get_mut(&arg.batch_id)
.expect("batch not found");
let cba = batch
.commit_batch_arguments
.as_ref()
.expect("batch does not have CommitBatchArguments");
let max_iterations = arg
.max_iterations
.unwrap_or(DEFAULT_MAX_COMPUTE_EVIDENCE_ITERATIONS);
let mut ec = batch.evidence_computation.take().unwrap_or_default();
for _ in 0..max_iterations {
ec = ec.advance(cba, &self.chunks);
if matches!(ec, Computed(_)) {
break;
}
}
batch.evidence_computation = Some(ec);
if let Some(Computed(evidence)) = &batch.evidence_computation {
Ok(Some(evidence.clone()))
} else {
Ok(None)
}
}
pub fn delete_batch(&mut self, arg: DeleteBatchArguments) -> Result<(), String> {
if self.batches.remove(&arg.batch_id).is_none() {
return Err("batch not found".to_string());
}
self.chunks.retain(|_, c| c.batch_id != arg.batch_id);
Ok(())
}
pub fn list_assets(&self) -> Vec<AssetDetails> {
self.assets
.iter()
.map(|(key, asset)| {
let mut encodings: Vec<_> = asset
.encodings
.iter()
.map(|(enc_name, enc)| AssetEncodingDetails {
content_encoding: enc_name.clone(),
sha256: Some(ByteBuf::from(enc.sha256)),
length: Nat::from(enc.total_length),
modified: enc.modified.clone(),
})
.collect();
encodings.sort_by(|l, r| l.content_encoding.cmp(&r.content_encoding));
AssetDetails {
key: key.clone(),
content_type: asset.content_type.clone(),
encodings,
}
})
.collect::<Vec<_>>()
}
pub fn certified_tree(&self, certificate: &[u8]) -> CertifiedTree {
let mut serializer = serde_cbor::ser::Serializer::new(vec![]);
serializer.self_describe().unwrap();
self.asset_hashes
.as_hash_tree()
.serialize(&mut serializer)
.unwrap();
CertifiedTree {
certificate: certificate.to_vec(),
tree: serializer.into_inner(),
}
}
pub fn get(&self, arg: GetArg) -> Result<EncodedAsset, String> {
let asset = self.get_asset(&arg.key)?;
for enc in arg.accept_encodings.iter() {
if let Some(asset_enc) = asset.encodings.get(enc) {
return Ok(EncodedAsset {
content: asset_enc.content_chunks[0].clone(),
content_type: asset.content_type.clone(),
content_encoding: enc.clone(),
total_length: Nat::from(asset_enc.total_length as u64),
sha256: Some(ByteBuf::from(asset_enc.sha256)),
});
}
}
Err("no such encoding".to_string())
}
pub fn get_chunk(&self, arg: GetChunkArg) -> Result<RcBytes, String> {
let asset = self.get_asset(&arg.key)?;
let enc = asset
.encodings
.get(&arg.content_encoding)
.ok_or_else(|| "no such encoding".to_string())?;
let expected_hash = arg.sha256.ok_or("sha256 required")?;
if expected_hash != enc.sha256 {
return Err("sha256 mismatch".to_string());
}
if arg.index >= enc.content_chunks.len() {
return Err("chunk index out of bounds".to_string());
}
let index: usize = arg.index.0.to_usize().unwrap();
Ok(enc.content_chunks[index].clone())
}
fn build_http_response(
&self,
certificate: &[u8],
path: &str,
requested_encodings: Vec<String>,
chunk_index: usize,
callback: CallbackFunc,
etags: Vec<Hash>,
req: HttpRequest,
) -> HttpResponse {
if let Ok(asset) = self.get_asset(&path.into()) {
if !asset.allow_raw_access() && req.is_raw_domain() {
return req.redirect_from_raw_to_certified_domain();
}
} else if let Ok(asset) = self.get_asset(&FALLBACK_FILE.to_string()) {
if !asset.allow_raw_access() && req.is_raw_domain() {
return req.redirect_from_raw_to_certified_domain();
}
}
let (certificate_header, witness_result) = if req.get_certificate_version() == 1 {
self.asset_hashes.witness_to_header_v1(path, certificate)
} else {
self.asset_hashes.witness_to_header(path, certificate)
};
if witness_result == WitnessResult::FallbackFound {
if let Ok(asset) = self.get_asset(&FALLBACK_FILE.to_string()) {
if let Some(response) = HttpResponse::build_ok_from_requested_encodings(
asset,
&requested_encodings,
path,
chunk_index,
Some(&certificate_header),
&callback,
&etags,
req.get_certificate_version(),
) {
return response;
}
}
} else if witness_result == WitnessResult::PathFound {
if let Ok(asset) = self.get_asset(&path.into()) {
if !asset.allow_raw_access() && req.is_raw_domain() {
return req.redirect_from_raw_to_certified_domain();
}
if let Some(response) = HttpResponse::build_ok_from_requested_encodings(
asset,
&requested_encodings,
path,
chunk_index,
Some(&certificate_header),
&callback,
&etags,
req.get_certificate_version(),
) {
return response;
}
}
}
HttpResponse::build_404(certificate_header, req.get_certificate_version())
}
pub fn http_request(
&self,
req: HttpRequest,
certificate: &[u8],
callback: CallbackFunc,
) -> HttpResponse {
let mut encodings = vec![];
// waiting for https://dfinity.atlassian.net/browse/BOUN-446
let etags = Vec::new();
for (name, value) in req.headers.iter() {
if name.eq_ignore_ascii_case("Accept-Encoding") {
for v in value.split(',') {
encodings.push(v.trim().to_string());
}
}
}
let path = match req.url.find('?') {
Some(i) => &req.url[..i],
None => &req.url[..],
};
match url_decode(path) {
Ok(path) => {
self.build_http_response(certificate, &path, encodings, 0, callback, etags, req)
}
Err(err) => HttpResponse {
status_code: 400,
headers: vec![],
body: RcBytes::from(ByteBuf::from(format!(
"failed to decode path '{}': {}",
path, err
))),
upgrade: None,
streaming_strategy: None,
},
}
}
pub fn http_request_streaming_callback(
&self,
StreamingCallbackToken {
key,
content_encoding,
index,
sha256,
}: StreamingCallbackToken,
) -> Result<StreamingCallbackHttpResponse, String> {
let asset = self
.get_asset(&key)
.map_err(|_| "Invalid token on streaming: key not found.".to_string())?;
let enc = asset
.encodings
.get(&content_encoding)
.ok_or_else(|| "Invalid token on streaming: encoding not found.".to_string())?;
let expected_hash = sha256.ok_or("sha256 required")?;
if expected_hash != enc.sha256 {
return Err("sha256 mismatch".to_string());
}
// MAX is good enough. This means a chunk would be above 64-bits, which is impossible...
let chunk_index = index.0.to_usize().unwrap_or(usize::MAX);
Ok(StreamingCallbackHttpResponse {
body: enc.content_chunks[chunk_index].clone(),
token: StreamingCallbackToken::create_token(
&content_encoding,
enc.content_chunks.len(),
enc.sha256,
&key,
chunk_index,
),
})
}
pub fn get_asset_properties(&self, key: AssetKey) -> Result<AssetProperties, String> {
let asset = self
.assets
.get(&key)
.ok_or_else(|| "asset not found".to_string())?;
Ok(AssetProperties {
max_age: asset.max_age,
headers: asset.headers.clone(),
allow_raw_access: asset.allow_raw_access,
is_aliased: asset.is_aliased,
})
}
pub fn set_asset_properties(&mut self, arg: SetAssetPropertiesArguments) -> Result<(), String> {
let dependent_keys = self.dependent_keys(&arg.key);
let asset = self
.assets
.get_mut(&arg.key)
.ok_or_else(|| "asset not found".to_string())?;
if let Some(headers) = arg.headers {
asset.headers = headers
}
if let Some(max_age) = arg.max_age {
asset.max_age = max_age
}
if let Some(allow_raw_access) = arg.allow_raw_access {
asset.allow_raw_access = allow_raw_access
}
if let Some(is_aliased) = arg.is_aliased {
asset.is_aliased = is_aliased
}
on_asset_change(&mut self.asset_hashes, &arg.key, asset, dependent_keys);
Ok(())
}
// Returns keys that needs to be updated if the supplied key is changed.
fn dependent_keys(&self, key: &AssetKey) -> Vec<AssetKey> {
if self
.assets