-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathmanaged_account.rs
More file actions
1505 lines (1319 loc) · 51.5 KB
/
managed_account.rs
File metadata and controls
1505 lines (1319 loc) · 51.5 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
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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Managed account FFI bindings
//!
//! This module provides FFI-compatible managed account functionality that wraps
//! ManagedAccount instances from the key-wallet crate. FFIManagedAccount is a
//! simple wrapper around `Arc<ManagedAccount>` without additional fields.
use std::os::raw::c_uint;
use std::sync::Arc;
use dashcore::hashes::Hash;
use crate::address_pool::{FFIAddressPool, FFIAddressPoolType};
use crate::error::{FFIError, FFIErrorCode};
use crate::types::FFIAccountType;
use crate::wallet_manager::FFIWalletManager;
use crate::FFINetwork;
use key_wallet::account::account_collection::DashpayAccountKey;
use key_wallet::managed_account::address_pool::AddressPool;
use key_wallet::managed_account::ManagedCoreAccount;
use key_wallet::AccountType;
/// Opaque managed account handle that wraps ManagedAccount
pub struct FFIManagedAccount {
/// The underlying managed account
pub(crate) account: Arc<ManagedCoreAccount>,
}
impl FFIManagedAccount {
/// Create a new FFI managed account handle
pub fn new(account: &ManagedCoreAccount) -> Self {
FFIManagedAccount {
account: Arc::new(account.clone()),
}
}
/// Get a reference to the inner managed account
pub fn inner(&self) -> &ManagedCoreAccount {
self.account.as_ref()
}
}
/// FFI Result type for ManagedAccount operations
#[repr(C)]
pub struct FFIManagedAccountResult {
/// The managed account handle if successful, NULL if error
pub account: *mut FFIManagedAccount,
/// Error code (0 = success)
pub error_code: i32,
/// Error message (NULL if success, must be freed by caller if not NULL)
pub error_message: *mut std::os::raw::c_char,
}
impl FFIManagedAccountResult {
/// Create a success result
pub fn success(account: *mut FFIManagedAccount) -> Self {
FFIManagedAccountResult {
account,
error_code: 0,
error_message: std::ptr::null_mut(),
}
}
/// Create an error result
pub fn error(code: FFIErrorCode, message: String) -> Self {
use std::ffi::CString;
let c_message = CString::new(message).unwrap_or_else(|_| {
CString::new("Unknown error").expect("Hardcoded string should never fail")
});
FFIManagedAccountResult {
account: std::ptr::null_mut(),
error_code: code as i32,
error_message: c_message.into_raw(),
}
}
}
/// Get a managed account from a managed wallet
///
/// This function gets a ManagedAccount from the wallet manager's managed wallet info,
/// returning a managed account handle that wraps the ManagedAccount.
///
/// # Safety
///
/// - `manager` must be a valid pointer to an FFIWalletManager instance
/// - `wallet_id` must be a valid pointer to a 32-byte wallet ID
/// - The caller must ensure all pointers remain valid for the duration of this call
/// - The returned account must be freed with `managed_account_free` when no longer needed
#[no_mangle]
pub unsafe extern "C" fn managed_wallet_get_account(
manager: *const FFIWalletManager,
wallet_id: *const u8,
account_index: c_uint,
account_type: FFIAccountType,
) -> FFIManagedAccountResult {
if manager.is_null() {
return FFIManagedAccountResult::error(
FFIErrorCode::InvalidInput,
"Manager is null".to_string(),
);
}
if wallet_id.is_null() {
return FFIManagedAccountResult::error(
FFIErrorCode::InvalidInput,
"Wallet ID is null".to_string(),
);
}
// Get the managed wallet info from the manager
let mut error = FFIError::success();
let managed_wallet_ptr = crate::wallet_manager::wallet_manager_get_managed_wallet_info(
manager, wallet_id, &mut error,
);
if managed_wallet_ptr.is_null() {
return FFIManagedAccountResult::error(
error.code,
if error.message.is_null() {
"Failed to get managed wallet info".to_string()
} else {
let c_str = std::ffi::CStr::from_ptr(error.message);
c_str.to_string_lossy().to_string()
},
);
}
let managed_wallet = &*managed_wallet_ptr;
let account_type_rust = account_type.to_account_type(account_index);
let result = {
use key_wallet::account::StandardAccountType;
let managed_collection = &managed_wallet.inner().accounts;
let managed_account = match account_type_rust {
AccountType::Standard {
index,
standard_account_type,
} => match standard_account_type {
StandardAccountType::BIP44Account => {
managed_collection.standard_bip44_accounts.get(&index)
}
StandardAccountType::BIP32Account => {
managed_collection.standard_bip32_accounts.get(&index)
}
},
AccountType::CoinJoin {
index,
} => managed_collection.coinjoin_accounts.get(&index),
AccountType::IdentityRegistration => managed_collection.identity_registration.as_ref(),
AccountType::IdentityTopUp {
registration_index,
} => managed_collection.identity_topup.get(®istration_index),
AccountType::IdentityTopUpNotBoundToIdentity => {
managed_collection.identity_topup_not_bound.as_ref()
}
AccountType::IdentityInvitation => managed_collection.identity_invitation.as_ref(),
AccountType::ProviderVotingKeys => managed_collection.provider_voting_keys.as_ref(),
AccountType::ProviderOwnerKeys => managed_collection.provider_owner_keys.as_ref(),
AccountType::ProviderOperatorKeys => managed_collection.provider_operator_keys.as_ref(),
AccountType::ProviderPlatformKeys => managed_collection.provider_platform_keys.as_ref(),
AccountType::DashpayReceivingFunds {
..
} => None,
AccountType::DashpayExternalAccount {
..
} => None,
AccountType::PlatformPayment {
..
} => None,
};
match managed_account {
Some(account) => {
let ffi_account = FFIManagedAccount::new(account);
FFIManagedAccountResult::success(Box::into_raw(Box::new(ffi_account)))
}
None => FFIManagedAccountResult::error(
FFIErrorCode::NotFound,
"Account not found".to_string(),
),
}
};
// Clean up the managed wallet pointer
crate::managed_wallet::managed_wallet_info_free(managed_wallet_ptr);
result
}
/// Get a managed IdentityTopUp account with a specific registration index
///
/// This is used for top-up accounts that are bound to a specific identity.
/// Returns a managed account handle that wraps the ManagedAccount.
///
/// # Safety
///
/// - `manager` must be a valid pointer to an FFIWalletManager instance
/// - `wallet_id` must be a valid pointer to a 32-byte wallet ID
/// - The caller must ensure all pointers remain valid for the duration of this call
/// - The returned account must be freed with `managed_account_free` when no longer needed
#[no_mangle]
pub unsafe extern "C" fn managed_wallet_get_top_up_account_with_registration_index(
manager: *const FFIWalletManager,
wallet_id: *const u8,
registration_index: c_uint,
) -> FFIManagedAccountResult {
if manager.is_null() {
return FFIManagedAccountResult::error(
FFIErrorCode::InvalidInput,
"Manager is null".to_string(),
);
}
if wallet_id.is_null() {
return FFIManagedAccountResult::error(
FFIErrorCode::InvalidInput,
"Wallet ID is null".to_string(),
);
}
// Get the managed wallet info from the manager
let mut error = FFIError::success();
let managed_wallet_ptr = crate::wallet_manager::wallet_manager_get_managed_wallet_info(
manager, wallet_id, &mut error,
);
if managed_wallet_ptr.is_null() {
return FFIManagedAccountResult::error(
error.code,
if error.message.is_null() {
"Failed to get managed wallet info".to_string()
} else {
let c_str = std::ffi::CStr::from_ptr(error.message);
c_str.to_string_lossy().to_string()
},
);
}
let managed_wallet = &*managed_wallet_ptr;
let result = match managed_wallet.inner().accounts.identity_topup.get(®istration_index) {
Some(account) => {
let ffi_account = FFIManagedAccount::new(account);
FFIManagedAccountResult::success(Box::into_raw(Box::new(ffi_account)))
}
None => FFIManagedAccountResult::error(
FFIErrorCode::NotFound,
format!(
"IdentityTopUp account for registration index {} not found",
registration_index
),
),
};
// Clean up the managed wallet pointer
crate::managed_wallet::managed_wallet_info_free(managed_wallet_ptr);
result
}
/// Get a managed DashPay receiving funds account by composite key
///
/// # Safety
/// - `manager`, `wallet_id` must be valid
/// - `user_identity_id` and `friend_identity_id` must each point to 32 bytes
#[no_mangle]
pub unsafe extern "C" fn managed_wallet_get_dashpay_receiving_account(
manager: *const FFIWalletManager,
wallet_id: *const u8,
account_index: c_uint,
user_identity_id: *const u8,
friend_identity_id: *const u8,
) -> FFIManagedAccountResult {
if manager.is_null()
|| wallet_id.is_null()
|| user_identity_id.is_null()
|| friend_identity_id.is_null()
{
return FFIManagedAccountResult::error(
FFIErrorCode::InvalidInput,
"Null pointer provided".to_string(),
);
}
let mut user_id = [0u8; 32];
let mut friend_id = [0u8; 32];
core::ptr::copy_nonoverlapping(user_identity_id, user_id.as_mut_ptr(), 32);
core::ptr::copy_nonoverlapping(friend_identity_id, friend_id.as_mut_ptr(), 32);
let key = DashpayAccountKey {
index: account_index,
user_identity_id: user_id,
friend_identity_id: friend_id,
};
let mut error = FFIError::success();
let managed_wallet_ptr = crate::wallet_manager::wallet_manager_get_managed_wallet_info(
manager, wallet_id, &mut error,
);
if managed_wallet_ptr.is_null() {
return FFIManagedAccountResult::error(
error.code,
if error.message.is_null() {
"Failed to get managed wallet info".to_string()
} else {
std::ffi::CStr::from_ptr(error.message).to_string_lossy().to_string()
},
);
}
let managed_wallet = &*managed_wallet_ptr;
let result = match managed_wallet.inner().accounts.dashpay_receival_accounts.get(&key) {
Some(account) => FFIManagedAccountResult::success(Box::into_raw(Box::new(
FFIManagedAccount::new(account),
))),
None => {
FFIManagedAccountResult::error(FFIErrorCode::NotFound, "Account not found".to_string())
}
};
crate::managed_wallet::managed_wallet_info_free(managed_wallet_ptr);
result
}
/// Get a managed DashPay external account by composite key
///
/// # Safety
/// - Pointers must be valid
#[no_mangle]
pub unsafe extern "C" fn managed_wallet_get_dashpay_external_account(
manager: *const FFIWalletManager,
wallet_id: *const u8,
account_index: c_uint,
user_identity_id: *const u8,
friend_identity_id: *const u8,
) -> FFIManagedAccountResult {
if manager.is_null()
|| wallet_id.is_null()
|| user_identity_id.is_null()
|| friend_identity_id.is_null()
{
return FFIManagedAccountResult::error(
FFIErrorCode::InvalidInput,
"Null pointer provided".to_string(),
);
}
let mut user_id = [0u8; 32];
let mut friend_id = [0u8; 32];
core::ptr::copy_nonoverlapping(user_identity_id, user_id.as_mut_ptr(), 32);
core::ptr::copy_nonoverlapping(friend_identity_id, friend_id.as_mut_ptr(), 32);
let key = DashpayAccountKey {
index: account_index,
user_identity_id: user_id,
friend_identity_id: friend_id,
};
let mut error = FFIError::success();
let managed_wallet_ptr = crate::wallet_manager::wallet_manager_get_managed_wallet_info(
manager, wallet_id, &mut error,
);
if managed_wallet_ptr.is_null() {
return FFIManagedAccountResult::error(
error.code,
if error.message.is_null() {
"Failed to get managed wallet info".to_string()
} else {
std::ffi::CStr::from_ptr(error.message).to_string_lossy().to_string()
},
);
}
let managed_wallet = &*managed_wallet_ptr;
let result = match managed_wallet.inner().accounts.dashpay_external_accounts.get(&key) {
Some(account) => FFIManagedAccountResult::success(Box::into_raw(Box::new(
FFIManagedAccount::new(account),
))),
None => {
FFIManagedAccountResult::error(FFIErrorCode::NotFound, "Account not found".to_string())
}
};
crate::managed_wallet::managed_wallet_info_free(managed_wallet_ptr);
result
}
/// Get the network of a managed account
///
/// # Safety
///
/// - `account` must be a valid pointer to an FFIManagedAccount instance
/// - Returns `FFINetwork::Dash` if the account is null
#[no_mangle]
pub unsafe extern "C" fn managed_account_get_network(
account: *const FFIManagedAccount,
) -> FFINetwork {
if account.is_null() {
return FFINetwork::Dash;
}
let account = &*account;
account.inner().network.into()
}
/// Get the parent wallet ID of a managed account
///
/// Note: ManagedAccount doesn't store the parent wallet ID directly.
/// The wallet ID is typically known from the context (e.g., when getting the account from a managed wallet).
///
/// # Safety
///
/// - `wallet_id` must be a valid pointer to a 32-byte wallet ID buffer that was provided by the caller
/// - The returned pointer is the same as the input pointer for convenience
/// - The caller must not free the returned pointer as it's the same as the input
#[no_mangle]
pub unsafe extern "C" fn managed_account_get_parent_wallet_id(wallet_id: *const u8) -> *const u8 {
// Simply return the wallet_id that was passed in
// This function exists for API consistency but ManagedAccount doesn't store parent wallet ID
wallet_id
}
/// Get the account type of a managed account
///
/// # Safety
///
/// - `account` must be a valid pointer to an FFIManagedAccount instance
/// - `index_out` must be a valid pointer to receive the account index (or null)
#[no_mangle]
pub unsafe extern "C" fn managed_account_get_account_type(
account: *const FFIManagedAccount,
index_out: *mut c_uint,
) -> FFIAccountType {
if account.is_null() {
return FFIAccountType::StandardBIP44; // Default type
}
let account = &*account;
let managed_account = account.inner();
let account_type_rust = managed_account.account_type.to_account_type();
// Set the index if output pointer is provided
if !index_out.is_null() {
*index_out = account_type_rust.index().unwrap_or(0);
}
// Convert to FFI account type
match account_type_rust {
AccountType::Standard {
standard_account_type,
..
} => {
use key_wallet::account::StandardAccountType;
match standard_account_type {
StandardAccountType::BIP44Account => FFIAccountType::StandardBIP44,
StandardAccountType::BIP32Account => FFIAccountType::StandardBIP32,
}
}
AccountType::CoinJoin {
..
} => FFIAccountType::CoinJoin,
AccountType::IdentityRegistration => FFIAccountType::IdentityRegistration,
AccountType::IdentityTopUp {
..
} => FFIAccountType::IdentityTopUp,
AccountType::IdentityTopUpNotBoundToIdentity => {
FFIAccountType::IdentityTopUpNotBoundToIdentity
}
AccountType::IdentityInvitation => FFIAccountType::IdentityInvitation,
AccountType::ProviderVotingKeys => FFIAccountType::ProviderVotingKeys,
AccountType::ProviderOwnerKeys => FFIAccountType::ProviderOwnerKeys,
AccountType::ProviderOperatorKeys => FFIAccountType::ProviderOperatorKeys,
AccountType::ProviderPlatformKeys => FFIAccountType::ProviderPlatformKeys,
AccountType::DashpayReceivingFunds {
..
} => FFIAccountType::DashpayReceivingFunds,
AccountType::DashpayExternalAccount {
..
} => FFIAccountType::DashpayExternalAccount,
AccountType::PlatformPayment {
..
} => FFIAccountType::PlatformPayment,
}
}
/// Check if a managed account is watch-only
///
/// # Safety
///
/// - `account` must be a valid pointer to an FFIManagedAccount instance
#[no_mangle]
pub unsafe extern "C" fn managed_account_get_is_watch_only(
account: *const FFIManagedAccount,
) -> bool {
if account.is_null() {
return false;
}
let account = &*account;
account.inner().is_watch_only
}
/// Get the balance of a managed account
///
/// # Safety
///
/// - `account` must be a valid pointer to an FFIManagedAccount instance
/// - `balance_out` must be a valid pointer to an FFIBalance structure
#[no_mangle]
pub unsafe extern "C" fn managed_account_get_balance(
account: *const FFIManagedAccount,
balance_out: *mut crate::types::FFIBalance,
) -> bool {
if account.is_null() || balance_out.is_null() {
return false;
}
let account = &*account;
let balance = &account.inner().balance;
*balance_out = crate::types::FFIBalance {
confirmed: balance.spendable(),
unconfirmed: balance.unconfirmed(),
immature: balance.immature(),
locked: balance.locked(),
total: balance.total(),
};
true
}
/// Get the number of transactions in a managed account
///
/// # Safety
///
/// - `account` must be a valid pointer to an FFIManagedAccount instance
#[no_mangle]
pub unsafe extern "C" fn managed_account_get_transaction_count(
account: *const FFIManagedAccount,
) -> c_uint {
if account.is_null() {
return 0;
}
let account = &*account;
account.inner().transactions.len() as c_uint
}
/// Get the number of UTXOs in a managed account
///
/// # Safety
///
/// - `account` must be a valid pointer to an FFIManagedAccount instance
#[no_mangle]
pub unsafe extern "C" fn managed_account_get_utxo_count(
account: *const FFIManagedAccount,
) -> c_uint {
if account.is_null() {
return 0;
}
let account = &*account;
account.inner().utxos.len() as c_uint
}
/// FFI-compatible transaction record
#[repr(C)]
pub struct FFITransactionRecord {
/// Transaction ID (32 bytes)
pub txid: [u8; 32],
/// Net amount for this account (positive = received, negative = sent)
pub net_amount: i64,
/// Block height if confirmed, 0 if unconfirmed
pub height: u32,
/// Block hash if confirmed (32 bytes), all zeros if unconfirmed
pub block_hash: [u8; 32],
/// Unix timestamp
pub timestamp: u64,
/// Fee if known, 0 if unknown
pub fee: u64,
/// Whether this is our transaction
pub is_ours: bool,
}
/// Get all transactions from a managed account
///
/// Returns an array of FFITransactionRecord structures.
///
/// # Safety
///
/// - `account` must be a valid pointer to an FFIManagedAccount instance
/// - `transactions_out` must be a valid pointer to receive the transactions array pointer
/// - `count_out` must be a valid pointer to receive the count
/// - The caller must free the returned array using `managed_account_free_transactions`
#[no_mangle]
pub unsafe extern "C" fn managed_account_get_transactions(
account: *const FFIManagedAccount,
transactions_out: *mut *mut FFITransactionRecord,
count_out: *mut usize,
) -> bool {
if account.is_null() || transactions_out.is_null() || count_out.is_null() {
return false;
}
let account = &*account;
let transactions = &account.inner().transactions;
if transactions.is_empty() {
*transactions_out = std::ptr::null_mut();
*count_out = 0;
return true;
}
// Allocate array for transaction records
let count = transactions.len();
let layout = match std::alloc::Layout::array::<FFITransactionRecord>(count) {
Ok(layout) => layout,
Err(_) => return false,
};
let ptr = std::alloc::alloc(layout) as *mut FFITransactionRecord;
if ptr.is_null() {
return false;
}
// Copy transaction data into FFI structures
for (i, (_txid, record)) in transactions.iter().enumerate() {
let ffi_record = &mut *ptr.add(i);
// Copy txid
ffi_record.txid = record.txid.to_byte_array();
// Copy net amount
ffi_record.net_amount = record.net_amount;
// Copy height (0 if unconfirmed)
ffi_record.height = record.height.unwrap_or(0);
// Copy block hash (zeros if unconfirmed)
if let Some(block_hash) = record.block_hash {
ffi_record.block_hash = block_hash.to_byte_array();
} else {
ffi_record.block_hash = [0u8; 32];
}
// Copy timestamp
ffi_record.timestamp = record.timestamp;
// Copy fee (0 if unknown)
ffi_record.fee = record.fee.unwrap_or(0);
// Copy is_ours flag
ffi_record.is_ours = record.is_ours;
}
*transactions_out = ptr;
*count_out = count;
true
}
/// Free transactions array returned by managed_account_get_transactions
///
/// # Safety
///
/// - `transactions` must be a pointer returned by `managed_account_get_transactions`
/// - `count` must be the count returned by `managed_account_get_transactions`
/// - This function must only be called once per allocation
#[no_mangle]
pub unsafe extern "C" fn managed_account_free_transactions(
transactions: *mut FFITransactionRecord,
count: usize,
) {
if !transactions.is_null() && count > 0 {
let layout = match std::alloc::Layout::array::<FFITransactionRecord>(count) {
Ok(layout) => layout,
Err(_) => return,
};
std::alloc::dealloc(transactions as *mut u8, layout);
}
}
/// Free a managed account handle
///
/// # Safety
///
/// - `account` must be a valid pointer to an FFIManagedAccount that was allocated by this library
/// - The pointer must not be used after calling this function
/// - This function must only be called once per allocation
#[no_mangle]
pub unsafe extern "C" fn managed_account_free(account: *mut FFIManagedAccount) {
if !account.is_null() {
let _ = Box::from_raw(account);
}
}
/// Free a managed account result's error message (if any)
/// Note: This does NOT free the account handle itself - use managed_account_free for that
///
/// # Safety
///
/// - `result` must be a valid pointer to an FFIManagedAccountResult
/// - The error_message field must be either null or a valid CString allocated by this library
/// - The caller must ensure the result pointer remains valid for the duration of this call
#[no_mangle]
pub unsafe extern "C" fn managed_account_result_free_error(result: *mut FFIManagedAccountResult) {
if !result.is_null() {
let result = &mut *result;
if !result.error_message.is_null() {
let _ = std::ffi::CString::from_raw(result.error_message);
result.error_message = std::ptr::null_mut();
}
}
}
/// Get number of accounts in a managed wallet
///
/// # Safety
///
/// - `manager` must be a valid pointer to an FFIWalletManager instance
/// - `wallet_id` must be a valid pointer to a 32-byte wallet ID
/// - `error` must be a valid pointer to an FFIError structure or null
/// - The caller must ensure all pointers remain valid for the duration of this call
#[no_mangle]
pub unsafe extern "C" fn managed_wallet_get_account_count(
manager: *const FFIWalletManager,
wallet_id: *const u8,
error: *mut FFIError,
) -> c_uint {
if manager.is_null() || wallet_id.is_null() {
FFIError::set_error(error, FFIErrorCode::InvalidInput, "Null pointer provided".to_string());
return 0;
}
// Get the wallet from the manager
let wallet_ptr = crate::wallet_manager::wallet_manager_get_wallet(manager, wallet_id, error);
if wallet_ptr.is_null() {
// Error already set by wallet_manager_get_wallet
return 0;
}
let wallet = &*wallet_ptr;
FFIError::set_success(error);
let accounts = &wallet.inner().accounts;
let count = accounts.standard_bip44_accounts.len()
+ accounts.standard_bip32_accounts.len()
+ accounts.coinjoin_accounts.len()
+ accounts.identity_registration.is_some() as usize
+ accounts.identity_topup.len();
// Clean up the wallet pointer
crate::wallet::wallet_free_const(wallet_ptr);
count as c_uint
}
// Note: BLS and EdDSA accounts are handled through regular FFIManagedAccount
// since ManagedAccountCollection stores all accounts as ManagedAccount type
/// Get the account index from a managed account
///
/// Returns the primary account index for Standard and CoinJoin accounts.
/// Returns 0 for account types that don't have an index (like Identity or Provider accounts).
///
/// # Safety
///
/// - `account` must be a valid pointer to an FFIManagedAccount instance
#[no_mangle]
pub unsafe extern "C" fn managed_account_get_index(account: *const FFIManagedAccount) -> c_uint {
if account.is_null() {
return 0;
}
let account = &*account;
account.inner().account_type.index_or_default()
}
/// Get the external address pool from a managed account
///
/// This function returns the external (receive) address pool for Standard accounts.
/// Returns NULL for account types that don't have separate external/internal pools.
///
/// # Safety
///
/// - `account` must be a valid pointer to an FFIManagedAccount instance
/// - The returned pool must be freed with `address_pool_free` when no longer needed
#[no_mangle]
pub unsafe extern "C" fn managed_account_get_external_address_pool(
account: *const FFIManagedAccount,
) -> *mut FFIAddressPool {
if account.is_null() {
return std::ptr::null_mut();
}
let account = &*account;
let managed_account = account.inner();
// Get external address pool if this is a standard account
match &managed_account.account_type {
key_wallet::managed_account::managed_account_type::ManagedAccountType::Standard {
external_addresses,
..
} => {
let ffi_pool = FFIAddressPool {
pool: external_addresses as *const AddressPool as *mut AddressPool,
pool_type: FFIAddressPoolType::External,
};
Box::into_raw(Box::new(ffi_pool))
}
_ => std::ptr::null_mut(),
}
}
/// Get the internal address pool from a managed account
///
/// This function returns the internal (change) address pool for Standard accounts.
/// Returns NULL for account types that don't have separate external/internal pools.
///
/// # Safety
///
/// - `account` must be a valid pointer to an FFIManagedAccount instance
/// - The returned pool must be freed with `address_pool_free` when no longer needed
#[no_mangle]
pub unsafe extern "C" fn managed_account_get_internal_address_pool(
account: *const FFIManagedAccount,
) -> *mut FFIAddressPool {
if account.is_null() {
return std::ptr::null_mut();
}
let account = &*account;
let managed_account = account.inner();
// Get internal address pool if this is a standard account
match &managed_account.account_type {
key_wallet::managed_account::managed_account_type::ManagedAccountType::Standard {
internal_addresses,
..
} => {
let ffi_pool = FFIAddressPool {
pool: internal_addresses as *const AddressPool as *mut AddressPool,
pool_type: FFIAddressPoolType::Internal,
};
Box::into_raw(Box::new(ffi_pool))
}
_ => std::ptr::null_mut(),
}
}
/// Get an address pool from a managed account by type
///
/// This function returns the appropriate address pool based on the pool type parameter.
/// For Standard accounts with External/Internal pool types, returns the corresponding pool.
/// For non-standard accounts with Single pool type, returns their single address pool.
///
/// # Safety
///
/// - `manager` must be a valid pointer to an FFIWalletManager instance
/// - `account` must be a valid pointer to an FFIManagedAccount instance
/// - `wallet_id` must be a valid pointer to a 32-byte wallet ID
/// - The returned pool must be freed with `address_pool_free` when no longer needed
#[no_mangle]
pub unsafe extern "C" fn managed_account_get_address_pool(
account: *const FFIManagedAccount,
pool_type: FFIAddressPoolType,
) -> *mut FFIAddressPool {
if account.is_null() {
return std::ptr::null_mut();
}
let account = &*account;
let managed_account = account.inner();
use key_wallet::managed_account::managed_account_type::ManagedAccountType;
match pool_type {
FFIAddressPoolType::External => {
// Only standard accounts have external pools
match &managed_account.account_type {
ManagedAccountType::Standard {
external_addresses,
..
} => {
let ffi_pool = FFIAddressPool {
pool: external_addresses as *const AddressPool as *mut AddressPool,
pool_type: FFIAddressPoolType::External,
};
Box::into_raw(Box::new(ffi_pool))
}
_ => std::ptr::null_mut(),
}
}
FFIAddressPoolType::Internal => {
// Only standard accounts have internal pools
match &managed_account.account_type {
ManagedAccountType::Standard {
internal_addresses,
..
} => {
let ffi_pool = FFIAddressPool {
pool: internal_addresses as *const AddressPool as *mut AddressPool,
pool_type: FFIAddressPoolType::Internal,
};
Box::into_raw(Box::new(ffi_pool))
}
_ => std::ptr::null_mut(),
}
}
FFIAddressPoolType::Single => {
// Get the single address pool for non-standard accounts
let pool_ref = match &managed_account.account_type {
ManagedAccountType::Standard {
..
} => {
// Standard accounts don't have a "single" pool
return std::ptr::null_mut();
}
ManagedAccountType::CoinJoin {
addresses,
..
} => addresses,
ManagedAccountType::IdentityRegistration {
addresses,
} => addresses,
ManagedAccountType::IdentityTopUp {
addresses,
..
} => addresses,
ManagedAccountType::IdentityTopUpNotBoundToIdentity {
addresses,
} => addresses,
ManagedAccountType::IdentityInvitation {
addresses,
} => addresses,
ManagedAccountType::ProviderVotingKeys {
addresses,
} => addresses,
ManagedAccountType::ProviderOwnerKeys {
addresses,
} => addresses,
ManagedAccountType::ProviderOperatorKeys {
addresses,
} => addresses,
ManagedAccountType::ProviderPlatformKeys {
addresses,
} => addresses,
ManagedAccountType::DashpayReceivingFunds {
addresses,
..
} => addresses,
ManagedAccountType::DashpayExternalAccount {
addresses,
..
} => addresses,
ManagedAccountType::PlatformPayment {
addresses,
..
} => addresses,
};
let ffi_pool = FFIAddressPool {
pool: pool_ref as *const AddressPool as *mut AddressPool,
pool_type: FFIAddressPoolType::Single,
};
Box::into_raw(Box::new(ffi_pool))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::address_pool::address_pool_free;
use crate::types::{FFIAccountCreationOptionType, FFIWalletAccountCreationOptions};
use crate::wallet_manager::{
wallet_manager_add_wallet_from_mnemonic_with_options, wallet_manager_create,
wallet_manager_free, wallet_manager_free_wallet_ids, wallet_manager_get_wallet_ids,
};
use crate::FFINetwork;
use std::ffi::CString;
use std::ptr;
const TEST_MNEMONIC: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about";
#[test]
fn test_managed_account_basic() {
unsafe {
let mut error = FFIError::success();
// Create wallet manager
let manager = wallet_manager_create(FFINetwork::Testnet, &mut error);
assert!(!manager.is_null());
assert_eq!(error.code, FFIErrorCode::Success);
// Add a wallet with default accounts
let mnemonic = CString::new(TEST_MNEMONIC).unwrap();
let passphrase = CString::new("").unwrap();
let success = wallet_manager_add_wallet_from_mnemonic_with_options(
manager,
mnemonic.as_ptr(),
passphrase.as_ptr(),
ptr::null(),
&mut error,
);