summaryrefslogtreecommitdiffstats
path: root/examples/inheritance_demo.rs
blob: 00c22ac36e9c060982c32f156852a4f8eaca35e3 (plain) (blame)
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
/// Demonstration of OnionCoin's Revolutionary Inheritance System
///
/// World's first cryptocurrency with NATIVE inheritance built into the blockchain!
///
/// Features:
/// - Time-locked contracts with progressive unlock
/// - Heartbeat system (proof of life)
/// - Shamir secret sharing (3-of-5)
/// - Anti-scam protections
/// - Dispute resolution

use onioncoin_inheritance::*;
use onioncoin_inheritance::contract::ContractStatus;
use onioncoin_inheritance::unlock::UnlockScheduleType;
use onioncoin_inheritance::recovery::{DisputeReason, Evidence, EvidenceType, ResolutionType, ResolutionAction};

fn main() {
    println!("=== OnionCoin Inheritance System Demo ===\n");

    demo_basic_inheritance();
    println!("\n{}\n", "=".repeat(60));

    demo_progressive_unlock();
    println!("\n{}\n", "=".repeat(60));

    demo_heartbeat_system();
    println!("\n{}\n", "=".repeat(60));

    demo_shamir_secret_sharing();
    println!("\n{}\n", "=".repeat(60));

    demo_dispute_resolution();
    println!("\n{}\n", "=".repeat(60));

    demo_complete_scenario();
}

fn demo_basic_inheritance() {
    println!("šŸ“œ BASIC INHERITANCE CONTRACT");
    println!("=============================");

    // Create beneficiaries
    let beneficiaries = vec![
        Beneficiary::new([1u8; 32], 60).unwrap(), // Wife: 60%
        Beneficiary::new([2u8; 32], 40).unwrap(), // Child: 40%
    ];

    // Create contract
    let contract = InheritanceContract::new(
        [0u8; 32],                          // Owner pubkey
        beneficiaries,
        InheritanceConfig::default(),       // 90 days + 30 days grace
        100_000,                            // 100,000 ONC locked
        0,
    ).unwrap();

    println!("Contract Created:");
    println!("  Owner: {:?}...", &contract.owner[0..4]);
    println!("  Locked Amount: {} ONC", contract.locked_amount);
    println!("  Beneficiaries: {}", contract.beneficiaries.len());

    for (i, b) in contract.beneficiaries.iter().enumerate() {
        let amount = b.calculate_amount(contract.locked_amount);
        println!("    {}. {}% = {} ONC", i + 1, b.percentage, amount);
    }

    println!("\nHeartbeat Requirements:");
    println!("  Interval: {} days", contract.config.heartbeat_interval / (24 * 3600));
    println!("  Grace Period: {} days", contract.config.grace_period / (24 * 3600));
    println!("  Total Timeout: {} days", contract.config.total_timeout() / (24 * 3600));

    println!("\nāœ… NO OTHER CRYPTO HAS THIS BUILT-IN!");
}

fn demo_progressive_unlock() {
    println!("šŸ”“ PROGRESSIVE UNLOCK (INNOVATIVE!)");
    println!("===================================");

    let beneficiaries = vec![Beneficiary::new([1u8; 32], 100).unwrap()];

    let mut contract = InheritanceContract::new(
        [0u8; 32],
        beneficiaries,
        InheritanceConfig::default(),
        100_000,
        0,
    ).unwrap();

    println!("Why Progressive Unlock?");
    println!("  āŒ Traditional dead man's switch: ALL funds unlock at once");
    println!("  āœ… OnionCoin: Gradual unlock gives owner time to recover!\n");

    // Simulate timeout
    contract.status = ContractStatus::Unlocking;

    // Initialize progressive unlock
    ProgressiveUnlock::initialize(&mut contract, UnlockScheduleType::Standard).unwrap();

    let schedule = contract.unlock_schedule.as_ref().unwrap();

    println!("Standard 4-Tier Schedule:");
    for tier in &schedule.tiers {
        println!("  Tier {}: Day +{} → Unlock {}%",
            tier.tier,
            tier.days_after_expiry,
            tier.unlock_percentage);
    }

    println!("\nExample Timeline:");
    println!("  Day 0:   Grace period expires");
    println!("  Day 30:  Tier 1 unlocks → 10,000 ONC available (10%)");
    println!("  Day 60:  Tier 2 unlocks → 25,000 ONC more (35% total)");
    println!("  Day 90:  Tier 3 unlocks → 35,000 ONC more (70% total)");
    println!("  Day 120: Tier 4 unlocks → 30,000 ONC more (100% total)");

    println!("\nšŸ’” If owner wakes up from coma on day 50:");
    println!("   Only 35% unlocked, can dispute and recover 65%!");
}

fn demo_heartbeat_system() {
    println!("šŸ’“ HEARTBEAT SYSTEM");
    println!("==================");

    let beneficiaries = vec![Beneficiary::new([1u8; 32], 100).unwrap()];

    let mut contract = InheritanceContract::new(
        [0u8; 32],
        beneficiaries,
        InheritanceConfig::default(),
        10000,
        0,
    ).unwrap();

    let mut manager = HeartbeatManager::new();
    manager.register_contract(contract.contract_id, 0);

    println!("How It Works:");
    println!("  1. Owner must 'check in' every 90 days");
    println!("  2. Heartbeat = Send 0.00000001 ONC to yourself");
    println!("  3. Privacy-preserving (no one knows why you sent it)");
    println!("  4. Can do via Tor for extra privacy\n");

    // Simulate heartbeats
    println!("Simulating Owner Activity:");

    // Day 30
    manager.process_heartbeat(&mut contract, 30 * 24 * 3600).unwrap();
    println!("  Day 30: āœ“ Heartbeat sent");

    // Day 65
    manager.process_heartbeat(&mut contract, 65 * 24 * 3600).unwrap();
    println!("  Day 65: āœ“ Heartbeat sent");

    let stats = manager.get_stats(&contract.contract_id).unwrap();
    println!("\nStatistics:");
    println!("  Total Heartbeats: {}", stats.heartbeat_count);
    println!("  Average Interval: {:.1} days", stats.avg_interval_days);
    println!("  Last Heartbeat: {} days ago",
        (65 * 24 * 3600 - stats.last_heartbeat) / (24 * 3600));

    println!("\n  Recommendation: {}", manager.suggest_frequency(&contract.contract_id).unwrap());

    // Simulate warning
    println!("\nWarning System:");
    let notifications = manager.check_contracts(&[&contract], 65 * 24 * 3600 + 75 * 24 * 3600);

    if !notifications.is_empty() {
        println!("  āš ļø  {}", notifications[0].message);
    }
}

fn demo_shamir_secret_sharing() {
    println!("šŸ” SHAMIR SECRET SHARING (3-of-5)");
    println!("=================================");

    println!("Scenario: Split seed phrase among 5 trusted people");
    println!("  Any 3 can recover, but 2 or fewer cannot\n");

    let seed_phrase = b"abandon ability able about above absent absorb abstract absurd abuse access accident";

    // Create 5 guardians
    let guardians = vec![
        [1u8; 32], // Best friend
        [2u8; 32], // Sister
        [3u8; 32], // Lawyer
        [4u8; 32], // Colleague
        [5u8; 32], // Trusted advisor
    ];

    println!("Guardians:");
    let guardian_names = ["Best Friend", "Sister", "Lawyer", "Colleague", "Advisor"];
    for (i, name) in guardian_names.iter().enumerate() {
        println!("  {}. {} ({:?}...)", i + 1, name, &guardians[i][0..4]);
    }

    // Create Shamir scheme
    let mut shamir = ShamirShares::new(3, 5).unwrap();
    let shares = shamir.split_secret(seed_phrase, &guardians).unwrap();

    println!("\nāœ… Secret split into 5 shares");
    println!("   Each guardian receives their encrypted share\n");

    // Simulate recovery scenario
    println!("Recovery Scenario:");
    println!("  Owner passed away, beneficiaries contact guardians\n");

    // Only 2 shares - fails
    println!("  Attempt 1: Guardian 1 + Guardian 2 (2 shares)");
    let result = shamir.recover_secret(&shares[0..2]);
    println!("    āŒ Failed: Need minimum 3 shares\n");

    // 3 shares - success!
    println!("  Attempt 2: Guardian 1 + Guardian 3 + Guardian 5 (3 shares)");
    let recovered = shamir.recover_secret(&[shares[0].clone(), shares[2].clone(), shares[4].clone()]).unwrap();
    println!("    āœ… Success: Seed phrase recovered!");

    if recovered == seed_phrase {
        println!("    āœ… Verified: Matches original seed\n");
    }

    println!("Security:");
    println!("  āœ… No single guardian can access funds");
    println!("  āœ… Collusion of 3+ required");
    println!("  āœ… Redundancy: Can lose 2 shares and still recover");
}

fn demo_dispute_resolution() {
    println!("āš–ļø  DISPUTE RESOLUTION (ANTI-SCAM)");
    println!("=================================");

    let beneficiaries = vec![Beneficiary::new([1u8; 32], 100).unwrap()];

    let mut contract = InheritanceContract::new(
        [0u8; 32],
        beneficiaries,
        InheritanceConfig::default(),
        50000,
        0,
    ).unwrap();

    let mut recovery_manager = RecoveryManager::default();

    println!("Scenario: Owner in hospital, unable to send heartbeat");
    println!("  Grace period expires, unlock starts...\n");

    // Simulate unlock starting
    contract.status = ContractStatus::Unlocking;

    println!("Owner Recovers and Files Dispute:");
    recovery_manager.file_dispute(
        &mut contract,
        [0u8; 32], // Owner
        DisputeReason::TemporaryIncapacitation,
        1000,
    ).unwrap();

    println!("  āœ… Dispute filed successfully");
    println!("  Status: {:?}", contract.status);

    // Add evidence
    let evidence = Evidence {
        evidence_type: EvidenceType::MedicalCertificate,
        data: vec![1, 2, 3], // Encrypted medical cert
        submitted_at: 1100,
    };

    recovery_manager.add_evidence(&contract.contract_id, evidence).unwrap();
    println!("  āœ… Medical certificate submitted\n");

    // Resolve dispute
    println!("Resolution:");
    let resolution = DisputeResolution {
        resolution_type: ResolutionType::ResetHeartbeat,
        actions: vec![ResolutionAction::HeartbeatReset],
        resolved_at: 2000,
        notes: Some("Owner verified alive, medical emergency confirmed".to_string()),
    };

    recovery_manager.resolve_dispute(&mut contract, resolution, 2000).unwrap();

    println!("  āœ… Heartbeat reset");
    println!("  āœ… Contract resumed: {:?}", contract.status);
    println!("  āœ… Funds secure, owner has full control\n");

    println!("Anti-Scam Protection:");
    println!("  āœ… Maximum 3 disputes allowed (prevent abuse)");
    println!("  āœ… 7-day cooldown between disputes");
    println!("  āœ… Evidence required (proof of life)");
    println!("  āœ… Suspicious activity detection");
}

fn demo_complete_scenario() {
    println!("šŸŽ¬ COMPLETE SCENARIO");
    println!("===================");

    println!("Alice wants to ensure her crypto goes to her family if she dies\n");

    // Step 1: Create contract
    println!("Step 1: Create Inheritance Contract");
    let beneficiaries = vec![
        Beneficiary::new([1u8; 32], 70).unwrap(), // Husband
        Beneficiary::new([2u8; 32], 30).unwrap(), // Daughter
    ];

    let mut contract = InheritanceContract::new(
        [0u8; 32], // Alice
        beneficiaries,
        InheritanceConfig::default(),
        500_000, // 500,000 ONC
        0,
    ).unwrap();

    println!("  āœ… Contract created");
    println!("  āœ… 500,000 ONC locked");
    println!("  āœ… 70% to husband, 30% to daughter\n");

    // Step 2: Optional Shamir shares
    println!("Step 2: Setup Shamir Secret Sharing (Optional)");
    let guardians = vec![
        [10u8; 32],
        [11u8; 32],
        [12u8; 32],
        [13u8; 32],
        [14u8; 32],
    ];

    let distribution = ShareDistribution::standard_3_of_5(guardians).unwrap();
    println!("  āœ… Seed split among 5 trusted guardians");
    println!("  āœ… Any 3 can help family recover\n");

    // Step 3: Regular heartbeats
    println!("Step 3: Alice Sends Regular Heartbeats");
    let mut manager = HeartbeatManager::new();
    manager.register_contract(contract.contract_id, 0);

    for month in 1..=12 {
        let days = month * 30;
        manager.process_heartbeat(&mut contract, days * 24 * 3600).unwrap();
        if month % 3 == 0 {
            println!("  āœ“ Month {}: Heartbeat sent", month);
        }
    }
    println!("  āœ… 12 months of regular heartbeats\n");

    // Step 4: Alice passes away (tragic scenario)
    println!("Step 4: Alice Passes Away (Simulation)");
    println!("  Last heartbeat: Month 12");
    println!("  Current time: Month 16 (120 days later)\n");

    let current_time = 16 * 30 * 24 * 3600;

    // Step 5: Grace period expires
    println!("Step 5: System Detects Timeout");
    contract.update_status(current_time);
    println!("  Status: {:?}", contract.status);

    let notifications = manager.check_contracts(&[&contract], current_time);
    println!("  Notifications sent: {}", notifications.len());
    println!("    - Critical warning to Alice (no response)");
    println!("    - Info to beneficiaries (grace period)\n");

    // Step 6: Progressive unlock
    println!("Step 6: Progressive Unlock Begins");
    contract.status = ContractStatus::Unlocking;
    ProgressiveUnlock::initialize(&mut contract, UnlockScheduleType::Standard).unwrap();

    // Simulate tier 1 unlock (30 days after grace expiry)
    let tier1_time = current_time + 30 * 24 * 3600;
    let distributions = ProgressiveUnlock::process(&mut contract, tier1_time).unwrap();

    println!("  Day 30: Tier 1 Unlocks (10%)");
    for dist in &distributions {
        println!("    → {} ONC to beneficiary {:?}...",
            dist.amount,
            &dist.beneficiary[0..4]);
    }

    println!("\n  Husband receives: 35,000 ONC (70% of 50,000)");
    println!("  Daughter receives: 15,000 ONC (30% of 50,000)\n");

    // Step 7: Full unlock
    let final_time = current_time + 120 * 24 * 3600;
    ProgressiveUnlock::process(&mut contract, final_time).unwrap();

    println!("Step 7: Full Unlock Complete (Day 120)");
    println!("  Husband total: 350,000 ONC");
    println!("  Daughter total: 150,000 ONC");
    println!("  Status: {:?}", contract.status);

    println!("\nāœ… INHERITANCE SUCCESSFULLY DISTRIBUTED");
    println!("āœ… NO LAWYER FEES");
    println!("āœ… NO COURT PROCESS");
    println!("āœ… FULLY AUTOMATED");
    println!("āœ… PRIVACY PRESERVED");

    println!("\nšŸŽ‰ THIS IS THE FUTURE OF CRYPTO INHERITANCE!");
}