forked from FinesseStudioLab/Trivela
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
539 lines (487 loc) · 20.1 KB
/
Copy pathlib.rs
File metadata and controls
539 lines (487 loc) · 20.1 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
//! # Trivela Campaign Contract
//!
//! On-chain campaign metadata and eligibility for Trivela.
//! Stores campaign config and allows checking participant status.
//!
//! Events:
//! - `register`: topics `(register, participant)`, data `()`
//! - `active`: topics `(active,)`, data `active: bool`
//! - `window`: topics `(window,)`, data `(start: u64, end: u64)`
//! - `maxcap`: topics `(maxcap,)`, data `max_cap: u64`
//! - `merkle`: topics `(merkle,)`, data `root: BytesN<32>`
//!
//! ## Merkle allowlist
//!
//! When a Merkle root is set via `set_merkle_root`, all calls to `register`
//! must include both a `leaf` (the 32-byte value committed in the tree) and
//! a valid sibling-hash `proof`.
//!
//! ### Leaf convention
//! Off-chain tooling must build the tree with
//! `leaf = sha256(address_xdr_bytes)` for each allowlisted address, and pass
//! that pre-computed leaf on-chain. Pairs are hashed in sorted order so
//! proofs are position-independent (the same convention as OpenZeppelin's
//! `MerkleProof`).
//!
//! ### Security note
//! `participant.require_auth()` ensures only the participant's own keypair
//! can submit a registration transaction, so a third party cannot register
//! an address on someone's behalf. The expected leaf for a given address
//! should be generated by a trusted off-chain tool so that only genuinely
//! allowlisted addresses possess a valid `(leaf, proof)` pair.
#![no_std]
use soroban_sdk::{
contract, contracterror, contractimpl, contractmeta, symbol_short, Address, Bytes, BytesN, Env,
Symbol, Vec,
};
#[contracterror]
#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)]
#[repr(u32)]
pub enum Error {
Unauthorized = 100,
OutsideTimeWindow = 101,
CapReached = 102,
CampaignInactive = 103,
NotInAllowlist = 104,
UnsupportedMigration = 105,
InvalidAdminNonce = 106,
InvalidWindow = 107,
NoPendingAdmin = 108,
}
contractmeta!(key = "Description", val = "Trivela campaign configuration");
// ── Instance-storage TTL (issue #279) ────────────────────────────────────────
//
// Mainnet ledgers close every ~5 seconds, so the prior `extend_ttl(50, 100)`
// literals expired instance storage roughly 8 minutes after the last
// mutation. These constants size the lifetime for production; tests override
// with the small values via `cfg(test)` so suites don't churn ledger budget.
// See `docs/TTL_STRATEGY.md` for the full rationale.
#[cfg(not(test))]
pub const TTL_THRESHOLD: u32 = 100_000;
#[cfg(not(test))]
pub const TTL_EXTEND_TO: u32 = 518_400;
#[cfg(test)]
pub const TTL_THRESHOLD: u32 = 50;
#[cfg(test)]
pub const TTL_EXTEND_TO: u32 = 100;
const ADMIN: Symbol = symbol_short!("admin");
const CAMPAIGN_ACTIVE: Symbol = symbol_short!("active");
const PARTICIPANT: Symbol = symbol_short!("partic");
const START_TIME: Symbol = symbol_short!("start");
const END_TIME: Symbol = symbol_short!("end");
const MAX_CAP: Symbol = symbol_short!("maxcap");
const PARTICIPANT_COUNT: Symbol = symbol_short!("count");
const MERKLE_ROOT: Symbol = symbol_short!("mkroot");
const SCHEMA_VERSION: Symbol = symbol_short!("schema_v");
const CURRENT_SCHEMA_VERSION: u32 = 1;
const ADMIN_NONCE: Symbol = symbol_short!("anonce");
const REGISTER_EVENT: Symbol = symbol_short!("register");
const SET_ACTIVE_EVENT: Symbol = symbol_short!("active");
const SET_WINDOW_EVENT: Symbol = symbol_short!("window");
const SET_MAX_CAP_EVENT: Symbol = symbol_short!("maxcap");
const SET_MERKLE_ROOT_EVENT: Symbol = symbol_short!("merkle");
// #280 — TTL thresholds for the per-participant persistent storage
// entries. Values are deliberately modest in this initial migration:
// every register call refreshes its own key without taking on the
// expense of much-longer extension windows. Production deployers
// should bump these via a future admin-only setter when traffic
// patterns are known (e.g. lengthen to a full campaign window once
// max_cap and end_time are public).
const PARTICIPANT_TTL_THRESHOLD: u32 = 100;
const PARTICIPANT_TTL_EXTEND_TO: u32 = 500;
// ── 2-step admin transfer (issue #281) ───────────────────────────────────────
const PENDING_ADMIN: Symbol = symbol_short!("padmin");
const ADMIN_PROPOSED_EVENT: Symbol = symbol_short!("aproposed");
const ADMIN_ACCEPTED_EVENT: Symbol = symbol_short!("aaccepted");
#[contract]
pub struct CampaignContract;
/// Hash two 32-byte values in sorted order so proofs are position-independent.
fn hash_pair(env: &Env, a: BytesN<32>, b: BytesN<32>) -> BytesN<32> {
let (left, right) = if a <= b { (a, b) } else { (b, a) };
let mut combined = [0u8; 64];
combined[..32].copy_from_slice(&left.to_array());
combined[32..].copy_from_slice(&right.to_array());
env.crypto()
.sha256(&Bytes::from_slice(env, &combined))
.into()
}
/// Verify that `leaf` is included in the tree identified by `root` using the
/// given sibling-hash `proof`.
fn verify_merkle_proof(
env: &Env,
leaf: BytesN<32>,
proof: &Vec<BytesN<32>>,
root: &BytesN<32>,
) -> bool {
let mut computed = leaf;
for sibling in proof.iter() {
computed = hash_pair(env, computed, sibling);
}
&computed == root
}
fn require_admin_with_nonce(env: &Env, admin: &Address, nonce: u64) -> Result<(), Error> {
admin.require_auth();
let stored: Address = env.storage().instance().get(&ADMIN).unwrap();
if &stored != admin {
return Err(Error::Unauthorized);
}
let current: u64 = env.storage().instance().get(&ADMIN_NONCE).unwrap_or(0);
if nonce != current {
return Err(Error::InvalidAdminNonce);
}
env.storage().instance().set(&ADMIN_NONCE, &(current + 1));
Ok(())
}
#[contractimpl]
impl CampaignContract {
/// Initialize campaign contract with an admin.
pub fn initialize(env: Env, admin: Address) -> Result<(), Error> {
env.storage().instance().set(&ADMIN, &admin);
env.storage().instance().set(&CAMPAIGN_ACTIVE, &true);
env.storage().instance().set(&START_TIME, &0u64);
env.storage().instance().set(&END_TIME, &u64::MAX);
env.storage().instance().set(&PARTICIPANT_COUNT, &0u64);
env.storage()
.instance()
.set(&SCHEMA_VERSION, &CURRENT_SCHEMA_VERSION);
env.storage().instance().set(&ADMIN_NONCE, &0u64);
env.storage().instance().extend_ttl(TTL_THRESHOLD, TTL_EXTEND_TO);
Ok(())
}
/// Returns the active storage schema version for this contract.
pub fn schema_version(env: Env) -> u32 {
env.storage()
.instance()
.get(&SCHEMA_VERSION)
.unwrap_or(CURRENT_SCHEMA_VERSION)
}
/// Migration entrypoint for future schema transitions.
///
/// For now, version `1` is the only supported schema and this function
/// serves as an idempotent migration hook for upgrade workflows.
pub fn migrate(env: Env, admin: Address, target_version: u32) -> Result<u32, Error> {
admin.require_auth();
let stored: Address = env.storage().instance().get(&ADMIN).unwrap();
if stored != admin {
return Err(Error::Unauthorized);
}
if target_version != CURRENT_SCHEMA_VERSION {
return Err(Error::UnsupportedMigration);
}
env.storage()
.instance()
.set(&SCHEMA_VERSION, &CURRENT_SCHEMA_VERSION);
env.storage().instance().extend_ttl(TTL_THRESHOLD, TTL_EXTEND_TO);
Ok(CURRENT_SCHEMA_VERSION)
}
/// Set registration time window (admin only).
///
/// Both bounds are inclusive: `register` succeeds when
/// `start <= now <= end`. Use `0` and `u64::MAX` for an effectively
/// open window. Rejects `start > end` with `InvalidWindow`.
pub fn set_window(
env: Env,
admin: Address,
nonce: u64,
start: u64,
end: u64,
) -> Result<(), Error> {
require_admin_with_nonce(&env, &admin, nonce)?;
if start > end {
return Err(Error::InvalidWindow);
}
env.storage().instance().set(&START_TIME, &start);
env.storage().instance().set(&END_TIME, &end);
env.events().publish((SET_WINDOW_EVENT,), (start, end));
env.storage().instance().extend_ttl(TTL_THRESHOLD, TTL_EXTEND_TO);
Ok(())
}
/// Get the configured `(start, end)` registration window.
///
/// Defaults to `(0, u64::MAX)` when no window has been set, which
/// callers can interpret as "unbounded".
pub fn get_window(env: Env) -> (u64, u64) {
let start: u64 = env.storage().instance().get(&START_TIME).unwrap_or(0);
let end: u64 = env.storage().instance().get(&END_TIME).unwrap_or(u64::MAX);
(start, end)
}
/// Returns `true` when the current ledger timestamp is within
/// `[start, end]` of the configured window.
///
/// Off-chain callers and dependent contracts (e.g. rewards logic)
/// can use this view to gate operations on campaign liveness without
/// duplicating the window check.
pub fn is_within_window(env: Env) -> bool {
let now = env.ledger().timestamp();
let start: u64 = env.storage().instance().get(&START_TIME).unwrap_or(0);
let end: u64 = env.storage().instance().get(&END_TIME).unwrap_or(u64::MAX);
now >= start && now <= end
}
/// Set campaign active flag (admin only).
pub fn set_active(env: Env, admin: Address, nonce: u64, active: bool) -> Result<(), Error> {
require_admin_with_nonce(&env, &admin, nonce)?;
env.storage().instance().set(&CAMPAIGN_ACTIVE, &active);
env.events().publish((SET_ACTIVE_EVENT,), active);
env.storage().instance().extend_ttl(TTL_THRESHOLD, TTL_EXTEND_TO);
Ok(())
}
/// Set maximum participant cap (admin only). Set to 0 for unlimited.
pub fn set_max_cap(env: Env, admin: Address, nonce: u64, max_cap: u64) -> Result<(), Error> {
require_admin_with_nonce(&env, &admin, nonce)?;
env.storage().instance().set(&MAX_CAP, &max_cap);
env.events().publish((SET_MAX_CAP_EVENT,), max_cap);
env.storage().instance().extend_ttl(TTL_THRESHOLD, TTL_EXTEND_TO);
Ok(())
}
/// Set the Merkle root for allowlist-gated registration (admin only).
///
/// Once set, every `register` call must supply a valid `(leaf, proof)`.
/// Remove the root by calling this again with a root of all zeros to
/// revert to open registration.
pub fn set_merkle_root(
env: Env,
admin: Address,
nonce: u64,
root: BytesN<32>,
) -> Result<(), Error> {
require_admin_with_nonce(&env, &admin, nonce)?;
env.storage().instance().set(&MERKLE_ROOT, &root);
env.events().publish((SET_MERKLE_ROOT_EVENT,), root.clone());
env.storage().instance().extend_ttl(TTL_THRESHOLD, TTL_EXTEND_TO);
Ok(())
}
/// Return the current Merkle root, or `None` when open registration is active.
pub fn get_merkle_root(env: Env) -> Option<BytesN<32>> {
env.storage().instance().get(&MERKLE_ROOT)
}
/// Register a participant.
///
/// `leaf` – the 32-byte leaf value committed in the Merkle tree for this
/// participant. Must be `sha256(address_xdr_bytes)` for the
/// caller's address, computed by off-chain tooling.
///
/// `proof` – ordered list of sibling hashes for the Merkle path from
/// `leaf` to the stored root. Pass an empty `Vec` when no root
/// is configured.
///
/// Returns `true` on first registration, `false` if already registered.
pub fn register(
env: Env,
participant: Address,
leaf: BytesN<32>,
proof: Vec<BytesN<32>>,
) -> Result<bool, Error> {
participant.require_auth();
let active: bool = env
.storage()
.instance()
.get(&CAMPAIGN_ACTIVE)
.unwrap_or(false);
if !active {
return Err(Error::CampaignInactive);
}
let now = env.ledger().timestamp();
let start: u64 = env.storage().instance().get(&START_TIME).unwrap_or(0);
let end: u64 = env.storage().instance().get(&END_TIME).unwrap_or(u64::MAX);
if now < start || now > end {
return Err(Error::OutsideTimeWindow);
}
// Merkle allowlist check – skipped when no root is stored.
if let Some(root) = env.storage().instance().get::<_, BytesN<32>>(&MERKLE_ROOT) {
if !verify_merkle_proof(&env, leaf, &proof, &root) {
return Err(Error::NotInAllowlist);
}
}
// #280 — Participant records live in PERSISTENT storage.
// Instance storage is shared with the contract code and caps
// at ~64KB total, which would brick a high-traffic campaign
// somewhere north of ~1.8k participants. Per-user data
// belongs in persistent storage where every key has its own
// TTL slot.
let key = (PARTICIPANT, participant.clone());
if env
.storage()
.persistent()
.get::<_, bool>(&key)
.unwrap_or(false)
{
return Ok(false);
}
let max_cap: u64 = env.storage().instance().get(&MAX_CAP).unwrap_or(0);
if max_cap > 0 {
let count: u64 = env
.storage()
.instance()
.get(&PARTICIPANT_COUNT)
.unwrap_or(0);
if count >= max_cap {
return Err(Error::CapReached);
}
}
env.storage().persistent().set(&key, &true);
// Extend the new persistent key's TTL alongside the write
// so the participant record stays alive across the campaign
// window. Threshold / extend-to values mirror the existing
// pattern used elsewhere in the workspace; the deployer can
// tune via a future admin-only setter without changing the
// storage tier.
env.storage()
.persistent()
.extend_ttl(&key, PARTICIPANT_TTL_THRESHOLD, PARTICIPANT_TTL_EXTEND_TO);
let count: u64 = env
.storage()
.instance()
.get(&PARTICIPANT_COUNT)
.unwrap_or(0);
env.storage()
.instance()
.set(&PARTICIPANT_COUNT, &(count + 1));
env.events().publish((REGISTER_EVENT, participant), ());
// Instance storage still holds aggregate state
// (PARTICIPANT_COUNT, ADMIN, etc.) so keep its TTL fresh
// too.
env.storage().instance().extend_ttl(50, 100);
env.storage().instance().extend_ttl(TTL_THRESHOLD, TTL_EXTEND_TO);
Ok(true)
}
/// Deregister a participant.
///
/// Checks liveness/window: if end_time is u64::MAX, checks if campaign is active;
/// otherwise, checks if current timestamp <= end_time.
pub fn deregister(env: Env, participant: Address) -> Result<bool, Error> {
participant.require_auth();
let end_time: u64 = env.storage().instance().get(&END_TIME).unwrap_or(u64::MAX);
if end_time != u64::MAX {
let now = env.ledger().timestamp();
if now > end_time {
return Err(Error::OutsideTimeWindow);
}
} else {
let active: bool = env.storage().instance().get(&CAMPAIGN_ACTIVE).unwrap_or(false);
if !active {
return Err(Error::CampaignInactive);
}
}
Ok(do_deregister(&env, participant))
}
/// Deregister a participant by the admin.
///
/// Bypasses time window and liveness checks. Requires admin auth and nonce validation.
pub fn admin_deregister(
env: Env,
admin: Address,
nonce: u64,
participant: Address,
) -> Result<bool, Error> {
require_admin_with_nonce(&env, &admin, nonce)?;
Ok(do_deregister(&env, participant))
}
/// Check if a participant is registered. (#280) Reads from
/// persistent storage where participant records live.
pub fn is_participant(env: Env, participant: Address) -> bool {
env.storage()
.persistent()
.get(&(PARTICIPANT, participant))
.unwrap_or(false)
}
/// Check if campaign is active.
pub fn is_active(env: Env) -> bool {
env.storage()
.instance()
.get(&CAMPAIGN_ACTIVE)
.unwrap_or(false)
}
/// Get current participant count.
pub fn get_participant_count(env: Env) -> u64 {
env.storage()
.instance()
.get(&PARTICIPANT_COUNT)
.unwrap_or(0)
}
/// Get maximum participant cap (0 means unlimited).
pub fn get_max_cap(env: Env) -> u64 {
env.storage().instance().get(&MAX_CAP).unwrap_or(0)
}
/// Get the next required admin nonce for sensitive operations.
pub fn admin_nonce(env: Env) -> u64 {
env.storage().instance().get(&ADMIN_NONCE).unwrap_or(0)
}
// ── Admin rotation (issue #281) ──────────────────────────────────────────
/// Return the current admin address.
pub fn admin(env: Env) -> Address {
env.storage().instance().get(&ADMIN).unwrap()
}
/// Return the pending admin address proposed by the current admin, if any.
pub fn pending_admin(env: Env) -> Option<Address> {
env.storage().instance().get(&PENDING_ADMIN)
}
/// Propose a new admin (current admin only). The transfer does not take
/// effect until `accept_admin` is called by the new admin.
pub fn propose_admin(
env: Env,
current_admin: Address,
new_admin: Address,
) -> Result<(), Error> {
current_admin.require_auth();
let stored_admin: Address = env.storage().instance().get(&ADMIN).unwrap();
if stored_admin != current_admin {
return Err(Error::Unauthorized);
}
env.storage().instance().set(&PENDING_ADMIN, &new_admin);
env.events()
.publish((ADMIN_PROPOSED_EVENT, current_admin), new_admin);
env.storage().instance().extend_ttl(TTL_THRESHOLD, TTL_EXTEND_TO);
Ok(())
}
/// Accept admin role. Caller MUST be the address that the current admin
/// previously proposed via `propose_admin`. Clears the pending slot on
/// success.
pub fn accept_admin(env: Env, new_admin: Address) -> Result<(), Error> {
new_admin.require_auth();
let pending: Address = env
.storage()
.instance()
.get(&PENDING_ADMIN)
.ok_or(Error::NoPendingAdmin)?;
if pending != new_admin {
return Err(Error::Unauthorized);
}
env.storage().instance().set(&ADMIN, &new_admin);
env.storage().instance().remove(&PENDING_ADMIN);
env.events()
.publish((ADMIN_ACCEPTED_EVENT,), new_admin);
env.storage().instance().extend_ttl(TTL_THRESHOLD, TTL_EXTEND_TO);
Ok(())
}
/// Cancel an in-flight admin transfer (current admin only).
pub fn cancel_admin_transfer(env: Env, current_admin: Address) -> Result<(), Error> {
current_admin.require_auth();
let stored_admin: Address = env.storage().instance().get(&ADMIN).unwrap();
if stored_admin != current_admin {
return Err(Error::Unauthorized);
}
env.storage().instance().remove(&PENDING_ADMIN);
env.storage().instance().extend_ttl(TTL_THRESHOLD, TTL_EXTEND_TO);
Ok(())
}
}
fn do_deregister(env: &Env, participant: Address) -> bool {
// #280 — Participant records live in PERSISTENT storage.
let key = (PARTICIPANT, participant.clone());
if !env.storage().persistent().get::<_, bool>(&key).unwrap_or(false) {
return false;
}
env.storage().persistent().remove(&key);
let count: u64 = env.storage().instance().get(&PARTICIPANT_COUNT).unwrap_or(0);
if count > 0 {
env.storage().instance().set(&PARTICIPANT_COUNT, &(count - 1));
}
env.events().publish(
(Symbol::new(env, "deregister"), participant),
(),
);
env.storage().instance().extend_ttl(TTL_THRESHOLD, TTL_EXTEND_TO);
true
}
#[cfg(test)]
mod test;