forked from Haroldwonder/TrustLink
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypes.rs
More file actions
587 lines (534 loc) · 18.6 KB
/
Copy pathtypes.rs
File metadata and controls
587 lines (534 loc) · 18.6 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
//! Shared data types and error codes for TrustLink.
//!
//! This module defines all contract types including:
//! - Core attestation types (Attestation, AttestationRequest, MultiSigProposal)
//! - Configuration types (ContractConfig, FeeConfig, TtlConfig, RateLimitConfig)
//! - Admin management (AdminCouncil, PendingAdminTransfer, CouncilProposal)
//! - Advanced features (Delegation, DisputeRecord, DecayConfig, AttestationTemplate, AttestationVersionSnapshot)
//! - Utility types (GlobalStats, IssuerStats, HealthStatus, AuditEntry, Endorsement)
use soroban_sdk::{contracterror, contracttype, xdr::ToXdr, Address, Bytes, Env, String, Vec};
/// Default lifetime for a multi-sig proposal: 7 days in seconds.
pub const MULTISIG_PROPOSAL_TTL_SECS: u64 = 7 * 24 * 60 * 60;
/// Default lifetime for an attestation request: 7 days in seconds.
pub const ATTESTATION_REQUEST_TTL_SECS: u64 = 7 * 24 * 60 * 60;
/// Seconds in one day.
pub const SECS_PER_DAY: u64 = 86_400;
/// Status of an attestation request.
#[contracttype]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum RequestStatus {
Pending = 0,
Fulfilled = 1,
Rejected = 2,
Cancelled = 3,
}
/// A pull-based attestation request submitted by a subject to a registered issuer.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AttestationRequest {
pub id: String,
pub subject: Address,
pub issuer: Address,
pub claim_type: String,
pub timestamp: u64,
pub expires_at: u64,
pub status: RequestStatus,
pub rejection_reason: Option<String>,
}
/// Trust tier assigned to a registered issuer.
#[contracttype]
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum IssuerTier {
Basic = 0,
Verified = 1,
Premium = 2,
}
impl IssuerTier {
pub fn rank(self) -> u32 {
self as u32
}
}
/// A registered expiration notification hook for a subject.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ExpirationHook {
pub callback_contract: Address,
pub notify_days_before: u32,
}
/// A multi-signature attestation proposal.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MultiSigProposal {
pub id: String,
pub proposer: Address,
pub subject: Address,
pub claim_type: String,
pub required_signers: Vec<Address>,
pub threshold: u32,
pub signers: Vec<Address>,
pub created_at: u64,
pub expires_at: u64,
pub finalized: bool,
/// Set to true when the proposer cancels the proposal before finalization.
pub cancelled: bool,
}
/// Contract metadata returned by `get_contract_metadata`.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ContractMetadata {
pub name: String,
pub version: String,
pub description: String,
}
/// Per-issuer statistics.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IssuerStats {
pub total_issued: u64,
}
/// Output format for `export_revocation_list`.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum RevocationListFormat {
/// Plain list of revoked attestation IDs.
SimpleList,
/// Compact bitstring encoding (Status List 2021 compatible).
Bitstring,
}
/// A snapshot of an issuer's revocation status for external verifiers,
/// produced by `export_revocation_list`.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RevocationList {
pub issuer: Address,
pub claim_type: Option<String>,
pub generated_at: u64,
pub revoked_attestation_ids: Vec<String>,
pub bitstring: Option<Bytes>,
pub total_attestation_count: u64,
pub revoked_count: u64,
}
/// Metadata about a registered issuer.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IssuerMetadata {
pub name: String,
pub url: String,
pub description: String,
}
/// Fee configuration for attestation creation.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FeeConfig {
pub attestation_fee: i128,
pub fee_collector: Address,
pub fee_token: Option<Address>,
}
/// Global contract statistics.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GlobalStats {
pub total_attestations: u64,
pub total_revocations: u64,
pub total_issuers: u64,
}
/// Health status for monitoring.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HealthStatus {
pub initialized: bool,
pub admin_set: bool,
pub issuer_count: u64,
pub total_attestations: u64,
}
/// TTL configuration.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TtlConfig {
pub ttl_days: u32,
}
/// Rate limiting configuration.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RateLimitConfig {
pub min_issuance_interval: u64,
}
/// Full contract configuration snapshot returned by `get_config`.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ContractConfig {
pub contract_name: String,
pub contract_version: String,
pub contract_description: String,
pub fee_config: FeeConfig,
pub ttl_config: TtlConfig,
pub require_registered_claim_type: bool,
/// When `true`, the `metadata` field on new attestations must be either
/// `None` or a 64-character lowercase hexadecimal string (SHA-256 hash).
/// Enables enforcement of GDPR data-minimisation at the contract level.
pub metadata_hash_only: bool,
/// Optional maximum number of attestations per subject.
/// When set, new attestations exceeding this limit will be rejected.
/// When `None`, attestations are unlimited (default for backward compatibility).
pub max_attestations_per_subject: Option<u32>,
/// Number of attestation IDs stored per chunk in the `ChunkedIndex`.
///
/// Larger values reduce storage-read counts for high-volume issuers/subjects
/// at the cost of larger individual reads/writes. Smaller values keep each
/// read/write cheap at the cost of more round-trips for large indexes.
/// Must be ≥ 1. Defaults to 50 when not explicitly set.
/// **Should only be changed before any attestations are written**; changing
/// it afterwards requires a full index migration.
pub chunk_size: u32,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ClaimTypeInfo {
pub claim_type: String,
pub description: String,
}
/// Constraints for a specific claim type enforced during attestation creation.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ClaimTypeConstraints {
pub min_metadata_len: Option<u32>,
pub max_metadata_len: Option<u32>,
pub require_metadata: bool,
}
/// Operations that require council quorum approval.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum CouncilOperation {
RemoveIssuer(Address),
PauseContract,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CouncilProposal {
pub id: u32,
pub operation: CouncilOperation,
pub proposer: Address,
pub approvals: Vec<Address>,
pub executed: bool,
/// Ledger timestamp at which the proposal reached quorum.
/// `None` means quorum has not been reached yet. Used by the timelock
/// guard in `execute_council_action`.
pub quorum_reached_at: Option<u64>,
}
/// Describes how an attestation entered the system.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AttestationOrigin {
Native,
Imported,
Bridged,
}
/// A single issuer-created claim about a subject address.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Attestation {
pub id: String,
pub issuer: Address,
pub subject: Address,
pub claim_type: String,
pub timestamp: u64,
pub expiration: Option<u64>,
pub revoked: bool,
pub metadata: Option<String>,
pub valid_from: Option<u64>,
pub origin: AttestationOrigin,
pub source_chain: Option<String>,
pub source_tx: Option<String>,
pub tags: Option<Vec<String>>,
pub revocation_reason: Option<String>,
pub deleted: bool,
/// ISO 3166-1 alpha-2 jurisdiction code, when the attestation was created
/// via `create_attestation_jurisdiction`.
pub jurisdiction: Option<String>,
/// Optional: shared bundle ID if this attestation was created as part of a bundle.
/// Allows verifiers to confirm a set of claims were issued atomically.
pub bundle_id: Option<String>,
}
/// Metadata for a bundle of attestations issued atomically.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AttestationBundle {
/// Unique bundle identifier (SHA256 of issuer + subject + claim_types + timestamp)
pub id: String,
/// Issuer who created the bundle
pub issuer: Address,
/// Subject to whom all attestations in the bundle were issued
pub subject: Address,
/// List of claim types in the bundle (fixed order for deterministic ID)
pub claim_types: Vec<String>,
/// Timestamp when the bundle was created
pub timestamp: u64,
/// IDs of all attestations in this bundle (in same order as claim_types)
pub attestation_ids: Vec<String>,
/// Whether all attestations in the bundle are still valid (none revoked)
pub all_valid: bool,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AttestationStatus {
Valid,
Expired,
Revoked,
Pending,
}
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum AuditAction {
Created,
Revoked,
Renewed,
Updated,
Transferred,
Deleted,
Amended,
}
/// A single immutable entry in an attestation's audit log.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AuditEntry {
pub action: AuditAction,
pub actor: Address,
pub timestamp: u64,
pub details: Option<String>,
}
/// A social-proof endorsement of an existing attestation by a registered issuer.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Endorsement {
pub attestation_id: String,
pub endorser: Address,
pub timestamp: u64,
}
/// Configurable storage limits to prevent exhaustion attacks.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct StorageLimits {
pub max_attestations_per_issuer: u32,
pub max_attestations_per_subject: u32,
}
/// Contract error codes are defined in [`crate::errors`] and re-exported
/// here so `crate::types::Error` remains a stable import path.
pub use crate::errors::Error;
impl Default for StorageLimits {
fn default() -> Self {
Self {
max_attestations_per_issuer: 10_000,
max_attestations_per_subject: 100,
}
}
}
/// Delegation from an issuer to a sub-issuer for specific claim types.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Delegation {
pub delegator: Address,
pub delegate: Address,
pub claim_type: String,
pub expiration: Option<u64>,
}
/// Storage key for the pending admin transfer (two-step pattern).
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PendingAdminTransfer {
pub proposed_by: Address,
pub new_admin: Address,
}
/// Admin council: ordered list of admin addresses.
pub type AdminCouncil = Vec<Address>;
/// A point-in-time snapshot of an attestation's mutable fields, saved before
/// each amendment so callers can reconstruct the full version history.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AttestationVersionSnapshot {
pub version: u32,
pub metadata: Option<String>,
pub amended_at: u64,
pub amended_by: Address,
}
/// Configurable parameters for issuer reputation decay, applied at read time
/// inside `get_confidence_score`. Stored on-chain so they are adjustable
/// without a contract upgrade.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DecayConfig {
/// Number of days of inactivity after which the score is halved.
/// Set to 0 to disable inactivity decay entirely.
pub half_life_days: u32,
/// Scaling factor (0–100) applied to the revocation ratio before
/// subtracting from the score. 100 means a 100 % revocation rate
/// would zero out the score entirely.
pub revocation_weight: u32,
}
impl Default for DecayConfig {
fn default() -> Self {
Self {
half_life_days: 90,
revocation_weight: 50,
}
}
}
/// An active dispute raised by a subject against one of their attestations.
/// The record is removed when the dispute is resolved.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct DisputeRecord {
pub attestation_id: String,
pub subject: Address,
pub reason: String,
pub disputed_at: u64,
}
/// A named attestation template owned by an issuer.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct AttestationTemplate {
pub claim_type: String,
pub metadata_template: Option<String>,
pub default_expiration_days: Option<u32>,
}
impl Attestation {
pub fn hash_payload(env: &Env, payload: &Bytes) -> String {
let hash = env.crypto().sha256(payload).to_array();
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut hex = [0u8; 64];
for i in 0..32 {
hex[i * 2] = HEX[(hash[i] >> 4) as usize];
hex[i * 2 + 1] = HEX[(hash[i] & 0x0f) as usize];
}
String::from_bytes(env, &hex)
}
/// Derives a deterministic attestation ID from `(issuer, subject, claim_type, timestamp)`.
///
/// # Same-second collisions (issue #951)
///
/// `timestamp` is the Stellar ledger close time, which has **second**
/// granularity. Two distinct creation attempts for the same
/// `(issuer, subject, claim_type)` triple that land in the same
/// ledger-close second — for example, a direct [`create_attestation`]
/// call racing a [`fulfill_request`] call for the same underlying claim —
/// derive the *same* ID. Whichever call is applied first succeeds; the
/// second is rejected with [`Error::DuplicateAttestation`], even though
/// from the caller's perspective these may be two genuinely different
/// attestation attempts rather than a retry of the same one.
///
/// This is a deliberate trade-off: the ID intentionally excludes fields
/// like `metadata` so that it stays fully derivable off-chain (e.g. by
/// [`crate::attestation::simulate_create_attestation`]) from only the
/// four inputs above, and so that legitimate retries of the *same*
/// attempt are naturally idempotent rather than creating duplicates. No
/// nonce is added, since that would make the ID non-deterministic from
/// the caller's point of view and break that off-chain derivability.
///
/// If a caller genuinely needs two distinct attestations for the same
/// triple within one ledger-close second, they must vary `claim_type`
/// (e.g. suffix it with a synthetic differentiator) or retry on the next
/// ledger, which advances `timestamp`. `metadata` cannot be used as a
/// differentiator, since it is not part of the hashed payload.
///
/// [`create_attestation`]: crate::attestation::create_attestation
/// [`fulfill_request`]: crate::request::fulfill_request
pub fn generate_id(
env: &Env,
issuer: &Address,
subject: &Address,
claim_type: &String,
timestamp: u64,
) -> String {
let mut bytes = Bytes::new(env);
bytes.append(&issuer.clone().to_xdr(env));
bytes.append(&subject.clone().to_xdr(env));
bytes.append(&claim_type.clone().to_xdr(env));
bytes.append(&Bytes::from_slice(env, ×tamp.to_be_bytes()));
let hash = env.crypto().sha256(&bytes).to_array();
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut id = [0u8; 32];
for i in 0..16 {
id[i * 2] = HEX[(hash[i] >> 4) as usize];
id[i * 2 + 1] = HEX[(hash[i] & 0x0f) as usize];
}
String::from_str(env, core::str::from_utf8(&id).unwrap_or(""))
}
/// Derives a deterministic attestation ID for a bridged attestation from
/// `(bridge, subject, claim_type, source_chain, source_tx, timestamp)`.
pub fn generate_bridge_id(
env: &Env,
bridge: &Address,
subject: &Address,
claim_type: &String,
source_chain: &String,
source_tx: &String,
timestamp: u64,
) -> String {
let mut bytes = Bytes::new(env);
bytes.append(&bridge.clone().to_xdr(env));
bytes.append(&subject.clone().to_xdr(env));
bytes.append(&claim_type.clone().to_xdr(env));
bytes.append(&source_chain.clone().to_xdr(env));
bytes.append(&source_tx.clone().to_xdr(env));
bytes.append(&Bytes::from_slice(env, ×tamp.to_be_bytes()));
let hash = env.crypto().sha256(&bytes).to_array();
const HEX: &[u8; 16] = b"0123456789abcdef";
let mut id = [0u8; 32];
for i in 0..16 {
id[i * 2] = HEX[(hash[i] >> 4) as usize];
id[i * 2 + 1] = HEX[(hash[i] & 0x0f) as usize];
}
String::from_str(env, core::str::from_utf8(&id).unwrap_or(""))
}
/// Compute the current validity state. A pending attestation is not usable,
/// and revocation permanently takes precedence over expiration.
pub fn get_status(&self, current_time: u64) -> AttestationStatus {
if let Some(valid_from) = self.valid_from {
if current_time < valid_from {
return AttestationStatus::Pending;
}
}
if self.revoked {
return AttestationStatus::Revoked;
}
if let Some(expiration) = self.expiration {
if current_time >= expiration {
return AttestationStatus::Expired;
}
}
AttestationStatus::Valid
}
}
impl AttestationRequest {
pub fn generate_id(
env: &Env,
subject: &Address,
issuer: &Address,
claim_type: &String,
timestamp: u64,
) -> String {
let mut payload = Bytes::new(env);
payload.append(&Bytes::from_slice(env, b"req:"));
payload.append(&subject.clone().to_xdr(env));
payload.append(&issuer.clone().to_xdr(env));
payload.append(&claim_type.clone().to_xdr(env));
payload.append(×tamp.to_xdr(env));
Attestation::hash_payload(env, &payload)
}
}
impl MultiSigProposal {
pub fn generate_id(
env: &Env,
proposer: &Address,
subject: &Address,
claim_type: &String,
timestamp: u64,
) -> String {
let mut payload = Bytes::new(env);
payload.append(&Bytes::from_slice(env, b"multisig:"));
payload.append(&proposer.clone().to_xdr(env));
payload.append(&subject.clone().to_xdr(env));
payload.append(&claim_type.clone().to_xdr(env));
payload.append(×tamp.to_xdr(env));
Attestation::hash_payload(env, &payload)
}
}