forked from PinSpace-Org/GistPin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
886 lines (742 loc) · 29.5 KB
/
Copy pathlib.rs
File metadata and controls
886 lines (742 loc) · 29.5 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
#![no_std]
use soroban_sdk::{
contract, contracterror, contractimpl, contracttype, symbol_short, Address, Env, String,
Symbol, Vec,
};
// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------
/// Lifespan applied when the caller does not supply one.
const DEFAULT_TTL_SECS: u64 = 24 * 60 * 60; // 24 hours
/// Upper bound on a caller-supplied lifespan.
const MAX_TTL_SECS: u64 = 7 * 24 * 60 * 60; // 7 days
/// Minimum gap between two posts by the same author in the same cell.
const COOLDOWN_SECS: u64 = 60;
// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------
#[contracterror]
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[repr(u32)]
pub enum GistError {
/// `ttl_secs` was zero.
TtlZero = 1,
/// `ttl_secs` exceeded `MAX_TTL_SECS`.
TtlTooLong = 2,
/// This author posted in this cell less than `COOLDOWN_SECS` ago.
CooldownActive = 3,
/// No gist exists with the given id.
NotFound = 4,
/// The caller is not permitted to perform this action (not the gist's
/// author, or not the moderator).
NotAuthorized = 5,
/// `initialize` has already been called.
AlreadyInitialized = 6,
/// A moderator action was attempted before `initialize`.
NotInitialized = 7,
/// Anonymous gists have no provable owner, so they cannot be edited or
/// deleted by users — only moderated.
AnonymousImmutable = 8,
}
// ---------------------------------------------------------------------------
// Data types
// ---------------------------------------------------------------------------
#[contracttype]
#[derive(Clone)]
pub struct Gist {
pub gist_id: u64,
pub author: Option<Address>,
pub location_cell: String,
pub content_hash: String,
pub created_at: u64,
/// Ledger timestamp after which this gist is considered expired.
pub expires_at: u64,
/// Set by a moderator to soft-hide the gist. Hidden gists are excluded
/// from listings but remain retrievable via `get_gist`.
pub hidden: bool,
}
// ---------------------------------------------------------------------------
// Storage keys
// ---------------------------------------------------------------------------
#[contracttype]
#[derive(Clone)]
pub enum DataKey {
/// A gist record, keyed by its id.
Gist(u64),
/// Ids of every gist posted in a location cell (secondary index).
CellIndex(String),
/// Last post timestamp for an (author, cell) pair — drives the cooldown.
LastPost(Address, String),
/// The moderator address, set once via `initialize`.
Admin,
/// Number of reports filed against a gist (advisory, for off-chain review).
Reports(u64),
}
const GIST_COUNT: Symbol = symbol_short!("GCOUNT");
// ---------------------------------------------------------------------------
// Contract
// ---------------------------------------------------------------------------
#[contract]
pub struct GistRegistry;
#[contractimpl]
impl GistRegistry {
/// Register a new gist on-chain and return its assigned `gist_id`.
///
/// Authorship:
/// * `author = Some(addr)` — a *signed* post. `addr.require_auth()` is
/// enforced, so a gist can never be attributed to an address that did
/// not authorize the call. Signed posts are also cooldown-limited.
/// * `author = None` — an *anonymous* post. No authorization is required
/// and no cooldown applies (there is no on-chain identity to rate-limit;
/// anonymous abuse is handled off-chain by the API layer).
///
/// Lifespan: `ttl_secs` defaults to [`DEFAULT_TTL_SECS`] and must be in
/// `1..=MAX_TTL_SECS`.
pub fn post_gist(
env: Env,
author: Option<Address>,
location_cell: String,
content_hash: String,
ttl_secs: Option<u64>,
) -> Result<u64, GistError> {
let now = env.ledger().timestamp();
// --- lifespan bounds (#876) ---------------------------------------
let ttl = ttl_secs.unwrap_or(DEFAULT_TTL_SECS);
if ttl == 0 {
return Err(GistError::TtlZero);
}
if ttl > MAX_TTL_SECS {
return Err(GistError::TtlTooLong);
}
let expires_at = now.checked_add(ttl).ok_or(GistError::TtlTooLong)?;
// --- signed authorship (#874) + cooldown (#877) --------------------
if let Some(addr) = author.clone() {
// A forged author cannot pass this: the transaction must carry an
// authorization entry for `addr`.
addr.require_auth();
let last_key = DataKey::LastPost(addr, location_cell.clone());
if let Some(last) = env.storage().persistent().get::<DataKey, u64>(&last_key) {
if now < last.saturating_add(COOLDOWN_SECS) {
return Err(GistError::CooldownActive);
}
}
env.storage().persistent().set(&last_key, &now);
}
let gist_id: u64 = env
.storage()
.instance()
.get(&GIST_COUNT)
.unwrap_or(0u64)
+ 1;
let gist = Gist {
gist_id,
author,
location_cell: location_cell.clone(),
content_hash,
created_at: now,
expires_at,
hidden: false,
};
env.storage().persistent().set(&DataKey::Gist(gist_id), &gist);
env.storage().instance().set(&GIST_COUNT, &gist_id);
// --- secondary index by cell (#875) --------------------------------
// Keeps `list_gists_by_cell` proportional to the results in the cell
// instead of scanning every gist ever posted.
let idx_key = DataKey::CellIndex(location_cell);
let mut ids: Vec<u64> = env
.storage()
.persistent()
.get(&idx_key)
.unwrap_or_else(|| Vec::new(&env));
ids.push_back(gist_id);
env.storage().persistent().set(&idx_key, &ids);
// Canonical event consumed by the off-chain indexer.
env.events()
.publish((Symbol::new(&env, "gist_posted"),), gist);
Ok(gist_id)
}
/// Retrieve a gist record by id. Expired gists are still returned so that
/// callers can inspect them; use [`Self::is_active`] to test expiry.
pub fn get_gist(env: Env, gist_id: u64) -> Option<Gist> {
env.storage().persistent().get(&DataKey::Gist(gist_id))
}
/// Whether a gist exists, has not expired, and has not been hidden by a
/// moderator.
pub fn is_active(env: Env, gist_id: u64) -> bool {
match env
.storage()
.persistent()
.get::<DataKey, Gist>(&DataKey::Gist(gist_id))
{
Some(gist) => !gist.hidden && env.ledger().timestamp() < gist.expires_at,
None => false,
}
}
/// Paginated list of the *active* (non-expired) gists in a location cell.
///
/// `cursor` is a zero-based offset into the cell's index (not a gist id);
/// `limit` caps the number of results returned.
pub fn list_gists_by_cell(
env: Env,
location_cell: String,
cursor: u32,
limit: u32,
) -> Vec<Gist> {
let ids: Vec<u64> = env
.storage()
.persistent()
.get(&DataKey::CellIndex(location_cell))
.unwrap_or_else(|| Vec::new(&env));
let now = env.ledger().timestamp();
let mut results = Vec::new(&env);
let mut count: u32 = 0;
let mut i = cursor;
while i < ids.len() && count < limit {
if let Some(id) = ids.get(i) {
if let Some(gist) = env
.storage()
.persistent()
.get::<DataKey, Gist>(&DataKey::Gist(id))
{
if !gist.hidden && now < gist.expires_at {
results.push_back(gist);
count += 1;
}
}
}
i += 1;
}
results
}
// -----------------------------------------------------------------------
// Moderation (#878)
// -----------------------------------------------------------------------
/// Set the moderator address. Callable exactly once, at deploy time.
///
/// Posting works without initialization; only moderator actions require it.
pub fn initialize(env: Env, admin: Address) -> Result<(), GistError> {
if env.storage().instance().has(&DataKey::Admin) {
return Err(GistError::AlreadyInitialized);
}
env.storage().instance().set(&DataKey::Admin, &admin);
Ok(())
}
/// The configured moderator, if `initialize` has been called.
pub fn get_admin(env: Env) -> Option<Address> {
env.storage().instance().get(&DataKey::Admin)
}
/// Soft-hide a gist. Moderator only.
///
/// Hidden gists are excluded from `list_gists_by_cell` and report
/// `is_active == false`, but remain retrievable via `get_gist` (with
/// `hidden == true`) so moderation stays auditable. Reversible via
/// [`Self::unhide_gist`].
pub fn hide_gist(env: Env, gist_id: u64) -> Result<(), GistError> {
Self::require_admin(&env)?;
Self::set_hidden(&env, gist_id, true)?;
env.events()
.publish((Symbol::new(&env, "gist_hidden"),), gist_id);
Ok(())
}
/// Reverse a previous [`Self::hide_gist`]. Moderator only.
pub fn unhide_gist(env: Env, gist_id: u64) -> Result<(), GistError> {
Self::require_admin(&env)?;
Self::set_hidden(&env, gist_id, false)?;
env.events()
.publish((Symbol::new(&env, "gist_unhidden"),), gist_id);
Ok(())
}
/// Permanently delete a gist. Moderator only.
///
/// Prefer [`Self::hide_gist`] unless the content must not persist —
/// removal is irreversible and leaves no record beyond the event.
pub fn remove_gist(env: Env, gist_id: u64) -> Result<(), GistError> {
Self::require_admin(&env)?;
if !env.storage().persistent().has(&DataKey::Gist(gist_id)) {
return Err(GistError::NotFound);
}
env.storage().persistent().remove(&DataKey::Gist(gist_id));
env.events()
.publish((Symbol::new(&env, "gist_removed"),), gist_id);
Ok(())
}
/// Flag a gist for off-chain review. Callable by anyone; advisory only —
/// it never hides content on its own.
pub fn report_gist(env: Env, gist_id: u64) -> Result<u32, GistError> {
if !env.storage().persistent().has(&DataKey::Gist(gist_id)) {
return Err(GistError::NotFound);
}
let key = DataKey::Reports(gist_id);
let count: u32 = env.storage().persistent().get(&key).unwrap_or(0) + 1;
env.storage().persistent().set(&key, &count);
env.events()
.publish((Symbol::new(&env, "gist_reported"),), (gist_id, count));
Ok(count)
}
/// Number of reports filed against a gist.
pub fn report_count(env: Env, gist_id: u64) -> u32 {
env.storage()
.persistent()
.get(&DataKey::Reports(gist_id))
.unwrap_or(0)
}
// -----------------------------------------------------------------------
// Author edit / delete (#879)
// -----------------------------------------------------------------------
/// Replace a gist's content pointer. Original author only.
///
/// Anonymous gists cannot be edited — there is no provable owner.
pub fn edit_gist(env: Env, gist_id: u64, new_content_hash: String) -> Result<(), GistError> {
let mut gist = Self::load_authored(&env, gist_id)?;
gist.content_hash = new_content_hash;
env.storage().persistent().set(&DataKey::Gist(gist_id), &gist);
env.events()
.publish((Symbol::new(&env, "gist_edited"),), gist);
Ok(())
}
/// Delete your own gist. Original author only.
///
/// Anonymous gists cannot be deleted by users — only moderated.
pub fn delete_gist(env: Env, gist_id: u64) -> Result<(), GistError> {
Self::load_authored(&env, gist_id)?;
env.storage().persistent().remove(&DataKey::Gist(gist_id));
env.events()
.publish((Symbol::new(&env, "gist_deleted"),), gist_id);
Ok(())
}
// -----------------------------------------------------------------------
// Internal helpers
// -----------------------------------------------------------------------
/// Require that the call is authorized by the configured moderator.
fn require_admin(env: &Env) -> Result<(), GistError> {
let admin: Address = env
.storage()
.instance()
.get(&DataKey::Admin)
.ok_or(GistError::NotInitialized)?;
admin.require_auth();
Ok(())
}
/// Load a gist, requiring that the call is authorized by its author.
fn load_authored(env: &Env, gist_id: u64) -> Result<Gist, GistError> {
let gist: Gist = env
.storage()
.persistent()
.get(&DataKey::Gist(gist_id))
.ok_or(GistError::NotFound)?;
match gist.author.clone() {
// A different address cannot pass this: the transaction must carry
// an authorization entry for the stored author.
Some(author) => author.require_auth(),
None => return Err(GistError::AnonymousImmutable),
}
Ok(gist)
}
/// Set the `hidden` flag on an existing gist.
fn set_hidden(env: &Env, gist_id: u64, hidden: bool) -> Result<(), GistError> {
let mut gist: Gist = env
.storage()
.persistent()
.get(&DataKey::Gist(gist_id))
.ok_or(GistError::NotFound)?;
gist.hidden = hidden;
env.storage().persistent().set(&DataKey::Gist(gist_id), &gist);
Ok(())
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use soroban_sdk::testutils::{Address as _, Events, Ledger};
use soroban_sdk::{Env, String};
fn setup(env: &Env) -> GistRegistryClient<'_> {
let contract_id = env.register(GistRegistry, ());
GistRegistryClient::new(env, &contract_id)
}
fn cell(env: &Env, s: &str) -> String {
String::from_str(env, s)
}
// -- posting / retrieval -------------------------------------------------
#[test]
fn anonymous_post_succeeds_and_is_retrievable() {
let env = Env::default();
let client = setup(&env);
env.ledger().set_timestamp(1_000_000);
let location = cell(&env, "r3gx");
let hash = cell(&env, "QmTest123");
let id = client.post_gist(&None, &location, &hash, &None);
assert_eq!(id, 1);
let gist = client.get_gist(&id).expect("gist should exist");
assert_eq!(gist.gist_id, 1);
assert_eq!(gist.location_cell, location);
assert_eq!(gist.content_hash, hash);
assert_eq!(gist.created_at, 1_000_000);
// default TTL applied
assert_eq!(gist.expires_at, 1_000_000 + DEFAULT_TTL_SECS);
assert!(gist.author.is_none());
}
#[test]
fn post_gist_emits_one_event() {
let env = Env::default();
let client = setup(&env);
client.post_gist(&None, &cell(&env, "r3gx"), &cell(&env, "QmEvent"), &None);
assert_eq!(env.events().all().len(), 1);
}
// -- signed authorship (#874) -------------------------------------------
#[test]
fn signed_post_records_the_author() {
let env = Env::default();
env.mock_all_auths();
let client = setup(&env);
let author = Address::generate(&env);
let id = client.post_gist(
&Some(author.clone()),
&cell(&env, "r3gx"),
&cell(&env, "QmSigned"),
&None,
);
let gist = client.get_gist(&id).unwrap();
assert_eq!(gist.author, Some(author));
}
#[test]
#[should_panic]
fn signed_post_without_authorization_is_rejected() {
let env = Env::default();
// NOTE: no mock_all_auths() — the required authorization is absent, so
// require_auth must reject the call (a forged author cannot post).
let client = setup(&env);
let author = Address::generate(&env);
client.post_gist(
&Some(author),
&cell(&env, "r3gx"),
&cell(&env, "QmForged"),
&None,
);
}
// -- expiry (#876) -------------------------------------------------------
#[test]
fn gist_is_active_before_expiry_and_inactive_after() {
let env = Env::default();
let client = setup(&env);
env.ledger().set_timestamp(1_000);
let id = client.post_gist(
&None,
&cell(&env, "r3gx"),
&cell(&env, "QmTtl"),
&Some(100u64),
);
assert!(client.is_active(&id));
env.ledger().set_timestamp(1_000 + 101);
assert!(!client.is_active(&id));
// the record itself is still retrievable
assert!(client.get_gist(&id).is_some());
}
#[test]
fn expired_gists_are_excluded_from_listings() {
let env = Env::default();
let client = setup(&env);
env.ledger().set_timestamp(1_000);
let location = cell(&env, "r3gx");
client.post_gist(&None, &location, &cell(&env, "QmShort"), &Some(50u64));
client.post_gist(&None, &location, &cell(&env, "QmLong"), &Some(5_000u64));
assert_eq!(client.list_gists_by_cell(&location, &0, &10).len(), 2);
env.ledger().set_timestamp(1_000 + 100); // first one expired
let active = client.list_gists_by_cell(&location, &0, &10);
assert_eq!(active.len(), 1);
assert_eq!(active.get(0).unwrap().content_hash, cell(&env, "QmLong"));
}
#[test]
fn ttl_bounds_are_enforced() {
let env = Env::default();
let client = setup(&env);
let location = cell(&env, "r3gx");
let hash = cell(&env, "QmBound");
assert_eq!(
client.try_post_gist(&None, &location, &hash, &Some(0u64)),
Err(Ok(GistError::TtlZero))
);
assert_eq!(
client.try_post_gist(&None, &location, &hash, &Some(MAX_TTL_SECS + 1)),
Err(Ok(GistError::TtlTooLong))
);
// the upper bound itself is accepted
assert!(client
.try_post_gist(&None, &location, &hash, &Some(MAX_TTL_SECS))
.is_ok());
}
// -- cooldown (#877) -----------------------------------------------------
#[test]
fn same_author_cannot_post_twice_in_a_cell_within_the_cooldown() {
let env = Env::default();
env.mock_all_auths();
let client = setup(&env);
env.ledger().set_timestamp(10_000);
let author = Address::generate(&env);
let location = cell(&env, "r3gx");
client.post_gist(&Some(author.clone()), &location, &cell(&env, "Qm1"), &None);
assert_eq!(
client.try_post_gist(&Some(author), &location, &cell(&env, "Qm2"), &None),
Err(Ok(GistError::CooldownActive))
);
}
#[test]
fn cooldown_expires_and_other_cells_are_unaffected() {
let env = Env::default();
env.mock_all_auths();
let client = setup(&env);
env.ledger().set_timestamp(10_000);
let author = Address::generate(&env);
let cell_a = cell(&env, "r3gx");
let cell_b = cell(&env, "u4ht");
client.post_gist(&Some(author.clone()), &cell_a, &cell(&env, "Qm1"), &None);
// a different cell is not blocked
assert!(client
.try_post_gist(&Some(author.clone()), &cell_b, &cell(&env, "Qm2"), &None)
.is_ok());
// once the window elapses, the original cell is allowed again
env.ledger().set_timestamp(10_000 + COOLDOWN_SECS);
assert!(client
.try_post_gist(&Some(author), &cell_a, &cell(&env, "Qm3"), &None)
.is_ok());
}
#[test]
fn anonymous_posts_are_not_cooldown_limited() {
let env = Env::default();
let client = setup(&env);
env.ledger().set_timestamp(10_000);
let location = cell(&env, "r3gx");
client.post_gist(&None, &location, &cell(&env, "Qm1"), &None);
client.post_gist(&None, &location, &cell(&env, "Qm2"), &None);
assert_eq!(client.list_gists_by_cell(&location, &0, &10).len(), 2);
}
// -- cell index / pagination (#875) --------------------------------------
#[test]
fn listing_returns_only_the_requested_cell() {
let env = Env::default();
let client = setup(&env);
let cell_a = cell(&env, "r3gx");
let cell_b = cell(&env, "u4ht");
let hash = cell(&env, "Qm000");
client.post_gist(&None, &cell_a, &hash, &None);
client.post_gist(&None, &cell_b, &hash, &None);
client.post_gist(&None, &cell_a, &hash, &None);
assert_eq!(client.list_gists_by_cell(&cell_a, &0, &10).len(), 2);
assert_eq!(client.list_gists_by_cell(&cell_b, &0, &10).len(), 1);
}
#[test]
fn listing_paginates_by_cursor_and_limit() {
let env = Env::default();
let client = setup(&env);
let location = cell(&env, "r3gx");
for _ in 0..5 {
client.post_gist(&None, &location, &cell(&env, "Qm"), &None);
}
let page1 = client.list_gists_by_cell(&location, &0, &2);
assert_eq!(page1.len(), 2);
assert_eq!(page1.get(0).unwrap().gist_id, 1);
assert_eq!(page1.get(1).unwrap().gist_id, 2);
let page2 = client.list_gists_by_cell(&location, &2, &2);
assert_eq!(page2.len(), 2);
assert_eq!(page2.get(0).unwrap().gist_id, 3);
let page3 = client.list_gists_by_cell(&location, &4, &2);
assert_eq!(page3.len(), 1);
}
#[test]
fn listing_an_unknown_cell_is_empty() {
let env = Env::default();
let client = setup(&env);
assert_eq!(client.list_gists_by_cell(&cell(&env, "nope"), &0, &10).len(), 0);
}
// -- initialization / moderator (#878) -----------------------------------
#[test]
fn initialize_sets_the_admin_once() {
let env = Env::default();
env.mock_all_auths();
let client = setup(&env);
let admin = Address::generate(&env);
assert!(client.get_admin().is_none());
client.initialize(&admin);
assert_eq!(client.get_admin(), Some(admin.clone()));
assert_eq!(
client.try_initialize(&admin),
Err(Ok(GistError::AlreadyInitialized))
);
}
#[test]
fn moderation_before_initialize_is_rejected() {
let env = Env::default();
env.mock_all_auths();
let client = setup(&env);
let id = client.post_gist(&None, &cell(&env, "r3gx"), &cell(&env, "Qm1"), &None);
assert_eq!(
client.try_hide_gist(&id),
Err(Ok(GistError::NotInitialized))
);
}
#[test]
fn moderator_can_hide_and_unhide_a_gist() {
let env = Env::default();
env.mock_all_auths();
let client = setup(&env);
client.initialize(&Address::generate(&env));
let location = cell(&env, "r3gx");
let id = client.post_gist(&None, &location, &cell(&env, "Qm1"), &None);
assert!(client.is_active(&id));
client.hide_gist(&id);
// excluded from listings and inactive, but still auditable
assert_eq!(client.list_gists_by_cell(&location, &0, &10).len(), 0);
assert!(!client.is_active(&id));
let gist = client.get_gist(&id).expect("hidden gist is still retrievable");
assert!(gist.hidden);
client.unhide_gist(&id);
assert!(client.is_active(&id));
assert_eq!(client.list_gists_by_cell(&location, &0, &10).len(), 1);
}
#[test]
#[should_panic]
fn hiding_without_moderator_authorization_is_rejected() {
let env = Env::default();
env.mock_all_auths();
let client = setup(&env);
client.initialize(&Address::generate(&env));
let id = client.post_gist(&None, &cell(&env, "r3gx"), &cell(&env, "Qm1"), &None);
// Drop the mocked authorizations: the admin's require_auth can no
// longer be satisfied, so moderation must fail.
env.set_auths(&[]);
client.hide_gist(&id);
}
#[test]
fn moderator_can_remove_a_gist_permanently() {
let env = Env::default();
env.mock_all_auths();
let client = setup(&env);
client.initialize(&Address::generate(&env));
let location = cell(&env, "r3gx");
let id = client.post_gist(&None, &location, &cell(&env, "Qm1"), &None);
client.remove_gist(&id);
assert!(client.get_gist(&id).is_none());
assert!(!client.is_active(&id));
assert_eq!(client.list_gists_by_cell(&location, &0, &10).len(), 0);
// removing again reports NotFound
assert_eq!(client.try_remove_gist(&id), Err(Ok(GistError::NotFound)));
}
#[test]
fn moderating_an_unknown_gist_reports_not_found() {
let env = Env::default();
env.mock_all_auths();
let client = setup(&env);
client.initialize(&Address::generate(&env));
assert_eq!(client.try_hide_gist(&999), Err(Ok(GistError::NotFound)));
}
// -- reporting (#878, advisory) -----------------------------------------
#[test]
fn anyone_can_report_and_reports_accumulate() {
let env = Env::default();
let client = setup(&env);
let location = cell(&env, "r3gx");
let id = client.post_gist(&None, &location, &cell(&env, "Qm1"), &None);
assert_eq!(client.report_count(&id), 0);
assert_eq!(client.report_gist(&id), 1);
assert_eq!(client.report_gist(&id), 2);
assert_eq!(client.report_count(&id), 2);
// reporting is advisory — it must not hide the gist on its own
assert!(client.is_active(&id));
assert_eq!(client.list_gists_by_cell(&location, &0, &10).len(), 1);
assert_eq!(client.try_report_gist(&999), Err(Ok(GistError::NotFound)));
}
// -- author edit / delete (#879) ----------------------------------------
#[test]
fn author_can_edit_their_own_gist() {
let env = Env::default();
env.mock_all_auths();
let client = setup(&env);
let author = Address::generate(&env);
let id = client.post_gist(
&Some(author),
&cell(&env, "r3gx"),
&cell(&env, "QmOld"),
&None,
);
client.edit_gist(&id, &cell(&env, "QmNew"));
let gist = client.get_gist(&id).unwrap();
assert_eq!(gist.content_hash, cell(&env, "QmNew"));
// metadata is preserved
assert_eq!(gist.gist_id, id);
}
#[test]
fn author_can_delete_their_own_gist() {
let env = Env::default();
env.mock_all_auths();
let client = setup(&env);
let author = Address::generate(&env);
let location = cell(&env, "r3gx");
let id = client.post_gist(&Some(author), &location, &cell(&env, "Qm1"), &None);
client.delete_gist(&id);
assert!(client.get_gist(&id).is_none());
assert_eq!(client.list_gists_by_cell(&location, &0, &10).len(), 0);
}
#[test]
#[should_panic]
fn a_different_address_cannot_edit_someone_elses_gist() {
let env = Env::default();
env.mock_all_auths();
let client = setup(&env);
let author = Address::generate(&env);
let id = client.post_gist(
&Some(author),
&cell(&env, "r3gx"),
&cell(&env, "QmOld"),
&None,
);
// Without the author's authorization the edit must be rejected.
env.set_auths(&[]);
client.edit_gist(&id, &cell(&env, "QmHijacked"));
}
#[test]
fn anonymous_gists_cannot_be_edited_or_deleted() {
let env = Env::default();
env.mock_all_auths();
let client = setup(&env);
let id = client.post_gist(&None, &cell(&env, "r3gx"), &cell(&env, "Qm1"), &None);
assert_eq!(
client.try_edit_gist(&id, &cell(&env, "QmNew")),
Err(Ok(GistError::AnonymousImmutable))
);
assert_eq!(
client.try_delete_gist(&id),
Err(Ok(GistError::AnonymousImmutable))
);
}
#[test]
fn editing_an_unknown_gist_reports_not_found() {
let env = Env::default();
env.mock_all_auths();
let client = setup(&env);
assert_eq!(
client.try_edit_gist(&999, &cell(&env, "QmNew")),
Err(Ok(GistError::NotFound))
);
assert_eq!(client.try_delete_gist(&999), Err(Ok(GistError::NotFound)));
}
// -- interaction between features ---------------------------------------
#[test]
fn moderation_and_expiry_are_independent() {
let env = Env::default();
env.mock_all_auths();
let client = setup(&env);
client.initialize(&Address::generate(&env));
env.ledger().set_timestamp(1_000);
let location = cell(&env, "r3gx");
let id = client.post_gist(&None, &location, &cell(&env, "Qm1"), &Some(100u64));
client.hide_gist(&id);
assert!(!client.is_active(&id));
// unhiding an expired gist does not resurrect it
env.ledger().set_timestamp(1_000 + 500);
client.unhide_gist(&id);
assert!(!client.is_active(&id));
assert_eq!(client.list_gists_by_cell(&location, &0, &10).len(), 0);
}
}