rabia-banking-example 0.4.1

Banking ledger state machine implementation example using the Rabia SMR protocol
Documentation
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
//! # Banking SMR Example
//!
//! A banking ledger implementation that demonstrates how to create a complex State Machine
//! Replication (SMR) application using the Rabia consensus protocol.
//!
//! This example shows a more sophisticated SMR implementation with:
//! - Account management
//! - Transfer operations with validation
//! - Transaction history
//! - Balance tracking
//! - Error handling for insufficient funds
//!
//! ## Example Usage
//!
//! ```rust
//! use rabia_banking_example::{BankingSMR, BankingCommand};
//! use rabia_core::smr::StateMachine;
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let mut bank = BankingSMR::new();
//!     
//!     // Create accounts
//!     let create_cmd = BankingCommand::CreateAccount {
//!         account_id: "alice".to_string(),
//!         initial_balance: 1000,
//!     };
//!     let response = bank.apply_command(create_cmd).await;
//!     println!("Account created: {:?}", response);
//!     
//!     Ok(())
//! }
//! ```

use async_trait::async_trait;
use rabia_core::smr::StateMachine;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Account information
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Account {
    /// Account identifier
    pub account_id: String,
    /// Current balance in cents (to avoid floating point precision issues)
    pub balance: i64,
    /// Account creation timestamp
    pub created_at: u64,
    /// Last transaction timestamp
    pub last_transaction_at: u64,
    /// Total number of transactions
    pub transaction_count: u64,
}

impl Account {
    pub fn new(account_id: String, initial_balance: i64) -> Self {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as u64;

        Self {
            account_id,
            balance: initial_balance,
            created_at: now,
            last_transaction_at: now,
            transaction_count: 0,
        }
    }

    pub fn update_balance(&mut self, new_balance: i64) {
        self.balance = new_balance;
        self.last_transaction_at = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis() as u64;
        self.transaction_count += 1;
    }
}

/// Transaction record
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Transaction {
    /// Unique transaction ID
    pub transaction_id: String,
    /// Source account (None for deposits)
    pub from_account: Option<String>,
    /// Destination account (None for withdrawals)
    pub to_account: Option<String>,
    /// Amount in cents
    pub amount: i64,
    /// Transaction timestamp
    pub timestamp: u64,
    /// Transaction type
    pub transaction_type: TransactionType,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum TransactionType {
    Deposit,
    Withdrawal,
    Transfer,
}

/// Commands that can be applied to the banking system
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum BankingCommand {
    /// Create a new account
    CreateAccount {
        account_id: String,
        initial_balance: i64,
    },
    /// Deposit money into an account
    Deposit { account_id: String, amount: i64 },
    /// Withdraw money from an account
    Withdraw { account_id: String, amount: i64 },
    /// Transfer money between accounts
    Transfer {
        from_account: String,
        to_account: String,
        amount: i64,
    },
    /// Get account balance
    GetBalance { account_id: String },
    /// Get account information
    GetAccount { account_id: String },
    /// List all accounts
    ListAccounts,
    /// Get transaction history
    GetTransactionHistory {
        account_id: Option<String>,
        limit: Option<usize>,
    },
}

/// Response from banking operations
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct BankingResponse {
    /// Whether the operation was successful
    pub success: bool,
    /// Result data (account info, balance, etc.)
    pub data: Option<BankingData>,
    /// Error message if operation failed
    pub error: Option<String>,
    /// Transaction ID for operations that create transactions
    pub transaction_id: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum BankingData {
    Account(Account),
    Balance(i64),
    Accounts(Vec<Account>),
    Transactions(Vec<Transaction>),
}

impl BankingResponse {
    pub fn success(data: Option<BankingData>) -> Self {
        Self {
            success: true,
            data,
            error: None,
            transaction_id: None,
        }
    }

    pub fn success_with_transaction(data: Option<BankingData>, transaction_id: String) -> Self {
        Self {
            success: true,
            data,
            error: None,
            transaction_id: Some(transaction_id),
        }
    }

    pub fn error(message: String) -> Self {
        Self {
            success: false,
            data: None,
            error: Some(message),
            transaction_id: None,
        }
    }
}

/// State of the banking state machine
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct BankingState {
    /// All accounts indexed by account ID
    pub accounts: HashMap<String, Account>,
    /// Transaction history
    pub transactions: Vec<Transaction>,
    /// Total number of operations performed
    pub operation_count: u64,
}

/// Banking state machine implementation
#[derive(Debug, Clone)]
pub struct BankingSMR {
    state: BankingState,
}

impl BankingSMR {
    /// Create a new banking state machine
    pub fn new() -> Self {
        Self {
            state: BankingState::default(),
        }
    }

    /// Get the total number of accounts
    pub fn account_count(&self) -> usize {
        self.state.accounts.len()
    }

    /// Get the total number of transactions
    pub fn transaction_count(&self) -> usize {
        self.state.transactions.len()
    }

    /// Get the total number of operations performed
    pub fn operation_count(&self) -> u64 {
        self.state.operation_count
    }

    /// Get total value across all accounts
    pub fn total_value(&self) -> i64 {
        self.state
            .accounts
            .values()
            .map(|account| account.balance)
            .sum()
    }

    fn generate_transaction_id() -> String {
        uuid::Uuid::new_v4().to_string()
    }

    fn validate_amount(amount: i64) -> Result<(), String> {
        if amount <= 0 {
            return Err("Amount must be positive".to_string());
        }
        if amount > 1_000_000_000 {
            // Max $10M per transaction
            return Err("Amount exceeds maximum limit".to_string());
        }
        Ok(())
    }

    fn validate_account_id(account_id: &str) -> Result<(), String> {
        if account_id.is_empty() {
            return Err("Account ID cannot be empty".to_string());
        }
        if account_id.len() > 50 {
            return Err("Account ID too long".to_string());
        }
        Ok(())
    }
}

impl Default for BankingSMR {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl StateMachine for BankingSMR {
    type Command = BankingCommand;
    type Response = BankingResponse;
    type State = BankingState;

    async fn apply_command(&mut self, command: Self::Command) -> Self::Response {
        self.state.operation_count += 1;

        match command {
            BankingCommand::CreateAccount {
                account_id,
                initial_balance,
            } => {
                if let Err(e) = Self::validate_account_id(&account_id) {
                    return BankingResponse::error(e);
                }

                if initial_balance < 0 {
                    return BankingResponse::error(
                        "Initial balance cannot be negative".to_string(),
                    );
                }

                if self.state.accounts.contains_key(&account_id) {
                    return BankingResponse::error("Account already exists".to_string());
                }

                let account = Account::new(account_id.clone(), initial_balance);
                self.state.accounts.insert(account_id, account.clone());

                BankingResponse::success(Some(BankingData::Account(account)))
            }

            BankingCommand::Deposit { account_id, amount } => {
                if let Err(e) = Self::validate_amount(amount) {
                    return BankingResponse::error(e);
                }

                let account = match self.state.accounts.get_mut(&account_id) {
                    Some(account) => account,
                    None => return BankingResponse::error("Account not found".to_string()),
                };

                match account.balance.checked_add(amount) {
                    Some(new_balance) => {
                        account.update_balance(new_balance);

                        let transaction_id = Self::generate_transaction_id();
                        let transaction = Transaction {
                            transaction_id: transaction_id.clone(),
                            from_account: None,
                            to_account: Some(account_id),
                            amount,
                            timestamp: std::time::SystemTime::now()
                                .duration_since(std::time::UNIX_EPOCH)
                                .unwrap_or_default()
                                .as_millis() as u64,
                            transaction_type: TransactionType::Deposit,
                        };
                        self.state.transactions.push(transaction);

                        BankingResponse::success_with_transaction(
                            Some(BankingData::Balance(new_balance)),
                            transaction_id,
                        )
                    }
                    None => BankingResponse::error("Deposit would cause overflow".to_string()),
                }
            }

            BankingCommand::Withdraw { account_id, amount } => {
                if let Err(e) = Self::validate_amount(amount) {
                    return BankingResponse::error(e);
                }

                let account = match self.state.accounts.get_mut(&account_id) {
                    Some(account) => account,
                    None => return BankingResponse::error("Account not found".to_string()),
                };

                if account.balance < amount {
                    return BankingResponse::error("Insufficient funds".to_string());
                }

                let new_balance = account.balance - amount;
                account.update_balance(new_balance);

                let transaction_id = Self::generate_transaction_id();
                let transaction = Transaction {
                    transaction_id: transaction_id.clone(),
                    from_account: Some(account_id),
                    to_account: None,
                    amount,
                    timestamp: std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .unwrap_or_default()
                        .as_millis() as u64,
                    transaction_type: TransactionType::Withdrawal,
                };
                self.state.transactions.push(transaction);

                BankingResponse::success_with_transaction(
                    Some(BankingData::Balance(new_balance)),
                    transaction_id,
                )
            }

            BankingCommand::Transfer {
                from_account,
                to_account,
                amount,
            } => {
                if let Err(e) = Self::validate_amount(amount) {
                    return BankingResponse::error(e);
                }

                if from_account == to_account {
                    return BankingResponse::error("Cannot transfer to same account".to_string());
                }

                // Check if both accounts exist and get their current balances
                let from_balance = match self.state.accounts.get(&from_account) {
                    Some(account) => account.balance,
                    None => return BankingResponse::error("Source account not found".to_string()),
                };

                if !self.state.accounts.contains_key(&to_account) {
                    return BankingResponse::error("Destination account not found".to_string());
                }

                if from_balance < amount {
                    return BankingResponse::error("Insufficient funds".to_string());
                }

                // Perform the transfer
                let from_account_ref = self.state.accounts.get_mut(&from_account).unwrap();
                from_account_ref.update_balance(from_balance - amount);

                let to_account_ref = self.state.accounts.get_mut(&to_account).unwrap();
                let to_new_balance = to_account_ref.balance + amount;
                to_account_ref.update_balance(to_new_balance);

                let transaction_id = Self::generate_transaction_id();
                let transaction = Transaction {
                    transaction_id: transaction_id.clone(),
                    from_account: Some(from_account),
                    to_account: Some(to_account),
                    amount,
                    timestamp: std::time::SystemTime::now()
                        .duration_since(std::time::UNIX_EPOCH)
                        .unwrap_or_default()
                        .as_millis() as u64,
                    transaction_type: TransactionType::Transfer,
                };
                self.state.transactions.push(transaction);

                BankingResponse::success_with_transaction(None, transaction_id)
            }

            BankingCommand::GetBalance { account_id } => {
                match self.state.accounts.get(&account_id) {
                    Some(account) => {
                        BankingResponse::success(Some(BankingData::Balance(account.balance)))
                    }
                    None => BankingResponse::error("Account not found".to_string()),
                }
            }

            BankingCommand::GetAccount { account_id } => {
                match self.state.accounts.get(&account_id) {
                    Some(account) => {
                        BankingResponse::success(Some(BankingData::Account(account.clone())))
                    }
                    None => BankingResponse::error("Account not found".to_string()),
                }
            }

            BankingCommand::ListAccounts => {
                let accounts: Vec<Account> = self.state.accounts.values().cloned().collect();
                BankingResponse::success(Some(BankingData::Accounts(accounts)))
            }

            BankingCommand::GetTransactionHistory { account_id, limit } => {
                let mut transactions: Vec<Transaction> = if let Some(account_id) = account_id {
                    self.state
                        .transactions
                        .iter()
                        .filter(|tx| {
                            tx.from_account.as_ref() == Some(&account_id)
                                || tx.to_account.as_ref() == Some(&account_id)
                        })
                        .cloned()
                        .collect()
                } else {
                    self.state.transactions.clone()
                };

                // Sort by timestamp (newest first)
                transactions.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));

                // Apply limit if specified
                if let Some(limit) = limit {
                    transactions.truncate(limit);
                }

                BankingResponse::success(Some(BankingData::Transactions(transactions)))
            }
        }
    }

    fn get_state(&self) -> Self::State {
        self.state.clone()
    }

    fn set_state(&mut self, state: Self::State) {
        self.state = state;
    }

    fn serialize_state(&self) -> Vec<u8> {
        bincode::serialize(&self.state).unwrap_or_default()
    }

    fn deserialize_state(&mut self, data: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
        self.state = bincode::deserialize(data)?;
        Ok(())
    }

    async fn apply_commands(&mut self, commands: Vec<Self::Command>) -> Vec<Self::Response> {
        let mut responses = Vec::with_capacity(commands.len());
        for command in commands {
            responses.push(self.apply_command(command).await);
        }
        responses
    }

    fn is_deterministic(&self) -> bool {
        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_banking_account_creation() {
        let mut bank = BankingSMR::new();

        let response = bank
            .apply_command(BankingCommand::CreateAccount {
                account_id: "alice".to_string(),
                initial_balance: 1000,
            })
            .await;

        assert!(response.success);
        assert_eq!(bank.account_count(), 1);

        // Test duplicate account creation
        let response = bank
            .apply_command(BankingCommand::CreateAccount {
                account_id: "alice".to_string(),
                initial_balance: 500,
            })
            .await;

        assert!(!response.success);
        assert!(response.error.as_ref().unwrap().contains("already exists"));
    }

    #[tokio::test]
    async fn test_banking_deposit_withdraw() {
        let mut bank = BankingSMR::new();

        // Create account
        bank.apply_command(BankingCommand::CreateAccount {
            account_id: "alice".to_string(),
            initial_balance: 1000,
        })
        .await;

        // Test deposit
        let response = bank
            .apply_command(BankingCommand::Deposit {
                account_id: "alice".to_string(),
                amount: 500,
            })
            .await;

        assert!(response.success);
        assert!(response.transaction_id.is_some());

        // Check balance
        let response = bank
            .apply_command(BankingCommand::GetBalance {
                account_id: "alice".to_string(),
            })
            .await;

        if let Some(BankingData::Balance(balance)) = response.data {
            assert_eq!(balance, 1500);
        } else {
            panic!("Expected balance data");
        }

        // Test withdrawal
        let response = bank
            .apply_command(BankingCommand::Withdraw {
                account_id: "alice".to_string(),
                amount: 200,
            })
            .await;

        assert!(response.success);

        // Test insufficient funds
        let response = bank
            .apply_command(BankingCommand::Withdraw {
                account_id: "alice".to_string(),
                amount: 2000,
            })
            .await;

        assert!(!response.success);
        assert!(response
            .error
            .as_ref()
            .unwrap()
            .contains("Insufficient funds"));
    }

    #[tokio::test]
    async fn test_banking_transfer() {
        let mut bank = BankingSMR::new();

        // Create accounts
        bank.apply_command(BankingCommand::CreateAccount {
            account_id: "alice".to_string(),
            initial_balance: 1000,
        })
        .await;

        bank.apply_command(BankingCommand::CreateAccount {
            account_id: "bob".to_string(),
            initial_balance: 500,
        })
        .await;

        // Test successful transfer
        let response = bank
            .apply_command(BankingCommand::Transfer {
                from_account: "alice".to_string(),
                to_account: "bob".to_string(),
                amount: 300,
            })
            .await;

        assert!(response.success);
        assert!(response.transaction_id.is_some());

        // Check balances
        let alice_response = bank
            .apply_command(BankingCommand::GetBalance {
                account_id: "alice".to_string(),
            })
            .await;
        let bob_response = bank
            .apply_command(BankingCommand::GetBalance {
                account_id: "bob".to_string(),
            })
            .await;

        if let Some(BankingData::Balance(alice_balance)) = alice_response.data {
            assert_eq!(alice_balance, 700);
        }

        if let Some(BankingData::Balance(bob_balance)) = bob_response.data {
            assert_eq!(bob_balance, 800);
        }

        // Test insufficient funds transfer
        let response = bank
            .apply_command(BankingCommand::Transfer {
                from_account: "alice".to_string(),
                to_account: "bob".to_string(),
                amount: 1000,
            })
            .await;

        assert!(!response.success);
        assert!(response
            .error
            .as_ref()
            .unwrap()
            .contains("Insufficient funds"));
    }

    #[tokio::test]
    async fn test_banking_state_serialization() {
        let mut bank = BankingSMR::new();

        // Create accounts and perform operations
        bank.apply_command(BankingCommand::CreateAccount {
            account_id: "alice".to_string(),
            initial_balance: 1000,
        })
        .await;

        bank.apply_command(BankingCommand::Deposit {
            account_id: "alice".to_string(),
            amount: 500,
        })
        .await;

        // Serialize state
        let serialized = bank.serialize_state();
        assert!(!serialized.is_empty());

        // Create new bank and deserialize
        let mut new_bank = BankingSMR::new();
        new_bank.deserialize_state(&serialized).unwrap();

        // Verify state was restored
        assert_eq!(new_bank.account_count(), 1);
        assert_eq!(new_bank.transaction_count(), 1);
        assert_eq!(new_bank.operation_count(), bank.operation_count());

        let response = new_bank
            .apply_command(BankingCommand::GetBalance {
                account_id: "alice".to_string(),
            })
            .await;

        if let Some(BankingData::Balance(balance)) = response.data {
            assert_eq!(balance, 1500);
        }
    }

    #[tokio::test]
    async fn test_banking_transaction_history() {
        let mut bank = BankingSMR::new();

        // Create accounts
        bank.apply_command(BankingCommand::CreateAccount {
            account_id: "alice".to_string(),
            initial_balance: 1000,
        })
        .await;

        bank.apply_command(BankingCommand::CreateAccount {
            account_id: "bob".to_string(),
            initial_balance: 500,
        })
        .await;

        // Perform several transactions
        bank.apply_command(BankingCommand::Deposit {
            account_id: "alice".to_string(),
            amount: 200,
        })
        .await;

        bank.apply_command(BankingCommand::Transfer {
            from_account: "alice".to_string(),
            to_account: "bob".to_string(),
            amount: 300,
        })
        .await;

        // Get all transaction history
        let response = bank
            .apply_command(BankingCommand::GetTransactionHistory {
                account_id: None,
                limit: None,
            })
            .await;

        if let Some(BankingData::Transactions(transactions)) = response.data {
            assert_eq!(transactions.len(), 2);
        }

        // Get Alice's transaction history
        let response = bank
            .apply_command(BankingCommand::GetTransactionHistory {
                account_id: Some("alice".to_string()),
                limit: None,
            })
            .await;

        if let Some(BankingData::Transactions(transactions)) = response.data {
            assert_eq!(transactions.len(), 2); // Deposit + Transfer
        }
    }
}