Skip to main content

tenzro_types/
bridge.rs

1//! Cross-chain bridge types for Tenzro Network
2//!
3//! This module defines types for bridging assets between Tenzro Network
4//! and other blockchains.
5
6use crate::primitives::{Address, Hash, Timestamp};
7use serde::{Deserialize, Serialize};
8
9/// A message sent through the bridge
10#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
11pub struct BridgeMessage {
12    /// Message ID
13    pub message_id: String,
14    /// Source chain
15    pub source_chain: String,
16    /// Destination chain
17    pub destination_chain: String,
18    /// Sender address on source chain
19    pub sender: String,
20    /// Recipient address on destination chain
21    pub recipient: String,
22    /// Message payload
23    pub payload: Vec<u8>,
24    /// Message nonce
25    pub nonce: u64,
26    /// Message timestamp
27    pub timestamp: Timestamp,
28    /// Bridge protocol used
29    pub protocol: BridgeProtocol,
30    /// Message status
31    pub status: BridgeMessageStatus,
32}
33
34impl BridgeMessage {
35    /// Creates a new bridge message
36    pub fn new(
37        source_chain: String,
38        destination_chain: String,
39        sender: String,
40        recipient: String,
41        payload: Vec<u8>,
42        nonce: u64,
43        protocol: BridgeProtocol,
44    ) -> Self {
45        Self {
46            message_id: uuid::Uuid::new_v4().to_string(),
47            source_chain,
48            destination_chain,
49            sender,
50            recipient,
51            payload,
52            nonce,
53            timestamp: Timestamp::now(),
54            protocol,
55            status: BridgeMessageStatus::Pending,
56        }
57    }
58
59    /// Computes the message hash
60    pub fn hash(&self) -> Hash {
61        // In production, this would use a proper hashing algorithm
62        let json = serde_json::to_string(self).unwrap_or_default();
63        let mut hasher = [0u8; 32];
64        let bytes = json.as_bytes();
65        for (i, byte) in bytes.iter().enumerate().take(32) {
66            hasher[i % 32] ^= byte;
67        }
68        Hash::new(hasher)
69    }
70}
71
72/// Status of a bridge message
73#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
74pub enum BridgeMessageStatus {
75    /// Message is pending
76    Pending,
77    /// Message is being processed
78    Processing,
79    /// Message has been confirmed on source chain
80    SourceConfirmed,
81    /// Message is being relayed
82    Relaying,
83    /// Message has been delivered to destination
84    Delivered,
85    /// Message failed
86    Failed,
87    /// Message was refunded
88    Refunded,
89}
90
91/// Bridge protocol types
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
93pub enum BridgeProtocol {
94    /// Lock and mint protocol
95    LockAndMint,
96    /// Burn and mint protocol
97    BurnAndMint,
98    /// Liquidity pool protocol
99    LiquidityPool,
100    /// Atomic swap protocol
101    AtomicSwap,
102    /// Optimistic bridge protocol
103    Optimistic,
104    /// ZK proof bridge protocol
105    ZeroKnowledge,
106}
107
108impl BridgeProtocol {
109    /// Returns the protocol name
110    pub fn as_str(&self) -> &str {
111        match self {
112            Self::LockAndMint => "Lock and Mint",
113            Self::BurnAndMint => "Burn and Mint",
114            Self::LiquidityPool => "Liquidity Pool",
115            Self::AtomicSwap => "Atomic Swap",
116            Self::Optimistic => "Optimistic",
117            Self::ZeroKnowledge => "Zero Knowledge",
118        }
119    }
120}
121
122/// A cross-chain transfer via bridge
123#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
124pub struct BridgeTransfer {
125    /// Transfer ID
126    pub transfer_id: String,
127    /// Bridge message
128    pub message: BridgeMessage,
129    /// Asset being transferred
130    pub asset_id: String,
131    /// Amount being transferred
132    pub amount: u64,
133    /// Bridge fee (in source chain units)
134    pub bridge_fee: u64,
135    /// Relayer fee (in destination chain units)
136    pub relayer_fee: u64,
137    /// Source transaction hash
138    pub source_tx_hash: Option<Hash>,
139    /// Destination transaction hash
140    pub destination_tx_hash: Option<Hash>,
141    /// Transfer proof
142    pub proof: Option<BridgeProof>,
143    /// Transfer metadata
144    pub metadata: BridgeTransferMetadata,
145}
146
147impl BridgeTransfer {
148    /// Creates a new bridge transfer
149    pub fn new(
150        message: BridgeMessage,
151        asset_id: String,
152        amount: u64,
153        bridge_fee: u64,
154    ) -> Self {
155        Self {
156            transfer_id: uuid::Uuid::new_v4().to_string(),
157            message,
158            asset_id,
159            amount,
160            bridge_fee,
161            relayer_fee: 0,
162            source_tx_hash: None,
163            destination_tx_hash: None,
164            proof: None,
165            metadata: BridgeTransferMetadata::default(),
166        }
167    }
168
169    /// Sets the source transaction hash
170    pub fn with_source_tx(mut self, tx_hash: Hash) -> Self {
171        self.source_tx_hash = Some(tx_hash);
172        self
173    }
174
175    /// Sets the destination transaction hash
176    pub fn with_destination_tx(mut self, tx_hash: Hash) -> Self {
177        self.destination_tx_hash = Some(tx_hash);
178        self
179    }
180
181    /// Sets the transfer proof
182    pub fn with_proof(mut self, proof: BridgeProof) -> Self {
183        self.proof = Some(proof);
184        self
185    }
186}
187
188/// Metadata for bridge transfers
189#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
190pub struct BridgeTransferMetadata {
191    /// Number of confirmations on source chain
192    pub source_confirmations: u32,
193    /// Required confirmations
194    pub required_confirmations: u32,
195    /// Relayer address
196    pub relayer: Option<String>,
197    /// Challenge period end (for optimistic bridges)
198    pub challenge_period_end: Option<Timestamp>,
199    /// Additional metadata
200    pub extra: Option<Vec<u8>>,
201}
202
203/// Proof for a bridge transfer
204#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
205pub struct BridgeProof {
206    /// Proof type
207    pub proof_type: BridgeProofType,
208    /// Proof data
209    pub proof_data: Vec<u8>,
210    /// Validator signatures (if applicable)
211    pub signatures: Vec<ValidatorSignature>,
212}
213
214impl BridgeProof {
215    /// Creates a new bridge proof
216    pub fn new(proof_type: BridgeProofType, proof_data: Vec<u8>) -> Self {
217        Self {
218            proof_type,
219            proof_data,
220            signatures: Vec::new(),
221        }
222    }
223
224    /// Adds a validator signature
225    pub fn add_signature(&mut self, signature: ValidatorSignature) {
226        self.signatures.push(signature);
227    }
228}
229
230/// Type of bridge proof
231#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
232pub enum BridgeProofType {
233    /// Merkle proof
234    Merkle,
235    /// Multi-signature proof
236    MultiSig,
237    /// ZK proof
238    ZeroKnowledge,
239    /// Light client proof
240    LightClient,
241    /// Optimistic proof (challenge-based)
242    Optimistic,
243}
244
245/// A validator signature for bridge operations
246#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
247pub struct ValidatorSignature {
248    /// Validator address
249    pub validator: Address,
250    /// Signature bytes
251    pub signature: Vec<u8>,
252    /// Validator's voting power
253    pub voting_power: u128,
254    /// Signature timestamp
255    pub signed_at: Timestamp,
256}
257
258/// Bridge relay configuration
259#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
260pub struct BridgeRelayConfig {
261    /// Relayer address
262    pub relayer: Address,
263    /// Supported source chains
264    pub supported_source_chains: Vec<String>,
265    /// Supported destination chains
266    pub supported_destination_chains: Vec<String>,
267    /// Relayer fee (basis points)
268    pub relayer_fee_bps: u32,
269    /// Minimum transfer amount
270    pub min_transfer_amount: u64,
271    /// Maximum transfer amount
272    pub max_transfer_amount: u64,
273    /// Relayer status
274    pub status: RelayerStatus,
275}
276
277impl BridgeRelayConfig {
278    /// Creates a new bridge relay configuration
279    pub fn new(relayer: Address) -> Self {
280        Self {
281            relayer,
282            supported_source_chains: Vec::new(),
283            supported_destination_chains: Vec::new(),
284            relayer_fee_bps: 10, // 0.1%
285            min_transfer_amount: 1000,
286            max_transfer_amount: u64::MAX,
287            status: RelayerStatus::Active,
288        }
289    }
290
291    /// Adds a supported source chain
292    pub fn add_source_chain(&mut self, chain: String) {
293        if !self.supported_source_chains.contains(&chain) {
294            self.supported_source_chains.push(chain);
295        }
296    }
297
298    /// Adds a supported destination chain
299    pub fn add_destination_chain(&mut self, chain: String) {
300        if !self.supported_destination_chains.contains(&chain) {
301            self.supported_destination_chains.push(chain);
302        }
303    }
304
305    /// Checks if a route is supported
306    pub fn supports_route(&self, source: &str, destination: &str) -> bool {
307        self.supported_source_chains.iter().any(|c| c == source)
308            && self.supported_destination_chains.iter().any(|c| c == destination)
309    }
310}
311
312/// Relayer operational status
313#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
314pub enum RelayerStatus {
315    /// Relayer is active
316    Active,
317    /// Relayer is paused
318    Paused,
319    /// Relayer is suspended
320    Suspended,
321}