forked from MettaChain/PropChain-contract
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
3760 lines (3316 loc) · 142 KB
/
Copy pathlib.rs
File metadata and controls
3760 lines (3316 loc) · 142 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
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(unexpected_cfgs)]
#![allow(
clippy::too_many_arguments,
clippy::result_large_err,
dead_code,
clippy::needless_borrows_for_generic_args,
clippy::type_complexity,
clippy::vec_init_then_push,
clippy::match_like_matches_macro
)]
use ink::prelude::string::String;
use ink::storage::Mapping;
use propchain_traits::*;
#[cfg(not(feature = "std"))]
use scale_info::prelude::vec::Vec;
#[ink::contract]
mod bridge {
use propchain_traits::{non_reentrant, ReentrancyError, ReentrancyGuard};
use super::*;
include!("errors.rs");
/// Maximum number of entries kept in [`PropertyBridge::pause_audit_log`].
/// When the log reaches this size, the oldest entry is dropped on insert.
const PAUSE_AUDIT_LOG_LIMIT: usize = 256;
const SIGNATURE_BITMAP_BYTES: usize = 32;
const MAX_VALIDATOR_BITMAP_SLOTS: usize = SIGNATURE_BITMAP_BYTES * 8;
impl From<ReentrancyError> for Error {
fn from(_: ReentrancyError) -> Self {
Error::ReentrantCall
}
}
#[derive(Debug, Clone, PartialEq, Eq, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
enum SignatureStorage {
Bitmap([u8; SIGNATURE_BITMAP_BYTES]),
Legacy(Vec<AccountId>),
}
#[derive(Debug, Clone, PartialEq, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
struct StoredBridgeRequestV2 {
request_id: u64,
token_id: TokenId,
source_chain: ChainId,
destination_chain: ChainId,
sender: AccountId,
recipient: AccountId,
required_signatures: u8,
signature_storage: SignatureStorage,
created_at: u64,
expires_at: Option<u64>,
status: BridgeOperationStatus,
multi_hop_status: MultiHopStatus,
route: Vec<ChainId>,
current_hop: u32,
total_gas_estimate: u64,
metadata: PropertyMetadata,
}
#[derive(Debug, Clone, PartialEq, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
struct LegacyStoredBridgeRequest {
request_id: u64,
token_id: TokenId,
source_chain: ChainId,
destination_chain: ChainId,
sender: AccountId,
recipient: AccountId,
required_signatures: u8,
signatures: Vec<AccountId>,
created_at: u64,
expires_at: Option<u64>,
status: BridgeOperationStatus,
multi_hop_status: MultiHopStatus,
route: Vec<ChainId>,
current_hop: u32,
total_gas_estimate: u64,
metadata: PropertyMetadata,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
struct StoredBridgeRequest {
request_id: u64,
token_id: TokenId,
source_chain: ChainId,
destination_chain: ChainId,
sender: AccountId,
recipient: AccountId,
required_signatures: u8,
signature_storage: SignatureStorage,
created_at: u64,
expires_at: Option<u64>,
status: BridgeOperationStatus,
multi_hop_status: MultiHopStatus,
route: Vec<ChainId>,
current_hop: u32,
total_gas_estimate: u64,
metadata: PropertyMetadata,
}
impl scale::Encode for StoredBridgeRequest {
fn size_hint(&self) -> usize {
StoredBridgeRequestV2::from(self.clone()).size_hint()
}
fn encode_to<T: scale::Output + ?Sized>(&self, dest: &mut T) {
StoredBridgeRequestV2::from(self.clone()).encode_to(dest);
}
}
impl scale::Decode for StoredBridgeRequest {
fn decode<I: scale::Input>(input: &mut I) -> Result<Self, scale::Error> {
// Linearise the drain: pre-allocate the destination buffer so
// `Vec::push` does NOT reallocate on every byte. The previous
// `Vec::new() + push` loop was O(n^2) because Vec::new() starts
// at capacity 0 and every push reallocates the entire buffer
// (1 -> 2 -> 4 -> 8 -> ...), and on a 1kB payload the decode
// alone could exceed the block-gas limit (Issue #736).
const INITIAL_CAPACITY: usize = 1024;
let mut bytes: Vec<u8> = Vec::with_capacity(INITIAL_CAPACITY);
while let Ok(byte) = input.read_byte() {
bytes.push(byte);
}
if let Ok(decoded) = <StoredBridgeRequestV2 as scale::Decode>::decode(&mut &bytes[..]) {
return Ok(decoded.into());
}
let legacy = <LegacyStoredBridgeRequest as scale::Decode>::decode(&mut &bytes[..])?;
Ok(legacy.into())
}
}
impl From<StoredBridgeRequest> for StoredBridgeRequestV2 {
fn from(value: StoredBridgeRequest) -> Self {
Self {
request_id: value.request_id,
token_id: value.token_id,
source_chain: value.source_chain,
destination_chain: value.destination_chain,
sender: value.sender,
recipient: value.recipient,
required_signatures: value.required_signatures,
signature_storage: value.signature_storage,
created_at: value.created_at,
expires_at: value.expires_at,
status: value.status,
multi_hop_status: value.multi_hop_status,
route: value.route,
current_hop: value.current_hop,
total_gas_estimate: value.total_gas_estimate,
metadata: value.metadata,
}
}
}
impl From<StoredBridgeRequestV2> for StoredBridgeRequest {
fn from(value: StoredBridgeRequestV2) -> Self {
Self {
request_id: value.request_id,
token_id: value.token_id,
source_chain: value.source_chain,
destination_chain: value.destination_chain,
sender: value.sender,
recipient: value.recipient,
required_signatures: value.required_signatures,
signature_storage: value.signature_storage,
created_at: value.created_at,
expires_at: value.expires_at,
status: value.status,
multi_hop_status: value.multi_hop_status,
route: value.route,
current_hop: value.current_hop,
total_gas_estimate: value.total_gas_estimate,
metadata: value.metadata,
}
}
}
impl From<LegacyStoredBridgeRequest> for StoredBridgeRequest {
fn from(value: LegacyStoredBridgeRequest) -> Self {
Self {
request_id: value.request_id,
token_id: value.token_id,
source_chain: value.source_chain,
destination_chain: value.destination_chain,
sender: value.sender,
recipient: value.recipient,
required_signatures: value.required_signatures,
signature_storage: SignatureStorage::Legacy(value.signatures),
created_at: value.created_at,
expires_at: value.expires_at,
status: value.status,
multi_hop_status: value.multi_hop_status,
route: value.route,
current_hop: value.current_hop,
total_gas_estimate: value.total_gas_estimate,
metadata: value.metadata,
}
}
}
impl StoredBridgeRequest {
fn new(
request_id: u64,
token_id: TokenId,
source_chain: ChainId,
destination_chain: ChainId,
sender: AccountId,
recipient: AccountId,
required_signatures: u8,
created_at: u64,
expires_at: Option<u64>,
route: Vec<ChainId>,
total_gas_estimate: u64,
metadata: PropertyMetadata,
) -> Self {
Self {
request_id,
token_id,
source_chain,
destination_chain,
sender,
recipient,
required_signatures,
signature_storage: SignatureStorage::Bitmap([0; SIGNATURE_BITMAP_BYTES]),
created_at,
expires_at,
status: BridgeOperationStatus::Pending,
multi_hop_status: MultiHopStatus::InProgress,
route,
current_hop: 0,
total_gas_estimate,
metadata,
}
}
fn signature_count(&self) -> u8 {
match &self.signature_storage {
SignatureStorage::Bitmap(bitmap) => bitmap
.iter()
.map(|byte| byte.count_ones() as u16)
.sum::<u16>() as u8,
SignatureStorage::Legacy(signers) => signers.len() as u8,
}
}
fn clear_signatures(&mut self) {
self.signature_storage = SignatureStorage::Bitmap([0; SIGNATURE_BITMAP_BYTES]);
}
}
impl scale::EncodeLike for StoredBridgeRequest {}
/// Emergency multi-sig request data structure
#[derive(Debug, Clone, PartialEq, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub struct EmergencyRequest {
request_id: u64,
request_type: EmergencyRequestType,
proposed_by: AccountId,
signatures: Vec<AccountId>,
created_at: u64,
expires_at: Option<u64>,
executed: bool,
// For pause_bridge: the pause flags and reason
pause_flags: Option<PauseFlags>,
pause_reason: Option<PauseReason>,
pause_detail: Option<String>,
// For freeze_asset: asset address and reason
asset_address: Option<AccountId>,
freeze_reason: Option<String>,
}
/// Types of emergency multi-sig requests
#[derive(Debug, Clone, PartialEq, Eq, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub enum EmergencyRequestType {
PauseBridge,
FreezeAsset,
}
/// Asset freeze information
#[derive(Debug, Clone, PartialEq, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub struct AssetFreezeInfo {
asset_address: AccountId,
frozen_by: AccountId,
frozen_at: u64,
reason: String,
affects_inflight: bool,
}
/// Bridge contract for cross-chain property token transfers
#[ink(storage)]
pub struct PropertyBridge {
/// Bridge configuration
config: BridgeConfig,
/// Multi-signature bridge requests
bridge_requests: Mapping<u64, StoredBridgeRequest>,
/// Bridge transaction history
bridge_history: Mapping<AccountId, Vec<BridgeTransaction>>,
/// Chain-specific information
chain_info: Mapping<ChainId, ChainBridgeInfo>,
/// Transaction verification records
verified_transactions: Mapping<Hash, bool>,
/// Cross-chain DEX settlement intents tracked by the bridge
cross_chain_trades: Mapping<u64, CrossChainTradeIntent>,
/// Per-request cross-chain transaction status tracker. Stores the
/// per-chain status of every bridge request so callers and indexers
/// can observe the full lifecycle on both source and destination.
cross_chain_tx_status: Mapping<u64, CrossChainTxStatus>,
/// Reverse index from a chain-native transaction hash to the bridge
/// `request_id`, enabling status lookups by hash from any chain.
tx_hash_index: Mapping<Hash, u64>,
/// Bridge operators
bridge_operators: Vec<AccountId>,
/// Registered validators for multi-signature cross-chain transactions.
/// Only accounts in this set may sign bridge requests (issue #203).
validators: Vec<AccountId>,
/// Stable per-validator bit positions used for signature bitmaps.
validator_bit_positions: Mapping<AccountId, u8>,
/// Historical bitmap slots. Slots are not recycled so old bitmaps stay readable.
validator_slots: Vec<Option<AccountId>>,
/// Request counter
request_counter: u64,
/// Transaction counter
transaction_counter: u64,
/// Cross-chain trade settlement counter
cross_chain_trade_counter: u64,
/// Admin account
admin: AccountId,
/// Registered ECDSA public keys for optional cryptographic signature verification
operator_public_keys: Mapping<AccountId, [u8; 33]>,
/// Pending admin key rotation request
pending_admin_rotation: Option<propchain_traits::KeyRotationRequest>,
/// Account daily bridge request count for rate limiting
account_daily_requests: Mapping<AccountId, u64>,
/// Account last reset day for rate limiting
account_last_reset_day: Mapping<AccountId, u64>,
/// Chain daily volume for rate limiting
chain_daily_volume: Mapping<ChainId, u128>,
/// Chain last reset day for rate limiting
chain_last_reset_day: Mapping<ChainId, u64>,
/// Account daily volume (amount) for rate limiting (#764)
account_daily_volume: Mapping<AccountId, u128>,
/// Account last reset day for volume rate limiting (#764)
account_daily_volume_last_reset_day: Mapping<AccountId, u64>,
/// Reentrancy protection
reentrancy_guard: ReentrancyGuard,
// ── Emergency pause / circuit-breaker (TASK 2) ──────────────────────────
/// Granular pause flags. Per-operation kill-switches plus a master
/// `all_operations` flag so individual flows can be frozen without a
/// full bridge halt.
pause_flags: PauseFlags,
/// Registered guardians (security incident-responders). Guardians
/// can trigger an emergency pause but only the admin may unpause.
guardians: Vec<AccountId>,
/// Bounded chronological audit log of every pause / unpause event.
/// Capped to `PAUSE_AUDIT_LOG_LIMIT` entries; oldest dropped on
/// overflow to keep storage usage predictable.
pause_audit_log: Vec<PauseAuditEntry>,
/// Tunable thresholds that drive automatic pausing.
suspicious_config: SuspiciousActivityConfig,
/// Per-account counters: number of bridge requests submitted in the
/// most recent observed block. Reset when a new block is observed.
account_block_request_count: Mapping<AccountId, u32>,
/// Per-account: the block number `account_block_request_count`
/// applies to.
account_block_request_block: Mapping<AccountId, u64>,
/// Per-chain rolling 1-hour volume counter (sum of `amount_in` from
/// `register_cross_chain_trade`).
chain_hourly_volume: Mapping<ChainId, u128>,
/// Per-chain: the start-of-hour block timestamp the counter applies to.
chain_hourly_window_start: Mapping<ChainId, u64>,
/// Rolling 1-hour count of `approve = false` signatures.
failed_signatures_window_count: u32,
/// Start-of-hour timestamp the failed-signature counter applies to.
failed_signatures_window_start: u64,
// ── Travel rule (FATF) ──────────────────────────────────────────────
/// Encrypted hash of travel rule data per bridge request (actual data stored off-chain).
travel_rule_data: Mapping<u64, TravelRuleData>,
/// Jurisdiction-specific travel rule thresholds (chain_id -> minimum amount requiring compliance).
travel_rule_thresholds: Mapping<ChainId, u128>,
// ── Emergency multi-sig for pause/freeze operations ────────────────
/// Emergency multi-sig members authorized to trigger pause/freeze operations.
emergency_signers: Vec<AccountId>,
/// Number of signatures required for emergency multi-sig operations.
emergency_threshold: u8,
/// Pending emergency multi-sig requests (request_id -> request data).
emergency_requests: Mapping<u64, EmergencyRequest>,
/// Emergency request counter.
emergency_request_counter: u64,
/// Frozen assets (asset_address -> freeze info).
frozen_assets: Mapping<AccountId, AssetFreezeInfo>,
/// Frozen tokens (token_id -> bool). Freeze-by-token (#12).
frozen_tokens: Mapping<TokenId, bool>,
// ── Batched Merkle verification for performance ────────────────────
/// Batch verification windows keyed by (source_chain, window_id).
/// Stores the Merkle root for each batch window.
batch_merkle_roots: Mapping<(ChainId, u64), Hash>,
/// Transaction to batch window mapping (transaction_hash -> (source_chain, window_id)).
transaction_to_batch: Mapping<Hash, (ChainId, u64)>,
/// Batch window counter per source chain.
batch_window_counter: Mapping<ChainId, u64>,
/// Transactions in each batch window (source_chain, window_id -> Vec<transaction_hash>).
batch_transactions: Mapping<(ChainId, u64), Vec<Hash>>,
/// Batch window size (number of transactions per batch).
batch_window_size: u64,
/// Current batch window start timestamp per source chain.
batch_window_start: Mapping<ChainId, u64>,
/// Batch window duration in seconds.
batch_window_duration: u64,
}
/// Events for bridge operations
#[ink(event)]
pub struct BridgeRequestCreated {
#[ink(topic)]
pub request_id: u64,
#[ink(topic)]
pub token_id: TokenId,
#[ink(topic)]
pub source_chain: ChainId,
#[ink(topic)]
pub destination_chain: ChainId,
#[ink(topic)]
pub requester: AccountId,
}
#[ink(event)]
pub struct BridgeRequestSigned {
#[ink(topic)]
pub request_id: u64,
#[ink(topic)]
pub signer: AccountId,
pub signatures_collected: u8,
pub signatures_required: u8,
}
#[ink(event)]
pub struct BridgeExecuted {
#[ink(topic)]
pub request_id: u64,
#[ink(topic)]
pub token_id: TokenId,
#[ink(topic)]
pub transaction_hash: Hash,
}
#[ink(event)]
pub struct BridgeFailed {
#[ink(topic)]
pub request_id: u64,
#[ink(topic)]
pub token_id: TokenId,
pub error: String,
}
#[ink(event)]
pub struct BridgeRecovered {
#[ink(topic)]
pub request_id: u64,
#[ink(topic)]
pub recovery_action: RecoveryAction,
}
/// Emitted when a bridge transaction is atomically rolled back (#201).
#[ink(event)]
pub struct BridgeRolledBack {
#[ink(topic)]
pub request_id: u64,
#[ink(topic)]
pub token_id: TokenId,
/// Original sender whose funds are now unlocked.
pub requester: AccountId,
/// Human-readable rollback reason for audit trail.
pub reason: String,
/// Block number at which the rollback was executed.
pub rolled_back_at: u32,
}
/// Emitted whenever the per-chain status of a cross-chain transaction
/// changes (creation, leg confirmation, failure, etc.). Off-chain
/// indexers can subscribe to this event to mirror full bridge state.
#[ink(event)]
pub struct CrossChainTxStatusUpdated {
#[ink(topic)]
pub request_id: u64,
#[ink(topic)]
pub chain_id: ChainId,
pub status: ChainTxStatus,
pub overall_status: BridgeOperationStatus,
pub tx_hash: Option<Hash>,
pub confirmations: u32,
pub timestamp: u64,
}
// ── Emergency pause events (TASK 2) ───────────────────────────────────
/// Emitted when the bridge enters (or extends) an emergency-paused state.
#[ink(event)]
pub struct EmergencyPauseTriggered {
#[ink(topic)]
pub triggered_by: AccountId,
pub reason: PauseReason,
pub flags: PauseFlags,
pub detail: Option<String>,
pub block_number: u32,
pub timestamp: u64,
}
/// Emitted when the bridge exits (fully or partially) an emergency-paused state.
#[ink(event)]
pub struct EmergencyUnpaused {
#[ink(topic)]
pub triggered_by: AccountId,
pub flags: PauseFlags,
pub block_number: u32,
pub timestamp: u64,
}
/// Emitted when a guardian is added or removed.
#[ink(event)]
pub struct GuardianSetUpdated {
#[ink(topic)]
pub guardian: AccountId,
/// `true` when added, `false` when removed.
pub added: bool,
}
/// Emitted when the auto-pause subsystem flags suspicious activity
/// (whether or not the threshold is exceeded). Useful for early
/// dashboards / alerting.
#[ink(event)]
pub struct SuspiciousActivityDetected {
#[ink(topic)]
pub reason: PauseReason,
#[ink(topic)]
pub subject: AccountId,
pub chain_id: Option<ChainId>,
pub measured: u128,
pub threshold: u128,
pub triggered_pause: bool,
pub timestamp: u64,
}
// ── Travel rule (FATF) data structure ─────────────────────────────────
/// Originator and beneficiary information required by FATF Recommendation 16.
/// The raw PII is stored off-chain; only the `data_hash` (SHA-256 of the
/// canonical off-chain payload) is persisted on-chain.
#[derive(Debug, Clone, PartialEq, Eq, scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, ink::storage::traits::StorageLayout)
)]
pub struct TravelRuleData {
/// UTF-8 name of the originator (hashed reference; actual name stored off-chain).
pub originator_name: Vec<u8>,
/// On-chain account of the originator.
pub originator_account: AccountId,
/// UTF-8 name of the beneficiary.
pub beneficiary_name: Vec<u8>,
/// On-chain account of the beneficiary.
pub beneficiary_account: AccountId,
/// Transfer amount in the base token unit.
pub transfer_amount: u128,
/// SHA-256 hash of the canonical off-chain compliance payload.
pub data_hash: [u8; 32],
/// Block timestamp at which the data was submitted (set by the contract).
pub submitted_at: u64,
}
/// Emitted when travel rule data is submitted for a bridge request.
#[ink(event)]
pub struct TravelRuleDataSubmitted {
#[ink(topic)]
pub request_id: u64,
#[ink(topic)]
pub originator_account: AccountId,
pub data_hash: [u8; 32],
pub timestamp: u64,
}
/// Emitted when a jurisdiction-specific travel rule threshold is updated.
#[ink(event)]
pub struct TravelRuleThresholdUpdated {
pub chain_id: ChainId,
pub threshold_amount: u128,
pub timestamp: u64,
}
// ── Emergency multi-sig events ────────────────────────────────────────
/// Emitted when an emergency multi-sig request is created.
#[ink(event)]
pub struct EmergencyRequestCreated {
#[ink(topic)]
pub request_id: u64,
#[ink(topic)]
pub request_type: EmergencyRequestType,
#[ink(topic)]
pub proposed_by: AccountId,
pub timestamp: u64,
}
/// Emitted when an emergency multi-sig request is signed.
#[ink(event)]
pub struct EmergencyRequestSigned {
#[ink(topic)]
pub request_id: u64,
#[ink(topic)]
pub signer: AccountId,
pub signatures_collected: u8,
pub signatures_required: u8,
}
/// Emitted when an emergency multi-sig request is executed.
#[ink(event)]
pub struct EmergencyRequestExecuted {
#[ink(topic)]
pub request_id: u64,
#[ink(topic)]
pub request_type: EmergencyRequestType,
#[ink(topic)]
pub executed_by: AccountId,
pub timestamp: u64,
}
/// Emitted when an asset is frozen.
#[ink(event)]
pub struct AssetFrozen {
#[ink(topic)]
pub asset_address: AccountId,
#[ink(topic)]
pub frozen_by: AccountId,
pub reason: String,
pub affects_inflight: bool,
pub timestamp: u64,
}
/// Emitted when an asset freeze is lifted.
#[ink(event)]
pub struct AssetUnfrozen {
#[ink(topic)]
pub asset_address: AccountId,
#[ink(topic)]
pub unfrozen_by: AccountId,
pub timestamp: u64,
}
// ── Token freeze events (#12) ────────────────────────────────────────────
/// Emitted when a token is frozen by ID.
#[ink(event)]
pub struct TokenFrozen {
#[ink(topic)]
pub token_id: TokenId,
#[ink(topic)]
pub frozen_by: AccountId,
pub timestamp: u64,
}
/// Emitted when a token freeze is lifted.
#[ink(event)]
pub struct TokenUnfrozen {
#[ink(topic)]
pub token_id: TokenId,
#[ink(topic)]
pub unfrozen_by: AccountId,
pub timestamp: u64,
}
// ── Batched Merkle verification events ───────────────────────────────
/// Emitted when a new batch verification window is created.
#[ink(event)]
pub struct BatchWindowCreated {
#[ink(topic)]
pub source_chain: ChainId,
pub window_id: u64,
pub window_start: u64,
pub window_duration: u64,
pub timestamp: u64,
}
/// Emitted when a batch Merkle root is submitted for verification.
#[ink(event)]
pub struct BatchMerkleRootSubmitted {
#[ink(topic)]
pub source_chain: ChainId,
pub window_id: u64,
pub merkle_root: Hash,
pub transaction_count: u64,
pub submitted_by: AccountId,
pub timestamp: u64,
}
/// Emitted when a batch Merkle root is verified.
#[ink(event)]
pub struct BatchMerkleRootVerified {
#[ink(topic)]
pub source_chain: ChainId,
pub window_id: u64,
pub merkle_root: Hash,
pub verified_by: AccountId,
pub timestamp: u64,
}
/// Emitted when a transaction is added to a batch window.
#[ink(event)]
pub struct TransactionAddedToBatch {
#[ink(topic)]
pub transaction_hash: Hash,
#[ink(topic)]
pub source_chain: ChainId,
pub window_id: u64,
pub timestamp: u64,
}
impl PropertyBridge {
/// Creates a new PropertyBridge contract
#[ink(constructor)]
pub fn new(
supported_chains: Vec<ChainId>,
min_signatures: u8,
max_signatures: u8,
default_timeout: u64,
gas_limit: u64,
) -> Self {
let caller = Self::env().caller();
let config = BridgeConfig {
supported_chains: supported_chains.clone(),
min_signatures_required: min_signatures,
max_signatures_required: max_signatures,
default_timeout_blocks: default_timeout,
gas_limit_per_bridge: gas_limit,
emergency_pause: false,
metadata_preservation: true,
rate_limit_enabled: true,
max_requests_per_day: 10,
max_value_per_day: 1_000_000_000_000_000_000,
};
// Initialize chain info for supported chains
let mut bridge = Self {
config,
bridge_requests: Mapping::default(),
bridge_history: Mapping::default(),
chain_info: Mapping::default(),
verified_transactions: Mapping::default(),
cross_chain_trades: Mapping::default(),
cross_chain_tx_status: Mapping::default(),
tx_hash_index: Mapping::default(),
bridge_operators: vec![caller],
validators: Vec::new(),
validator_bit_positions: Mapping::default(),
validator_slots: Vec::new(),
request_counter: 0,
transaction_counter: 0,
cross_chain_trade_counter: 0,
admin: caller,
operator_public_keys: Mapping::default(),
pending_admin_rotation: None,
account_daily_requests: Mapping::default(),
account_last_reset_day: Mapping::default(),
chain_daily_volume: Mapping::default(),
chain_last_reset_day: Mapping::default(),
account_daily_volume: Mapping::default(),
account_daily_volume_last_reset_day: Mapping::default(),
reentrancy_guard: ReentrancyGuard::new(),
pause_flags: PauseFlags::none(),
guardians: Vec::new(),
pause_audit_log: Vec::new(),
suspicious_config: SuspiciousActivityConfig::default_config(),
account_block_request_count: Mapping::default(),
account_block_request_block: Mapping::default(),
chain_hourly_volume: Mapping::default(),
chain_hourly_window_start: Mapping::default(),
failed_signatures_window_count: 0,
failed_signatures_window_start: 0,
travel_rule_data: Mapping::default(),
travel_rule_thresholds: Mapping::default(),
emergency_signers: Vec::new(),
emergency_threshold: 2, // Default threshold
emergency_requests: Mapping::default(),
emergency_request_counter: 0,
frozen_assets: Mapping::default(),
frozen_tokens: Mapping::default(),
batch_merkle_roots: Mapping::default(),
transaction_to_batch: Mapping::default(),
batch_window_counter: Mapping::default(),
batch_transactions: Mapping::default(),
batch_window_size: 10, // Default batch size
batch_window_start: Mapping::default(),
batch_window_duration: 300, // Default 5 minutes in seconds
};
// Set up default chain information
for chain_id in supported_chains {
let chain_info = ChainBridgeInfo {
chain_id,
chain_name: format!("Chain-{}", chain_id),
bridge_contract_address: None,
is_active: true,
gas_multiplier: propchain_traits::constants::DEFAULT_GAS_MULTIPLIER,
confirmation_blocks: propchain_traits::constants::DEFAULT_CONFIRMATION_BLOCKS,
supported_tokens: Vec::new(),
chain_daily_limit: 10_000_000_000_000_000_000, // Example large default
};
bridge.chain_info.insert(chain_id, &chain_info);
}
bridge
}
/// Initiates a bridge request with multi-signature requirement
#[ink(message)]
pub fn initiate_bridge_multisig(
&mut self,
token_id: TokenId,
destination_chain: ChainId,
recipient: AccountId,
required_signatures: u8,
timeout_blocks: Option<u64>,
metadata: PropertyMetadata,
) -> Result<u64, Error> {
let caller = self.env().caller();
// Granular pause check: blocks if `new_requests`, `all_operations`,
// or the legacy `BridgeConfig::emergency_pause` is set.
self.ensure_not_paused(BridgeOperation::NewRequest)?;
// Suspicious-activity heuristic: per-block request burst.
// If the burst threshold is hit on this very call, the auto-pause
// kicks in and the offending request is also rejected.
self.track_request_burst(caller)?;
// Validate destination chain
if !self.config.supported_chains.contains(&destination_chain) {
return Err(Error::InvalidChain);
}
// Validate signature requirements
if required_signatures < self.config.min_signatures_required
|| required_signatures > self.config.max_signatures_required
{
return Err(Error::InsufficientSignatures);
}
// Check if caller is authorized (token owner or approved operator)
if !self.is_authorized_for_token(caller, token_id) {
return Err(Error::Unauthorized);
}
// Enforce rate limiting
// For NFT bridge, we count requests but value is 0 here since NFT value isn't strictly defined by amount.
self.check_and_update_rate_limits(caller, destination_chain, 0, true)?;
self.ensure_token_not_frozen(token_id)?;
// Create bridge request
self.request_counter += 1;
let request_id = self.request_counter;
let current_block = u64::from(self.env().block_number());
let expires_at = timeout_blocks.map(|blocks| current_block + blocks);
let request = StoredBridgeRequest::new(
request_id,
token_id,
self.get_current_chain_id(),
destination_chain,
caller,
recipient,
required_signatures,
current_block,
expires_at,
Vec::new(),
0,
metadata,
);
self.bridge_requests.insert(request_id, &request);
// Initialize cross-chain transaction status: source leg starts in
// `Submitted`, destination leg has `NotStarted` until a relayer
// reports inclusion on the destination chain.
self.init_cross_chain_status(
request_id,
token_id,
request.source_chain,
destination_chain,
);
self.env().emit_event(BridgeRequestCreated {
request_id,
token_id,
source_chain: request.source_chain,
destination_chain,
requester: caller,
});
Ok(request_id)
}
/// Initiates a multi-hop bridge request that routes through one or more intermediate chains.
#[ink(message)]
pub fn initiate_multi_hop_bridge(
&mut self,
token_id: TokenId,
route: Vec<ChainId>,
recipient: AccountId,
required_signatures: u8,
timeout_blocks: Option<u64>,
metadata: PropertyMetadata,
) -> Result<u64, Error> {
let caller = self.env().caller();
self.ensure_not_paused(BridgeOperation::NewRequest)?;
self.track_request_burst(caller)?;
if route.len() < 2 {
return Err(Error::InvalidChain);
}
let current_chain = self.get_current_chain_id();
if route[0] == current_chain {
return Err(Error::InvalidChain);
}
if route
.iter()
.any(|chain| !self.config.supported_chains.contains(chain))
{
return Err(Error::InvalidChain);
}
if required_signatures < self.config.min_signatures_required
|| required_signatures > self.config.max_signatures_required
{