forked from CredenceOrg/Credence-Contracts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththeirs.rs
More file actions
690 lines (590 loc) · 22 KB
/
Copy paththeirs.rs
File metadata and controls
690 lines (590 loc) · 22 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
#![no_std]
use soroban_sdk::{
contract, contractimpl, contracttype, Address, Env, IntoVal, String, Symbol, Val, Vec,
};
mod early_exit_penalty;
mod rolling_bond;
mod tiered_bond;
#[contracttype]
#[derive(Clone, Debug)]
pub struct IdentityBond {
pub identity: Address,
pub bonded_amount: i128,
pub bond_start: u64,
pub bond_duration: u64,
pub slashed_amount: i128,
pub active: bool,
pub is_rolling: bool,
pub withdrawal_requested_at: u64,
pub notice_period: u64,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Attestation {
pub id: u64,
pub attester: Address,
pub subject: Address,
pub attestation_data: String,
pub timestamp: u64,
pub revoked: bool,
}
#[contracttype]
pub enum DataKey {
Admin,
Bond,
Attester(Address),
Attestation(u64),
AttestationCounter,
SubjectAttestations(Address),
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum BondTier {
Bronze,
Silver,
Gold,
Platinum,
}
#[contract]
pub struct CredenceBond;
#[contractimpl]
impl CredenceBond {
/// Initialize the contract (set admin).
pub fn initialize(e: Env, admin: Address) {
e.storage().instance().set(&DataKey::Admin, &admin);
}
/// Set early exit penalty config (admin only). Penalty in basis points (e.g. 500 = 5%).
pub fn set_early_exit_config(e: Env, admin: Address, treasury: Address, penalty_bps: u32) {
let stored_admin: Address = e
.storage()
.instance()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic!("not initialized"));
admin.require_auth();
if admin != stored_admin {
panic!("not admin");
}
early_exit_penalty::set_config(&e, treasury, penalty_bps);
}
/// Register an authorized attester (only admin can call).
pub fn register_attester(e: Env, attester: Address) {
let admin: Address = e
.storage()
.instance()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic!("not initialized"));
admin.require_auth();
e.storage()
.instance()
.set(&DataKey::Attester(attester.clone()), &true);
e.events()
.publish((Symbol::new(&e, "attester_registered"),), attester);
}
/// Remove an attester's authorization (only admin can call).
pub fn unregister_attester(e: Env, attester: Address) {
let admin: Address = e
.storage()
.instance()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic!("not initialized"));
admin.require_auth();
e.storage()
.instance()
.remove(&DataKey::Attester(attester.clone()));
e.events()
.publish((Symbol::new(&e, "attester_unregistered"),), attester);
}
/// Check if an address is an authorized attester.
pub fn is_attester(e: Env, attester: Address) -> bool {
e.storage()
.instance()
.get(&DataKey::Attester(attester))
.unwrap_or(false)
}
/// Create or top-up a bond for an identity (non-rolling helper).
pub fn create_bond(e: Env, identity: Address, amount: i128, duration: u64) -> IdentityBond {
Self::create_bond_with_rolling(e, identity, amount, duration, false, 0)
}
/// Create a bond with rolling parameters.
pub fn create_bond_with_rolling(
e: Env,
identity: Address,
amount: i128,
duration: u64,
is_rolling: bool,
notice_period: u64,
) -> IdentityBond {
let bond_start = e.ledger().timestamp();
let _end_timestamp = bond_start
.checked_add(duration)
.expect("bond end timestamp would overflow");
let bond = IdentityBond {
identity: identity.clone(),
bonded_amount: amount,
bond_start,
bond_duration: duration,
slashed_amount: 0,
active: true,
is_rolling,
withdrawal_requested_at: 0,
notice_period,
};
let key = DataKey::Bond;
e.storage().instance().set(&key, &bond);
bond
}
/// Return current bond state for an identity (simplified: single bond per contract instance).
pub fn get_identity_state(e: Env) -> IdentityBond {
e.storage()
.instance()
.get::<_, IdentityBond>(&DataKey::Bond)
.unwrap_or_else(|| panic!("no bond"))
}
/// Add an attestation for a subject (only authorized attesters can call).
pub fn add_attestation(
e: Env,
attester: Address,
subject: Address,
attestation_data: String,
) -> Attestation {
attester.require_auth();
// Verify attester is authorized
let is_authorized = e
.storage()
.instance()
.get(&DataKey::Attester(attester.clone()))
.unwrap_or(false);
if !is_authorized {
panic!("unauthorized attester");
}
// Get and increment attestation counter
let counter_key = DataKey::AttestationCounter;
let id: u64 = e.storage().instance().get(&counter_key).unwrap_or(0);
let next_id = id.checked_add(1).expect("attestation counter overflow");
e.storage().instance().set(&counter_key, &next_id);
// Create attestation
let attestation = Attestation {
id,
attester: attester.clone(),
subject: subject.clone(),
attestation_data: attestation_data.clone(),
timestamp: e.ledger().timestamp(),
revoked: false,
};
// Store attestation
e.storage()
.instance()
.set(&DataKey::Attestation(id), &attestation);
// Add to subject's attestation list
let subject_key = DataKey::SubjectAttestations(subject.clone());
let mut attestations: Vec<u64> = e
.storage()
.instance()
.get(&subject_key)
.unwrap_or(Vec::new(&e));
attestations.push_back(id);
e.storage().instance().set(&subject_key, &attestations);
// Emit event
e.events().publish(
(Symbol::new(&e, "attestation_added"), subject),
(id, attester, attestation_data),
);
attestation
}
/// Revoke an attestation (only the original attester can revoke).
pub fn revoke_attestation(e: Env, attester: Address, attestation_id: u64) {
attester.require_auth();
// Get attestation
let key = DataKey::Attestation(attestation_id);
let mut attestation: Attestation = e
.storage()
.instance()
.get(&key)
.unwrap_or_else(|| panic!("attestation not found"));
// Verify attester is the original attester
if attestation.attester != attester {
panic!("only original attester can revoke");
}
// Check if already revoked
if attestation.revoked {
panic!("attestation already revoked");
}
// Mark as revoked
attestation.revoked = true;
e.storage().instance().set(&key, &attestation);
// Emit event
e.events().publish(
(
Symbol::new(&e, "attestation_revoked"),
attestation.subject.clone(),
),
(attestation_id, attester),
);
}
/// Get an attestation by ID.
pub fn get_attestation(e: Env, attestation_id: u64) -> Attestation {
e.storage()
.instance()
.get(&DataKey::Attestation(attestation_id))
.unwrap_or_else(|| panic!("attestation not found"))
}
/// Get all attestation IDs for a subject.
pub fn get_subject_attestations(e: Env, subject: Address) -> Vec<u64> {
e.storage()
.instance()
.get(&DataKey::SubjectAttestations(subject))
.unwrap_or(Vec::new(&e))
}
/// Withdraw from bond. Checks that the bond has sufficient balance after accounting for slashed amount.
/// Returns the updated bond with reduced bonded_amount.
pub fn withdraw(e: Env, amount: i128) -> IdentityBond {
let key = DataKey::Bond;
let mut bond = e
.storage()
.instance()
.get::<_, IdentityBond>(&key)
.unwrap_or_else(|| panic!("no bond"));
// Calculate available balance (bonded - slashed)
let available = bond
.bonded_amount
.checked_sub(bond.slashed_amount)
.expect("slashed amount exceeds bonded amount");
// Verify sufficient available balance for withdrawal
if amount > available {
panic!("insufficient balance for withdrawal");
}
// Perform withdrawal with overflow protection
bond.bonded_amount = bond
.bonded_amount
.checked_sub(amount)
.expect("withdrawal caused underflow");
// Verify invariant: slashed amount should not exceed bonded amount after withdrawal
if bond.slashed_amount > bond.bonded_amount {
panic!("slashed amount exceeds bonded amount");
}
let old_tier = tiered_bond::get_tier_for_amount(bond.bonded_amount + amount);
let new_tier = tiered_bond::get_tier_for_amount(bond.bonded_amount);
tiered_bond::emit_tier_change_if_needed(&e, &bond.identity, old_tier, new_tier);
e.storage().instance().set(&key, &bond);
bond
}
/// Withdraw before lock-up end; applies early exit penalty and transfers penalty to treasury.
/// Net amount to user = amount - penalty. Use when lock-up has not yet ended.
pub fn withdraw_early(e: Env, amount: i128) -> IdentityBond {
let key = DataKey::Bond;
let mut bond = e
.storage()
.instance()
.get::<_, IdentityBond>(&key)
.unwrap_or_else(|| panic!("no bond"));
let available = bond
.bonded_amount
.checked_sub(bond.slashed_amount)
.expect("slashed amount exceeds bonded amount");
if amount > available {
panic!("insufficient balance for withdrawal");
}
let now = e.ledger().timestamp();
let end = bond.bond_start.saturating_add(bond.bond_duration);
if now >= end {
panic!("use withdraw for post lock-up");
}
let (treasury, penalty_bps) = early_exit_penalty::get_config(&e);
let remaining = end.saturating_sub(now);
let penalty = early_exit_penalty::calculate_penalty(
amount,
remaining,
bond.bond_duration,
penalty_bps,
);
early_exit_penalty::emit_penalty_event(&e, &bond.identity, amount, penalty, &treasury);
let old_tier = tiered_bond::get_tier_for_amount(bond.bonded_amount);
bond.bonded_amount = bond
.bonded_amount
.checked_sub(amount)
.expect("withdrawal caused underflow");
if bond.slashed_amount > bond.bonded_amount {
panic!("slashed amount exceeds bonded amount");
}
let new_tier = tiered_bond::get_tier_for_amount(bond.bonded_amount);
tiered_bond::emit_tier_change_if_needed(&e, &bond.identity, old_tier, new_tier);
e.storage().instance().set(&key, &bond);
bond
}
/// Request withdrawal (rolling bonds). Withdrawal allowed after notice period.
pub fn request_withdrawal(e: Env) -> IdentityBond {
let key = DataKey::Bond;
let mut bond = e
.storage()
.instance()
.get::<_, IdentityBond>(&key)
.unwrap_or_else(|| panic!("no bond"));
if !bond.is_rolling {
panic!("not a rolling bond");
}
if bond.withdrawal_requested_at != 0 {
panic!("withdrawal already requested");
}
bond.withdrawal_requested_at = e.ledger().timestamp();
e.storage().instance().set(&key, &bond);
e.events().publish(
(Symbol::new(&e, "withdrawal_requested"),),
(bond.identity.clone(), bond.withdrawal_requested_at),
);
bond
}
/// If bond is rolling and period has ended, renew (new period start = now). Emits renewal event.
pub fn renew_if_rolling(e: Env) -> IdentityBond {
let key = DataKey::Bond;
let mut bond = e
.storage()
.instance()
.get::<_, IdentityBond>(&key)
.unwrap_or_else(|| panic!("no bond"));
if !bond.is_rolling {
return bond;
}
let now = e.ledger().timestamp();
if !rolling_bond::is_period_ended(now, bond.bond_start, bond.bond_duration) {
return bond;
}
rolling_bond::apply_renewal(&mut bond, now);
e.storage().instance().set(&key, &bond);
e.events().publish(
(Symbol::new(&e, "bond_renewed"),),
(bond.identity.clone(), bond.bond_start, bond.bond_duration),
);
bond
}
/// Get current tier for the bond's bonded amount.
pub fn get_tier(e: Env) -> BondTier {
let bond = Self::get_identity_state(e);
tiered_bond::get_tier_for_amount(bond.bonded_amount)
}
/// Slash a portion of the bond. Increases slashed_amount up to the bonded_amount.
/// Returns the updated bond with increased slashed_amount.
pub fn slash(e: Env, amount: i128) -> IdentityBond {
let key = DataKey::Bond;
let mut bond = e
.storage()
.instance()
.get::<_, IdentityBond>(&key)
.unwrap_or_else(|| panic!("no bond"));
// Calculate new slashed amount, checking for overflow
let new_slashed = bond
.slashed_amount
.checked_add(amount)
.expect("slashing caused overflow");
// Cap slashed amount at bonded amount
bond.slashed_amount = if new_slashed > bond.bonded_amount {
bond.bonded_amount
} else {
new_slashed
};
e.storage().instance().set(&key, &bond);
bond
}
/// Top up the bond with additional amount (checks for overflow)
pub fn top_up(e: Env, amount: i128) -> IdentityBond {
let key = DataKey::Bond;
let mut bond = e
.storage()
.instance()
.get::<_, IdentityBond>(&key)
.unwrap_or_else(|| panic!("no bond"));
// Perform top-up with overflow protection
let old_tier = tiered_bond::get_tier_for_amount(bond.bonded_amount);
bond.bonded_amount = bond
.bonded_amount
.checked_add(amount)
.expect("top-up caused overflow");
let new_tier = tiered_bond::get_tier_for_amount(bond.bonded_amount);
tiered_bond::emit_tier_change_if_needed(&e, &bond.identity, old_tier, new_tier);
e.storage().instance().set(&key, &bond);
bond
}
/// Extend bond duration (checks for u64 overflow on timestamps)
pub fn extend_duration(e: Env, additional_duration: u64) -> IdentityBond {
let key = DataKey::Bond;
let mut bond = e
.storage()
.instance()
.get::<_, IdentityBond>(&key)
.unwrap_or_else(|| panic!("no bond"));
// Perform duration extension with overflow protection
bond.bond_duration = bond
.bond_duration
.checked_add(additional_duration)
.expect("duration extension caused overflow");
// Also verify the end timestamp wouldn't overflow
let _end_timestamp = bond
.bond_start
.checked_add(bond.bond_duration)
.expect("bond end timestamp would overflow");
e.storage().instance().set(&key, &bond);
bond
}
/// Deposit fees into the contract's fee pool.
pub fn deposit_fees(e: Env, amount: i128) {
let key = Symbol::new(&e, "fees");
let current: i128 = e.storage().instance().get(&key).unwrap_or(0);
e.storage().instance().set(&key, &(current + amount));
}
/// Withdraw the full bonded amount back to the identity.
/// Uses a reentrancy guard to prevent re-entrance during external calls.
pub fn withdraw_bond(e: Env, identity: Address) -> i128 {
identity.require_auth();
Self::acquire_lock(&e);
let bond_key = DataKey::Bond;
let bond: IdentityBond = e
.storage()
.instance()
.get(&bond_key)
.unwrap_or_else(|| panic!("no bond"));
if bond.identity != identity {
Self::release_lock(&e);
panic!("not bond owner");
}
if !bond.active {
Self::release_lock(&e);
panic!("bond not active");
}
let withdraw_amount = bond.bonded_amount - bond.slashed_amount;
// State update BEFORE external interaction (checks-effects-interactions)
let updated = IdentityBond {
identity: identity.clone(),
bonded_amount: 0,
bond_start: bond.bond_start,
bond_duration: bond.bond_duration,
slashed_amount: bond.slashed_amount,
active: false,
is_rolling: bond.is_rolling,
withdrawal_requested_at: bond.withdrawal_requested_at,
notice_period: bond.notice_period,
};
e.storage().instance().set(&bond_key, &updated);
// External call: invoke callback if a callback contract is registered.
// In production this would be a token transfer; here we use a hook for testing.
let cb_key = Symbol::new(&e, "callback");
if let Some(cb_addr) = e.storage().instance().get::<_, Address>(&cb_key) {
let fn_name = Symbol::new(&e, "on_withdraw");
let args: Vec<Val> = Vec::from_array(&e, [withdraw_amount.into_val(&e)]);
e.invoke_contract::<Val>(&cb_addr, &fn_name, args);
}
Self::release_lock(&e);
withdraw_amount
}
/// Slash a portion of a bond. Only callable by admin.
/// Uses a reentrancy guard to prevent re-entrance during external calls.
pub fn slash_bond(e: Env, admin: Address, slash_amount: i128) -> i128 {
admin.require_auth();
Self::acquire_lock(&e);
let stored_admin: Address = e
.storage()
.instance()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic!("no admin"));
if stored_admin != admin {
Self::release_lock(&e);
panic!("not admin");
}
let bond_key = DataKey::Bond;
let bond: IdentityBond = e
.storage()
.instance()
.get(&bond_key)
.unwrap_or_else(|| panic!("no bond"));
if !bond.active {
Self::release_lock(&e);
panic!("bond not active");
}
let new_slashed = bond.slashed_amount + slash_amount;
if new_slashed > bond.bonded_amount {
Self::release_lock(&e);
panic!("slash exceeds bond");
}
// State update BEFORE external interaction
let updated = IdentityBond {
identity: bond.identity.clone(),
bonded_amount: bond.bonded_amount,
bond_start: bond.bond_start,
bond_duration: bond.bond_duration,
slashed_amount: new_slashed,
active: bond.active,
is_rolling: bond.is_rolling,
withdrawal_requested_at: bond.withdrawal_requested_at,
notice_period: bond.notice_period,
};
e.storage().instance().set(&bond_key, &updated);
// External call: invoke callback if registered
let cb_key = Symbol::new(&e, "callback");
if let Some(cb_addr) = e.storage().instance().get::<_, Address>(&cb_key) {
let fn_name = Symbol::new(&e, "on_slash");
let args: Vec<Val> = Vec::from_array(&e, [slash_amount.into_val(&e)]);
e.invoke_contract::<Val>(&cb_addr, &fn_name, args);
}
Self::release_lock(&e);
new_slashed
}
/// Collect accumulated protocol fees. Only callable by admin.
/// Uses a reentrancy guard to prevent re-entrance during external calls.
pub fn collect_fees(e: Env, admin: Address) -> i128 {
admin.require_auth();
Self::acquire_lock(&e);
let stored_admin: Address = e
.storage()
.instance()
.get(&DataKey::Admin)
.unwrap_or_else(|| panic!("no admin"));
if stored_admin != admin {
Self::release_lock(&e);
panic!("not admin");
}
let fee_key = Symbol::new(&e, "fees");
let fees: i128 = e.storage().instance().get(&fee_key).unwrap_or(0);
// State update BEFORE external interaction
e.storage().instance().set(&fee_key, &0_i128);
// External call: invoke callback if registered
let cb_key = Symbol::new(&e, "callback");
if let Some(cb_addr) = e.storage().instance().get::<_, Address>(&cb_key) {
let fn_name = Symbol::new(&e, "on_collect");
let args: Vec<Val> = Vec::from_array(&e, [fees.into_val(&e)]);
e.invoke_contract::<Val>(&cb_addr, &fn_name, args);
}
Self::release_lock(&e);
fees
}
/// Register a callback contract address (for testing external call hooks).
pub fn set_callback(e: Env, addr: Address) {
e.storage()
.instance()
.set(&Symbol::new(&e, "callback"), &addr);
}
/// Check if the reentrancy lock is currently held.
pub fn is_locked(e: Env) -> bool {
Self::check_lock(&e)
}
// --- Reentrancy guard helpers ---
fn acquire_lock(e: &Env) {
let key = Symbol::new(e, "locked");
let locked: bool = e.storage().instance().get(&key).unwrap_or(false);
if locked {
panic!("reentrancy detected");
}
e.storage().instance().set(&key, &true);
}
fn release_lock(e: &Env) {
let key = Symbol::new(e, "locked");
e.storage().instance().set(&key, &false);
}
fn check_lock(e: &Env) -> bool {
let key = Symbol::new(e, "locked");
e.storage().instance().get(&key).unwrap_or(false)
}
}
#[cfg(test)]
mod test;
#[cfg(test)]
mod test_reentrancy;
#[cfg(test)]
mod test_attestation;