-
Notifications
You must be signed in to change notification settings - Fork 126
Expand file tree
/
Copy pathtest_client.rs
More file actions
4231 lines (3752 loc) · 137 KB
/
Copy pathtest_client.rs
File metadata and controls
4231 lines (3752 loc) · 137 KB
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
// Copyright (c) Walrus Foundation
// SPDX-License-Identifier: Apache-2.0
// Allowing `unwrap`s in tests.
#![allow(clippy::unwrap_used)]
// This avoids the following error when running simtests:
// error[E0275]: overflow evaluating the requirement `{coroutine ...}: std::marker::Send`
#![recursion_limit = "256"]
//! Contains end-to-end tests for the Walrus client interacting with a Walrus test cluster.
#[cfg(msim)]
use std::sync::atomic::{AtomicU32, Ordering};
#[cfg(not(msim))]
use std::thread;
use std::{
collections::{HashMap, HashSet},
net::SocketAddr,
num::NonZeroU16,
path::PathBuf,
str::FromStr,
sync::Arc,
time::Duration,
};
use bytes::Bytes;
use rand::{Rng, random, seq::SliceRandom, thread_rng};
use reqwest::Url;
#[cfg(msim)]
use sui_macros::{clear_fail_point, register_fail_point_if};
use sui_types::base_types::{ObjectID, SUI_ADDRESS_LENGTH, SuiAddress};
use tokio::{sync::Mutex, time::Instant};
use tokio_stream::StreamExt;
use walrus_core::{
BlobId,
DEFAULT_ENCODING,
EncodingType,
EpochCount,
QuiltPatchId,
ShardIndex,
SliverPairIndex,
encoding::{
BLOB_TYPE_ATTRIBUTE_KEY,
EncodingAxis,
EncodingFactory as _,
Primary,
QUILT_TYPE_VALUE,
Secondary,
encoded_blob_length_for_n_shards,
quilt_encoding::{QuiltApi, QuiltStoreBlob, QuiltVersionV1},
},
merkle::Node,
messages::BlobPersistenceType,
metadata::{QuiltMetadata, VerifiedBlobMetadataWithId},
};
use walrus_proc_macros::walrus_simtest;
use walrus_sdk::{
config::ClientConfig,
error::{
ClientError,
ClientErrorKind::{self, NoMetadataReceived, NotEnoughConfirmations, NotEnoughSlivers},
},
node_client::{
Blocklist,
StoreArgs,
StoreBlobsApi as _,
StoreBlobsInBucketApi as _,
WalrusNodeClient,
byte_range_read_client::{ByteRangeReadClient, ByteRangeReadClientConfig},
quilt_client::QuiltClientConfig,
responses::{BlobBucketStoreResult, BlobStoreResult, QuiltStoreResult},
streaming::start_streaming_blob,
upload_relay_client::UploadRelayClient,
},
store_optimizations::StoreOptimizations,
upload_relay::tip_config::{TipConfig, TipKind},
uploader::TailHandling,
};
use walrus_service::test_utils::{
StorageNodeHandleTrait,
TestCluster,
TestNodesConfig,
UnusedSocketAddress,
test_cluster::{self, FROST_PER_NODE_WEIGHT},
};
use walrus_storage_node_client::api::BlobStatus;
use walrus_sui::{
client::{
BlobPersistence,
ExpirySelectionPolicy,
PostStoreAction,
ReadClient,
SuiClientError,
SuiContractClient,
retry_client::{RetriableSuiClient, retriable_sui_client::LazySuiClientBuilder},
},
coin::Coin,
config::WalletConfig,
test_utils::{self, fund_addresses, wallet_for_testing},
types::{
Blob,
BlobEvent,
ContractEvent,
move_errors::{MoveExecutionError, RawMoveError},
move_structs::{BlobAttribute, BlobWithAttribute, Credits, SharedBlob},
},
};
use walrus_test_utils::{Result as TestResult, WithTempDir, assert_unordered_eq, async_param_test};
use walrus_upload_relay::{
UploadRelayHandle,
controller::{WalrusUploadRelayConfig, get_client_with_config},
};
use walrus_utils::{backoff::ExponentialBackoffConfig, metrics::Registry};
async_param_test! {
#[ignore = "ignore E2E tests by default"]
#[walrus_simtest]
test_store_and_read_blob_without_failures : [
empty: (0),
one_byte: (1),
large_byte: (30000),
]
}
async fn test_store_and_read_blob_without_failures(blob_size: usize) {
walrus_test_utils::init_tracing();
assert!(matches!(
run_store_and_read_with_crash_failures(&[], &[], blob_size, None).await,
Ok(()),
))
}
/// Basic read and write test for the client.
///
/// It generates random blobs and stores them.
/// It then reads the blobs back and verifies that the data is correct.
async fn basic_store_and_read<F>(
client: &WithTempDir<WalrusNodeClient<SuiContractClient>>,
num_blobs: usize,
data_length: usize,
upload_relay_client: Option<UploadRelayClient>,
pre_read_hook: F,
) -> TestResult
where
F: FnOnce() -> TestResult,
{
// Generate random blobs.
let blob_data = walrus_test_utils::random_data_list(data_length, num_blobs);
let mut path_to_data: HashMap<PathBuf, Vec<u8>> = HashMap::new();
let mut blobs_with_paths: Vec<(PathBuf, Vec<u8>)> = vec![];
let mut path_to_blob_id: HashMap<PathBuf, BlobId> = HashMap::new();
// Create paths for each blob.
for (i, data) in blob_data.iter().enumerate() {
let path = PathBuf::from(format!("blob_{i}"));
path_to_data.insert(path.clone(), data.to_vec());
blobs_with_paths.push((path, data.to_vec()));
}
let tail_handle_collector = Arc::new(Mutex::new(vec![]));
let store_args = {
let store_args = StoreArgs::default_with_epochs(1).no_store_optimizations();
if let Some(upload_relay_client) = upload_relay_client {
store_args.with_upload_relay_client(upload_relay_client)
} else if rand::thread_rng().gen_bool(0.5) {
store_args
.with_tail_handling(TailHandling::Detached)
.with_tail_handle_collector(tail_handle_collector.clone())
} else {
store_args
}
};
let store_result = client
.as_ref()
.reserve_and_store_blobs_retry_committees_with_path(blobs_with_paths, &store_args)
.await?;
// Wait for the tail uploads to complete.
// This is going to ensure that we wait for tail uploads to complete before reading the blobs.
// This is similar to blocking on tail uploads but happens after forming the certificate.
let mut handles = tail_handle_collector.lock().await;
while let Some(handle) = handles.pop() {
handle.await.unwrap();
}
for result in store_result {
match result.blob_store_result {
BlobStoreResult::NewlyCreated { blob_object, .. } => {
assert_eq!(
blob_object.encoding_type, DEFAULT_ENCODING,
"Stored blob has incorrect encoding type"
);
path_to_blob_id.insert(result.path, blob_object.blob_id);
}
_ => panic!(
"Expected NewlyCreated result, got: {:?}",
result.blob_store_result
),
};
}
// Call the pre-read hook before reading data.
pre_read_hook()?;
// Read back and verify all blobs.
for (path, blob_id) in path_to_blob_id {
let read_data = client.as_ref().read_blob::<Primary>(&blob_id).await?;
assert_eq!(
read_data,
path_to_data[&path],
"Data mismatch for blob at path {}",
path.display()
);
}
Ok(())
}
#[ignore = "ignore E2E tests by default"]
#[walrus_simtest]
async fn test_store_blobs_in_bucket() -> TestResult {
#[cfg(msim)]
{
test_store_blobs_in_bucket_inner().await
}
#[cfg(not(msim))]
run_with_large_stack(|| {
tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()?
.block_on(test_store_blobs_in_bucket_inner())
})
}
async fn test_store_blobs_in_bucket_inner() -> TestResult {
walrus_test_utils::init_tracing();
let (_sui_cluster_handle, _cluster, client, system_context, _) =
test_cluster::E2eTestSetupBuilder::new().build().await?;
let blob_bucket_pkg_id = system_context
.blob_bucket_pkg_id
.expect("blob bucket package is published for tests");
let blobs = walrus_test_utils::random_data_list(10_000, 2);
let store_args = StoreArgs::default_with_epochs(2)
.no_store_optimizations()
.deletable();
let encoded_size = client
.as_ref()
.encoding_config()
.get_for_type(store_args.encoding_type)
.encoded_blob_length(blobs[0].len().try_into().unwrap())
.unwrap();
let blob_bucket = client
.as_ref()
.sui_client()
.create_blob_bucket(blob_bucket_pkg_id, encoded_size, 1)
.await?;
let initial_pool_status = client
.as_ref()
.sui_client()
.blob_bucket_storage_pool_status(blob_bucket.bucket_object_id)
.await?;
assert_eq!(
initial_pool_status.reserved_encoded_capacity_bytes,
encoded_size
);
let store_results = client
.as_ref()
.reserve_and_store_blobs_in_bucket(blobs.clone(), blob_bucket, &store_args)
.await?;
let final_pool_status = client
.as_ref()
.sui_client()
.blob_bucket_storage_pool_status(blob_bucket.bucket_object_id)
.await?;
assert!(
final_pool_status.end_epoch > initial_pool_status.end_epoch,
"bucket storage pool should have been extended"
);
assert!(
final_pool_status.reserved_encoded_capacity_bytes >= encoded_size * blobs.len() as u64,
"bucket storage pool should have increased capacity for all blobs"
);
let mut blob_ids = Vec::with_capacity(store_results.len());
for store_result in store_results {
match store_result {
BlobBucketStoreResult::NewlyCreated { pooled_blob_object } => {
assert_eq!(
pooled_blob_object.storage_pool_id,
blob_bucket.storage_pool_id
);
assert!(pooled_blob_object.deletable);
assert!(pooled_blob_object.is_certified());
blob_ids.push(pooled_blob_object.blob_id);
}
BlobBucketStoreResult::Error {
blob_id,
failure_phase,
error_msg,
} => panic!(
"unexpected bucket store error for blob {blob_id:?} in {failure_phase}: {}",
error_msg
),
}
}
for (blob_id, expected_data) in blob_ids.into_iter().zip(blobs) {
let read_data = client.as_ref().read_blob::<Primary>(&blob_id).await?;
assert_eq!(read_data, expected_data);
}
Ok(())
}
#[cfg(not(msim))]
fn run_with_large_stack<T>(f: impl FnOnce() -> TestResult<T> + Send + 'static) -> TestResult<T>
where
T: Send + 'static,
{
// This bucket e2e path drives a deep Sui/Move setup and can overflow the default test-thread
// stack on CI runners.
let thread = thread::Builder::new()
.name("large-stack-e2e-test".to_string())
.stack_size(64 * 1024 * 1024)
.spawn(f)?;
thread
.join()
.map_err(|panic| -> Box<dyn std::error::Error + Send + Sync> {
format!("large-stack test thread panicked: {panic:?}").into()
})?
}
async_param_test! {
#[ignore = "ignore E2E tests by default"]
#[walrus_simtest]
test_store_and_read_blob_with_crash_failures : [
no_failures: (&[], &[], &[]),
one_failure: (&[0], &[], &[]),
f_failures: (&[4], &[], &[]),
f_plus_one_failures: (&[0, 4], &[], &[NotEnoughConfirmations(8, 9)]),
all_shard_failures: (&[0, 1, 2, 3, 4], &[], &[NotEnoughConfirmations(0, 9)]),
f_plus_one_read_failures: (&[], &[0, 4], &[]),
two_f_plus_one_read_failures: (
&[], &[1, 2, 4], &[NoMetadataReceived, NotEnoughSlivers]),
read_and_write_overlap_failures: (
&[4], &[2, 3], &[NoMetadataReceived, NotEnoughSlivers]),
]
}
async fn test_store_and_read_blob_with_crash_failures(
failed_shards_write: &[usize],
failed_shards_read: &[usize],
expected_errors: &[ClientErrorKind],
) {
walrus_test_utils::init_tracing();
let result = run_store_and_read_with_crash_failures(
failed_shards_write,
failed_shards_read,
31415,
None,
)
.await;
match (result, expected_errors) {
(Ok(()), []) => (),
(Err(actual_err), expected_errs) => match actual_err.downcast::<ClientError>() {
Ok(client_err) => {
if !expected_errs
.iter()
.any(|expected_err| error_kind_matches(client_err.kind(), expected_err))
{
panic!(
"client error mismatch; expected=({:?}); actual=({:?});",
expected_errs,
client_err.kind()
)
}
}
Err(err) => panic!("unexpected error {err}"),
},
(act, exp) => panic!("test result mismatch; expected=({exp:?}); actual=({act:?});"),
}
}
async fn run_store_and_read_with_crash_failures(
failed_shards_write: &[usize],
failed_shards_read: &[usize],
data_length: usize,
upload_relay_client: Option<UploadRelayClient>,
) -> TestResult {
walrus_test_utils::init_tracing();
let (_sui_cluster_handle, mut cluster, client, _, _) =
test_cluster::E2eTestSetupBuilder::new().build().await?;
// Stop the nodes in the write failure set.
failed_shards_write
.iter()
.for_each(|&idx| cluster.cancel_node(idx));
// Create closure that will stop nodes for read failures.
let pre_read_hook = {
let cluster = &mut cluster;
let failed_nodes = failed_shards_read.to_vec();
move || {
failed_nodes
.iter()
.for_each(|&idx| cluster.cancel_node(idx));
Ok(())
}
};
// Use basic_store_and_read with our pre_read_hook.
basic_store_and_read(&client, 4, data_length, upload_relay_client, pre_read_hook).await
}
async_param_test! {
#[ignore = "ignore E2E tests by default"]
#[walrus_simtest]
test_inconsistency -> TestResult : [
no_failures: (&[]),
one_failure: (&[0]),
f_failures: (&[4]),
]
}
/// Stores a blob that is inconsistent in 1 shard.
async fn test_inconsistency(failed_nodes: &[usize]) -> TestResult {
walrus_test_utils::init_tracing();
let (_sui_cluster_handle, mut cluster, mut client, _, _) =
test_cluster::E2eTestSetupBuilder::new().build().await?;
// Store a blob and get confirmations from each node.
let blob = walrus_test_utils::random_data(31415);
// Find the shards of the failed nodes.
let failed_node_names: Vec<String> = failed_nodes.iter().map(|i| format!("node-{i}")).collect();
let committees = client
.as_ref()
.get_committees()
.await
.expect("committees should be available");
let shards_of_failed_nodes = client.as_ref().shards_of(&failed_node_names, &committees);
// Encode the blob with false metadata for one shard.
let (pairs, metadata) = client
.as_ref()
.encoding_config()
.get_for_type(DEFAULT_ENCODING)
.encode_with_metadata(blob)?;
let mut metadata = metadata.metadata().to_owned();
let mut i = 0;
// Change a shard that is not in the failure set. Since the mapping of slivers to shards
// depends on the blob ID, we need to search for an invalid hash for which the modified shard
// is not in the failure set.
loop {
metadata.mut_inner().hashes[1].primary_hash = Node::Digest([i; 32]);
let blob_id = BlobId::from_sliver_pair_metadata(&metadata);
if !shards_of_failed_nodes.contains(
&SliverPairIndex::new(1).to_shard_index(NonZeroU16::new(13).unwrap(), &blob_id),
) {
break;
}
i += 1;
}
let blob_id = BlobId::from_sliver_pair_metadata(&metadata);
let metadata = VerifiedBlobMetadataWithId::new_verified_unchecked(blob_id, metadata);
tracing::debug!(
"shard index for inconsistent sliver: {}",
SliverPairIndex::new(1).to_shard_index(NonZeroU16::new(13).unwrap(), &blob_id)
);
// Register blob.
let (blob_sui_object, _) = client
.as_ref()
.resource_manager(&committees)
.get_existing_or_register(
&[&metadata],
1,
BlobPersistence::Permanent,
StoreOptimizations::none(),
)
.await?
.into_iter()
.next()
.expect("should register exactly one blob");
// Certify blob.
let certificate = client
.as_ref()
.send_blob_data_and_get_certificate(
&metadata,
Arc::new(pairs),
&BlobPersistenceType::Permanent,
None,
TailHandling::Blocking,
None,
None,
None,
None,
)
.await?;
// Stop the nodes in the failure set.
failed_nodes
.iter()
.for_each(|&idx| cluster.cancel_node(idx));
let blob_with_attr = BlobWithAttribute {
blob: blob_sui_object,
attribute: None,
};
client
.as_mut()
.sui_client()
.certify_blobs(&[(&blob_with_attr, certificate)], PostStoreAction::Keep)
.await?;
// Wait to receive an inconsistent blob event.
let events = client
.as_mut()
.sui_client()
.event_stream(Duration::from_millis(50), None)
.await?;
let mut events = std::pin::pin!(events);
tokio::time::timeout(Duration::from_secs(30), async {
while let Some(event) = events.next().await {
tracing::debug!("event: {event:?}");
if let ContractEvent::BlobEvent(BlobEvent::InvalidBlobID(_)) = event {
return;
}
}
panic!("should be infinite stream")
})
.await?;
// Cancel the nodes and wait to prevent event handles being dropped.
cluster.nodes.iter().for_each(|node| node.cancel());
tokio::time::sleep(Duration::from_secs(1)).await;
Ok(())
}
fn error_kind_matches(actual: &ClientErrorKind, expected: &ClientErrorKind) -> bool {
match (actual, expected) {
(
ClientErrorKind::NotEnoughConfirmations(act_a, act_b),
ClientErrorKind::NotEnoughConfirmations(exp_a, exp_b),
) => act_a == exp_a && act_b == exp_b,
(ClientErrorKind::NotEnoughSlivers, ClientErrorKind::NotEnoughSlivers) => true,
(ClientErrorKind::BlobIdDoesNotExist, ClientErrorKind::BlobIdDoesNotExist) => true,
(ClientErrorKind::NoMetadataReceived, ClientErrorKind::NoMetadataReceived) => true,
(ClientErrorKind::NoValidStatusReceived, ClientErrorKind::NoValidStatusReceived) => true,
(ClientErrorKind::Other(_), ClientErrorKind::Other(_)) => true,
(_, _) => false,
}
}
async_param_test! {
#[ignore = "ignore E2E tests by default"]
#[walrus_simtest]
test_store_with_existing_blob_resource -> TestResult : [
reuse_resource_permanent_1: (
1, BlobPersistence::Permanent, 1, BlobPersistence::Permanent, true
),
reuse_resource_permanent_2: (
2, BlobPersistence::Permanent, 1, BlobPersistence::Permanent, true
),
reuse_and_extend_permanent: (
1, BlobPersistence::Permanent, 2, BlobPersistence::Permanent, true
),
reuse_resource_deletable_1: (
1, BlobPersistence::Deletable, 1, BlobPersistence::Deletable, true
),
reuse_resource_deletable_2: (
2, BlobPersistence::Deletable, 1, BlobPersistence::Deletable, true
),
reuse_and_extend_deletable: (
1, BlobPersistence::Deletable, 2, BlobPersistence::Deletable, true
),
persistence_mismatch_1: (
1, BlobPersistence::Permanent, 1, BlobPersistence::Deletable, false
),
persistence_mismatch_2: (
1, BlobPersistence::Deletable, 1, BlobPersistence::Permanent, false
),
]
}
/// Tests that the client reuses existing (uncertified) blob registrations to store blobs.
///
/// The `epochs_ahead_registered` are the epochs ahead of the already-existing blob object.
/// The `persistence_registered` is the persistence of the already-existing blob object.
/// The `epochs_ahead_required` are the epochs ahead that are requested to the client when
/// registering anew.
/// The `persistence_required` is the persistence that is requested to the client when
/// registering anew.
/// `should_match` is a boolean that indicates if the blob object used in the final upload
/// should be the same as the first one registered.
async fn test_store_with_existing_blob_resource(
epochs_ahead_registered: EpochCount,
persistence_registered: BlobPersistence,
epochs_ahead_required: EpochCount,
persistence_required: BlobPersistence,
should_match: bool,
) -> TestResult {
walrus_test_utils::init_tracing();
let (_sui_cluster_handle, _cluster, client, _, _) =
test_cluster::E2eTestSetupBuilder::new().build().await?;
let blobs = walrus_test_utils::random_data_list(31415, 4);
let encoding_type = DEFAULT_ENCODING;
let metadata = blobs
.iter()
.map(|blob| {
let (_, metadata) = client
.as_ref()
.encoding_config()
.get_for_type(encoding_type)
.encode_with_metadata(blob.clone())
.expect("blob encoding should not fail");
let metadata = metadata.metadata().to_owned();
let blob_id = BlobId::from_sliver_pair_metadata(&metadata);
VerifiedBlobMetadataWithId::new_verified_unchecked(blob_id, metadata)
})
.collect::<Vec<_>>();
// Register a list of new blobs.
let committees = client
.as_ref()
.get_committees()
.await
.expect("committees should be available");
let original_blob_objects = client
.as_ref()
.resource_manager(&committees)
.get_existing_or_register(
&metadata.iter().collect::<Vec<_>>(),
epochs_ahead_registered,
persistence_registered,
StoreOptimizations::all(),
)
.await?
.into_iter()
.map(|(blob, _)| (blob.blob_id, blob))
.collect::<HashMap<_, _>>();
// Now ask the client to store again.
let store_args = StoreArgs::default_with_epochs(epochs_ahead_required)
.with_encoding_type(encoding_type)
.with_persistence(persistence_required);
let blob_stores = client
.inner
.reserve_and_store_blobs(blobs, &store_args)
.await?
.into_iter()
.map(|blob_store_result| match blob_store_result {
BlobStoreResult::NewlyCreated { blob_object, .. } => (blob_object.blob_id, blob_object),
_ => panic!("the client should be able to store the blob"),
})
.collect::<HashMap<_, _>>();
for (blob_id, blob_object) in blob_stores {
let original_blob_object = original_blob_objects
.get(&blob_id)
.expect("should have original blob object");
assert!(should_match == (blob_object.id == original_blob_object.id));
}
Ok(())
}
/// Registers a blob and returns the blob ID.
async fn register_blob(
client: &WithTempDir<WalrusNodeClient<SuiContractClient>>,
blob: &[u8],
encoding_type: EncodingType,
epochs_ahead: EpochCount,
persistence: BlobPersistence,
) -> TestResult<BlobId> {
// Encode blob and get metadata
let metadata = client
.as_ref()
.encoding_config()
.get_for_type(encoding_type)
.compute_metadata(blob)
.expect("blob encoding should not fail");
let metadata = metadata.metadata().to_owned();
let blob_id = BlobId::from_sliver_pair_metadata(&metadata);
let metadata = VerifiedBlobMetadataWithId::new_verified_unchecked(blob_id, metadata);
let committees = client
.as_ref()
.get_committees()
.await
.expect("committees should be available");
// Register the blob
let blob_id = client
.as_ref()
.resource_manager(&committees)
.get_existing_or_register(
&[&metadata],
epochs_ahead,
persistence,
StoreOptimizations::all(),
)
.await?
.into_iter()
.map(|(blob, _)| blob.blob_id)
.next()
.expect("should have registered blob");
Ok(blob_id)
}
/// Store a blob and return the blob ID.
async fn store_blob(
client: &WithTempDir<WalrusNodeClient<SuiContractClient>>,
blob: Vec<u8>,
encoding_type: EncodingType,
epochs_ahead: EpochCount,
persistence: BlobPersistence,
) -> TestResult<BlobId> {
let store_args = StoreArgs::default_with_epochs(epochs_ahead)
.with_encoding_type(encoding_type)
.with_persistence(persistence);
let result = client
.inner
.reserve_and_store_blobs(vec![blob.to_vec()], &store_args)
.await?;
Ok(result
.into_iter()
.next()
.expect("should have one blob store result")
.blob_id()
.expect("blob ID should be present"))
}
/// Tests that the client can store and read duplicate blobs.
#[ignore = "ignore E2E tests by default"]
#[walrus_simtest]
pub async fn test_store_and_read_duplicate_blobs() -> TestResult {
walrus_test_utils::init_tracing();
let (_sui_cluster_handle, _cluster, client, _, _) =
test_cluster::E2eTestSetupBuilder::new().build().await?;
let client = client.as_ref();
// Generate random blobs.
let mut blob_data = walrus_test_utils::random_data_list(31415, 3);
blob_data.push(blob_data[0].clone());
blob_data.push(blob_data[1].clone());
blob_data.push(blob_data[0].clone());
let blobs_with_paths: Vec<_> = blob_data
.into_iter()
.enumerate()
.map(|(i, data)| {
let path = PathBuf::from(format!("blob_{i}"));
(path, data)
})
.collect();
let store_args = StoreArgs::default_with_epochs(1).no_store_optimizations();
let store_result_with_path = client
.reserve_and_store_blobs_retry_committees_with_path(blobs_with_paths.clone(), &store_args)
.await?;
let read_result =
futures::future::join_all(store_result_with_path.iter().map(|result| async {
let blob = client
.read_blob::<Primary>(
&result
.blob_store_result
.blob_id()
.expect("blob ID should be present"),
)
.await
.expect("should be able to read blob");
(result.blob_store_result.blob_id(), blob)
}))
.await;
assert_eq!(store_result_with_path.len(), blobs_with_paths.len());
store_result_with_path
.iter()
.zip(blobs_with_paths.iter())
.zip(read_result.iter())
.for_each(|((result, (path, data)), (blob_id, blob))| {
assert_eq!(&result.path, path);
assert_eq!(blob, data);
assert_eq!(blob_id, &result.blob_store_result.blob_id());
});
Ok(())
}
async_param_test! {
#[ignore = "ignore E2E tests by default"]
#[walrus_simtest]
test_store_with_existing_blobs -> TestResult : [
deletable: (BlobPersistence::Deletable),
permanent: (BlobPersistence::Permanent),
]
}
/// Tests that blobs can be extended when possible.
async fn test_store_with_existing_blobs(persistence: BlobPersistence) -> TestResult {
walrus_test_utils::init_tracing();
let (_sui_cluster_handle, _cluster, client, _, _) =
test_cluster::E2eTestSetupBuilder::new().build().await?;
let blobs = walrus_test_utils::random_data_list(31415, 5);
// Initial setup, with blobs in different states, the names indicate the later outcome
// of a following store operation.
let encoding_type = DEFAULT_ENCODING;
let reuse_blob = register_blob(&client, &blobs[0], encoding_type, 40, persistence).await?;
let certify_and_extend_blob =
register_blob(&client, &blobs[1], encoding_type, 10, persistence).await?;
let already_certified_blob =
store_blob(&client, blobs[2].clone(), encoding_type, 50, persistence).await?;
let extended_blob =
store_blob(&client, blobs[3].clone(), encoding_type, 20, persistence).await?;
let epoch = client.as_ref().sui_client().current_epoch().await?;
let epochs_ahead = 30;
let store_args = StoreArgs::default_with_epochs(epochs_ahead)
.with_encoding_type(encoding_type)
.with_persistence(persistence);
let store_results = client
.inner
.reserve_and_store_blobs(blobs, &store_args)
.await?;
for (blob_index, result) in store_results.into_iter().enumerate() {
let Some(end_epoch) = result.end_epoch() else {
panic!("end_epoch should be present for blob {blob_index}");
};
assert!(
end_epoch >= epoch + epochs_ahead,
"blob {blob_index}: end_epoch ({end_epoch}) should be at least epoch ({epoch}) + \
epochs_ahead ({epochs_ahead})"
);
if result.blob_id() == Some(reuse_blob) {
assert!(matches!(
&result,
BlobStoreResult::NewlyCreated{blob_object:_, resource_operation, ..
} if resource_operation.is_reuse_registration()));
} else if result.blob_id() == Some(certify_and_extend_blob) {
assert!(matches!(
&result,
BlobStoreResult::NewlyCreated {
resource_operation,
..
} if resource_operation.is_certify_and_extend()
));
} else if result.blob_id() == Some(already_certified_blob) {
assert!(matches!(&result, BlobStoreResult::AlreadyCertified { .. }));
} else if result.blob_id() == Some(extended_blob) {
assert!(matches!(
&result,
BlobStoreResult::NewlyCreated {
resource_operation,
..
} if resource_operation.is_extend()
));
} else {
assert!(matches!(
&result,
BlobStoreResult::NewlyCreated {
resource_operation,
..
} if resource_operation.is_registration()
));
}
}
Ok(())
}
async_param_test! {
#[ignore = "ignore E2E tests by default"]
#[walrus_simtest]
test_store_with_existing_storage_resource -> TestResult : [
reuse_storage: (1, 1, true),
reuse_storage_two: (2, 1, true),
no_reuse_storage: (1, 2, false),
]
}
/// Tests that the client reuses existing storage resources to store blobs.
///
/// The `epochs_ahead_registered` are the epochs ahead of the already-existing storage resource.
/// The `epochs_ahead_required` are the epochs ahead that are requested to the client when
/// registering anew.
/// `should_match` is a boolean that indicates if the storage object used in the final upload
/// should be the same as the first one registered.
async fn test_store_with_existing_storage_resource(
epochs_ahead_registered: EpochCount,
epochs_ahead_required: EpochCount,
should_match: bool,
) -> TestResult {
walrus_test_utils::init_tracing();
let (_sui_cluster_handle, _cluster, client, _, _) =
test_cluster::E2eTestSetupBuilder::new().build().await?;
let blobs = walrus_test_utils::random_data_list(31415, 4);
let encoding_type = DEFAULT_ENCODING;
let unencoded_blobs: Vec<walrus_sdk::node_client::client_types::WalrusStoreBlobMaybeFinished> =
blobs
.iter()
.cloned()
.enumerate()
.map(|(i, data)| {
walrus_sdk::node_client::client_types::WalrusStoreBlobMaybeFinished::new_unencoded(
data,
format!("test-{i:02}"),
BlobAttribute::default(),
client
.as_ref()
.encoding_config()
.get_for_type(encoding_type),
)
})
.collect();
let encoded_blobs = walrus_sdk::node_client::encode_blobs(unencoded_blobs, None, None)?;
let encoded_sizes = encoded_blobs
.iter()
.map(|blob| {
blob.common
.encoded_size()
.expect("encoded size should be present")
})
.collect::<Vec<_>>();
// Reserve space for the blobs. Collect all original storage resource objects IDs.
let original_storage_resources =
futures::future::join_all(encoded_sizes.iter().map(|encoded_size| async {
let resource = client
.as_ref()
.sui_client()
.reserve_space(*encoded_size, epochs_ahead_registered)
.await
.expect("reserve space should not fail");
resource.id
}))
.await
.into_iter()
.collect::<HashSet<_>>();
// Now ask the client to store again.
// Collect all object IDs of the newly created blob objects.
let store_args =
StoreArgs::default_with_epochs(epochs_ahead_required).with_encoding_type(encoding_type);
let blob_store = client
.inner
.reserve_and_store_blobs(blobs, &store_args)
.await?
.into_iter()
.map(|blob_store_result| match blob_store_result {
BlobStoreResult::NewlyCreated { blob_object, .. } => blob_object.storage.id,
_ => panic!("the client should be able to store the blob"),
})
.collect::<HashSet<_>>();
// Check that the object IDs are the same.
assert!(should_match == (original_storage_resources == blob_store));
Ok(())
}
async_param_test! {
#[ignore = "ignore E2E tests by default"]
#[walrus_simtest]
test_delete_blob -> TestResult : [
no_delete: (0),
one_delete: (1),
multi_delete: (2),
]
}
/// Tests blob object deletion.
async fn test_delete_blob(blobs_to_create: u32) -> TestResult {
walrus_test_utils::init_tracing();
let (_sui_cluster_handle, _cluster, client, _, _) =
test_cluster::E2eTestSetupBuilder::new().build().await?;
let blobs = walrus_test_utils::random_data_list(314, 1);
// Store the blob multiple times, using separate end times to obtain multiple blob objects
// with the same blob ID.
let encoding_type = DEFAULT_ENCODING;
for idx in 1..blobs_to_create + 1 {
let store_args = StoreArgs::default_with_epochs(idx)
.with_encoding_type(encoding_type)
.no_store_optimizations()
.deletable();