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
728 lines (626 loc) · 25.6 KB
/
Copy pathlib.rs
File metadata and controls
728 lines (626 loc) · 25.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
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
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(unexpected_cfgs)]
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 super::*;
/// Error types for the bridge contract
#[derive(Debug, PartialEq, Eq, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum Error {
/// Caller is not authorized
Unauthorized,
/// Token does not exist
TokenNotFound,
/// Invalid chain ID
InvalidChain,
/// Bridge not supported for this token
BridgeNotSupported,
/// Insufficient signatures collected
InsufficientSignatures,
/// Bridge request has expired
RequestExpired,
/// Already signed this request
AlreadySigned,
/// Invalid bridge request
InvalidRequest,
/// Bridge operations are paused
BridgePaused,
/// Invalid metadata
InvalidMetadata,
/// Duplicate bridge request
DuplicateRequest,
/// Gas limit exceeded
GasLimitExceeded,
}
impl core::fmt::Display for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Error::Unauthorized => write!(f, "Caller is not authorized"),
Error::TokenNotFound => write!(f, "Token does not exist"),
Error::InvalidChain => write!(f, "Invalid chain ID"),
Error::BridgeNotSupported => write!(f, "Bridge not supported for this token"),
Error::InsufficientSignatures => write!(f, "Insufficient signatures collected"),
Error::RequestExpired => write!(f, "Bridge request has expired"),
Error::AlreadySigned => write!(f, "Already signed this request"),
Error::InvalidRequest => write!(f, "Invalid bridge request"),
Error::BridgePaused => write!(f, "Bridge operations are paused"),
Error::InvalidMetadata => write!(f, "Invalid metadata"),
Error::DuplicateRequest => write!(f, "Duplicate bridge request"),
Error::GasLimitExceeded => write!(f, "Gas limit exceeded"),
}
}
}
impl ContractError for Error {
fn error_code(&self) -> u32 {
match self {
Error::Unauthorized => bridge_codes::BRIDGE_UNAUTHORIZED,
Error::TokenNotFound => bridge_codes::BRIDGE_TOKEN_NOT_FOUND,
Error::InvalidChain => bridge_codes::BRIDGE_INVALID_CHAIN,
Error::BridgeNotSupported => bridge_codes::BRIDGE_NOT_SUPPORTED,
Error::InsufficientSignatures => bridge_codes::BRIDGE_INSUFFICIENT_SIGNATURES,
Error::RequestExpired => bridge_codes::BRIDGE_REQUEST_EXPIRED,
Error::AlreadySigned => bridge_codes::BRIDGE_ALREADY_SIGNED,
Error::InvalidRequest => bridge_codes::BRIDGE_INVALID_REQUEST,
Error::BridgePaused => bridge_codes::BRIDGE_PAUSED,
Error::InvalidMetadata => bridge_codes::BRIDGE_INVALID_METADATA,
Error::DuplicateRequest => bridge_codes::BRIDGE_DUPLICATE_REQUEST,
Error::GasLimitExceeded => bridge_codes::BRIDGE_GAS_LIMIT_EXCEEDED,
}
}
fn error_description(&self) -> &'static str {
match self {
Error::Unauthorized => "Caller does not have permission to perform this operation",
Error::TokenNotFound => "The specified token does not exist",
Error::InvalidChain => "The destination chain ID is invalid",
Error::BridgeNotSupported => "Cross-chain bridging is not supported for this token",
Error::InsufficientSignatures => "Not enough signatures collected for bridge operation",
Error::RequestExpired => "The bridge request has expired and can no longer be executed",
Error::AlreadySigned => "You have already signed this bridge request",
Error::InvalidRequest => "The bridge request is invalid or malformed",
Error::BridgePaused => "Bridge operations are temporarily paused",
Error::InvalidMetadata => "The token metadata is invalid",
Error::DuplicateRequest => "A bridge request with these parameters already exists",
Error::GasLimitExceeded => "The operation exceeded the gas limit",
}
}
fn error_category(&self) -> ErrorCategory {
ErrorCategory::Bridge
}
}
/// 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, MultisigBridgeRequest>,
/// 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>,
/// Bridge operators
bridge_operators: Vec<AccountId>,
/// Request counter
request_counter: u64,
/// Transaction counter
transaction_counter: u64,
/// Admin account
admin: AccountId,
}
/// 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,
}
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,
};
// 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(),
bridge_operators: vec![caller],
request_counter: 0,
transaction_counter: 0,
admin: caller,
};
// 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: 100, // 1.0x multiplier
confirmation_blocks: 6, // 6 block confirmations
supported_tokens: Vec::new(),
};
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();
// Check if bridge is paused
if self.config.emergency_pause {
return Err(Error::BridgePaused);
}
// 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);
}
// 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 = MultisigBridgeRequest {
request_id,
token_id,
source_chain: self.get_current_chain_id(),
destination_chain,
sender: caller,
recipient,
required_signatures,
signatures: Vec::new(),
created_at: current_block,
expires_at,
status: BridgeOperationStatus::Pending,
metadata,
};
self.bridge_requests.insert(request_id, &request);
self.env().emit_event(BridgeRequestCreated {
request_id,
token_id,
source_chain: request.source_chain,
destination_chain,
requester: caller,
});
Ok(request_id)
}
/// Signs a bridge request
#[ink(message)]
pub fn sign_bridge_request(&mut self, request_id: u64, approve: bool) -> Result<(), Error> {
let caller = self.env().caller();
// Check if caller is a bridge operator
if !self.bridge_operators.contains(&caller) {
return Err(Error::Unauthorized);
}
let mut request = self
.bridge_requests
.get(request_id)
.ok_or(Error::InvalidRequest)?;
// Check if request has expired
if let Some(expires_at) = request.expires_at {
if u64::from(self.env().block_number()) > expires_at {
return Err(Error::RequestExpired);
}
}
// Check if already signed
if request.signatures.contains(&caller) {
return Err(Error::AlreadySigned);
}
// Add signature
request.signatures.push(caller);
// Update status based on approval and signatures collected
if !approve {
request.status = BridgeOperationStatus::Failed;
} else if request.signatures.len() >= request.required_signatures as usize {
request.status = BridgeOperationStatus::Locked;
}
self.bridge_requests.insert(request_id, &request);
self.env().emit_event(BridgeRequestSigned {
request_id,
signer: caller,
signatures_collected: request.signatures.len() as u8,
signatures_required: request.required_signatures,
});
Ok(())
}
/// Executes a bridge request after collecting required signatures
#[ink(message)]
pub fn execute_bridge(&mut self, request_id: u64) -> Result<(), Error> {
let caller = self.env().caller();
// Check if caller is a bridge operator
if !self.bridge_operators.contains(&caller) {
return Err(Error::Unauthorized);
}
let mut request = self
.bridge_requests
.get(request_id)
.ok_or(Error::InvalidRequest)?;
// Check if request is ready for execution
if request.status != BridgeOperationStatus::Locked {
return Err(Error::InvalidRequest);
}
// Check if enough signatures are collected
if request.signatures.len() < request.required_signatures as usize {
return Err(Error::InsufficientSignatures);
}
// Generate transaction hash
let transaction_hash = self.generate_transaction_hash(&request);
// Create bridge transaction record
self.transaction_counter += 1;
let transaction = BridgeTransaction {
transaction_id: self.transaction_counter,
token_id: request.token_id,
source_chain: request.source_chain,
destination_chain: request.destination_chain,
sender: request.sender,
recipient: request.recipient,
transaction_hash,
timestamp: self.env().block_timestamp(),
gas_used: self.estimate_gas_usage(&request),
status: BridgeOperationStatus::InTransit,
metadata: request.metadata.clone(),
};
// Update request status
request.status = BridgeOperationStatus::Completed;
self.bridge_requests.insert(request_id, &request);
// Store transaction verification
self.verified_transactions.insert(transaction_hash, &true);
// Add to bridge history
let mut history = self.bridge_history.get(request.sender).unwrap_or_default();
history.push(transaction.clone());
self.bridge_history.insert(request.sender, &history);
self.env().emit_event(BridgeExecuted {
request_id,
token_id: request.token_id,
transaction_hash,
});
Ok(())
}
/// Recovers from a failed bridge operation
#[ink(message)]
pub fn recover_failed_bridge(
&mut self,
request_id: u64,
recovery_action: RecoveryAction,
) -> Result<(), Error> {
let caller = self.env().caller();
// Only admin can recover failed bridges
if caller != self.admin {
return Err(Error::Unauthorized);
}
let mut request = self
.bridge_requests
.get(request_id)
.ok_or(Error::InvalidRequest)?;
// Check if request is in a failed state
if !matches!(
request.status,
BridgeOperationStatus::Failed | BridgeOperationStatus::Expired
) {
return Err(Error::InvalidRequest);
}
// Execute recovery action
match recovery_action {
RecoveryAction::UnlockToken => {
// Logic to unlock the token would be implemented here
// This would typically call back to the property token contract
}
RecoveryAction::RefundGas => {
// Logic to refund gas costs would be implemented here
}
RecoveryAction::RetryBridge => {
// Reset request to pending for retry
request.status = BridgeOperationStatus::Pending;
request.signatures.clear();
}
RecoveryAction::CancelBridge => {
// Mark as cancelled
request.status = BridgeOperationStatus::Failed;
}
}
self.bridge_requests.insert(request_id, &request);
self.env().emit_event(BridgeRecovered {
request_id,
recovery_action,
});
Ok(())
}
/// Gets gas estimation for a bridge operation
#[ink(message)]
pub fn estimate_bridge_gas(
&self,
_token_id: TokenId,
destination_chain: ChainId,
) -> Result<u64, Error> {
let chain_info = self
.chain_info
.get(destination_chain)
.ok_or(Error::InvalidChain)?;
let base_gas = self.config.gas_limit_per_bridge;
let multiplier = chain_info.gas_multiplier;
Ok(base_gas * multiplier as u64 / 100)
}
/// Monitors bridge status
#[ink(message)]
pub fn monitor_bridge_status(&self, request_id: u64) -> Option<BridgeMonitoringInfo> {
let request = self.bridge_requests.get(request_id)?;
Some(BridgeMonitoringInfo {
bridge_request_id: request.request_id,
token_id: request.token_id,
source_chain: request.source_chain,
destination_chain: request.destination_chain,
status: request.status,
created_at: request.created_at,
expires_at: request.expires_at,
signatures_collected: request.signatures.len() as u8,
signatures_required: request.required_signatures,
error_message: None,
})
}
/// Verifies a bridge transaction
#[ink(message)]
pub fn verify_bridge_transaction(
&self,
transaction_hash: Hash,
_source_chain: ChainId,
) -> bool {
self.verified_transactions
.get(transaction_hash)
.unwrap_or(false)
}
/// Gets bridge history for an account
#[ink(message)]
pub fn get_bridge_history(&self, account: AccountId) -> Vec<BridgeTransaction> {
self.bridge_history.get(account).unwrap_or_default()
}
/// Adds a bridge operator
#[ink(message)]
pub fn add_bridge_operator(&mut self, operator: AccountId) -> Result<(), Error> {
let caller = self.env().caller();
if caller != self.admin {
return Err(Error::Unauthorized);
}
if !self.bridge_operators.contains(&operator) {
self.bridge_operators.push(operator);
}
Ok(())
}
/// Removes a bridge operator
#[ink(message)]
pub fn remove_bridge_operator(&mut self, operator: AccountId) -> Result<(), Error> {
let caller = self.env().caller();
if caller != self.admin {
return Err(Error::Unauthorized);
}
self.bridge_operators.retain(|op| op != &operator);
Ok(())
}
/// Checks if an account is a bridge operator
#[ink(message)]
pub fn is_bridge_operator(&self, account: AccountId) -> bool {
self.bridge_operators.contains(&account)
}
/// Gets all bridge operators
#[ink(message)]
pub fn get_bridge_operators(&self) -> Vec<AccountId> {
self.bridge_operators.clone()
}
/// Updates bridge configuration (admin only)
#[ink(message)]
pub fn update_config(&mut self, config: BridgeConfig) -> Result<(), Error> {
let caller = self.env().caller();
if caller != self.admin {
return Err(Error::Unauthorized);
}
self.config = config;
Ok(())
}
/// Gets current bridge configuration
#[ink(message)]
pub fn get_config(&self) -> BridgeConfig {
self.config.clone()
}
/// Pauses or unpauses the bridge (admin only)
#[ink(message)]
pub fn set_emergency_pause(&mut self, paused: bool) -> Result<(), Error> {
let caller = self.env().caller();
if caller != self.admin {
return Err(Error::Unauthorized);
}
self.config.emergency_pause = paused;
Ok(())
}
/// Gets chain information
#[ink(message)]
pub fn get_chain_info(&self, chain_id: ChainId) -> Option<ChainBridgeInfo> {
self.chain_info.get(chain_id)
}
/// Updates chain information (admin only)
#[ink(message)]
pub fn update_chain_info(
&mut self,
chain_id: ChainId,
info: ChainBridgeInfo,
) -> Result<(), Error> {
let caller = self.env().caller();
if caller != self.admin {
return Err(Error::Unauthorized);
}
self.chain_info.insert(chain_id, &info);
Ok(())
}
// Helper functions
fn is_authorized_for_token(&self, _account: AccountId, _token_id: TokenId) -> bool {
// This would typically check with the property token contract
// For now, we'll assume any account can initiate a bridge
true
}
fn get_current_chain_id(&self) -> ChainId {
// This should return the current chain ID
// For now, we'll use a default value
1
}
fn generate_transaction_hash(&self, request: &MultisigBridgeRequest) -> Hash {
// Generate a unique transaction hash for the bridge request
use scale::Encode;
let data = (
request.request_id,
request.token_id,
request.source_chain,
request.destination_chain,
request.sender,
request.recipient,
self.env().block_timestamp(),
);
let encoded_data = data.encode();
// Simple hash: use first 32 bytes of encoded data
let mut hash_bytes = [0u8; 32];
let len = encoded_data.len().min(32);
hash_bytes[..len].copy_from_slice(&encoded_data[..len]);
Hash::from(hash_bytes)
}
fn estimate_gas_usage(&self, request: &MultisigBridgeRequest) -> u64 {
// Estimate gas usage based on request complexity
let base_gas = 100000; // Base gas for bridge operation
let metadata_gas = request.metadata.legal_description.len() as u64 * 100; // Gas for metadata
base_gas + metadata_gas
}
}
// Unit tests
#[cfg(test)]
mod tests {
use super::*;
use ink::env::{test, DefaultEnvironment};
fn setup_bridge() -> PropertyBridge {
let supported_chains = vec![1, 2, 3];
PropertyBridge::new(supported_chains, 2, 5, 100, 500000)
}
#[ink::test]
fn test_constructor_works() {
let bridge = setup_bridge();
let config = bridge.get_config();
assert_eq!(config.min_signatures_required, 2);
assert_eq!(config.max_signatures_required, 5);
}
#[ink::test]
fn test_initiate_bridge_multisig() {
let mut bridge = setup_bridge();
let accounts = test::default_accounts::<DefaultEnvironment>();
test::set_caller::<DefaultEnvironment>(accounts.alice);
let metadata = PropertyMetadata {
location: String::from("Test Property"),
size: 1000,
legal_description: String::from("Test"),
valuation: 100000,
documents_url: String::from("ipfs://test"),
};
let result = bridge.initiate_bridge_multisig(1, 2, accounts.bob, 2, Some(50), metadata);
assert!(result.is_ok());
}
#[ink::test]
fn test_sign_bridge_request() {
let mut bridge = setup_bridge();
let accounts = test::default_accounts::<DefaultEnvironment>();
// First create a request
test::set_caller::<DefaultEnvironment>(accounts.alice);
let metadata = PropertyMetadata {
location: String::from("Test Property"),
size: 1000,
legal_description: String::from("Test"),
valuation: 100000,
documents_url: String::from("ipfs://test"),
};
let request_id = bridge
.initiate_bridge_multisig(1, 2, accounts.bob, 2, Some(50), metadata)
.expect("Bridge initiation should succeed in test");
// Now sign it as a bridge operator
let accounts = test::default_accounts::<DefaultEnvironment>();
test::set_caller::<DefaultEnvironment>(accounts.alice); // Use default admin account
let result = bridge.sign_bridge_request(request_id, true);
assert!(result.is_ok());
}
}
}