anya_core/layer2/
mod.rs

1// [AIR-3][AIS-3][AIM-3][BPC-3][RES-3]
2//! Layer2 implementation for official Bitcoin Improvement Proposals (BIPs)
3//!
4//! This module implements Layer2 protocols for Bitcoin, following
5//! the hexagonal architecture pattern required by BDF v2.5.
6
7use serde::{Deserialize, Serialize};
8use std::error::Error;
9use std::sync::Arc;
10
11// async_trait is used in trait definitions below
12#[allow(unused_imports)]
13use async_trait::async_trait;
14
15/// Layer2 protocol types supported by the implementation
16#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
17pub enum Layer2ProtocolType {
18    Lightning,
19    StateChannels,
20    RGB,
21    DLC,
22    BOB,
23    Liquid,
24    RSK,
25    Stacks,
26    TaprootAssets,
27}
28
29/// Transaction status in a Layer2 protocol
30#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
31pub enum TransactionStatus {
32    Pending,
33    Confirmed,
34    Failed,
35    Rejected,
36}
37
38/// Protocol state for Layer2 implementations
39#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct ProtocolState {
41    pub version: String,
42    pub connections: u32,
43    pub capacity: Option<u64>,
44    pub operational: bool,
45    pub height: u64,
46    pub hash: String,
47    pub timestamp: u64,
48}
49
50impl Default for ProtocolState {
51    fn default() -> Self {
52        Self {
53            version: "1.0.0".to_string(),
54            connections: 0,
55            capacity: None,
56            operational: false,
57            height: 0,
58            hash: "default_hash".to_string(),
59            timestamp: std::time::SystemTime::now()
60                .duration_since(std::time::UNIX_EPOCH)
61                .unwrap_or_default()
62                .as_secs(),
63        }
64    }
65}
66
67/// Asset parameters for Layer2 protocols
68#[derive(Debug, Clone, Serialize, Deserialize)]
69pub struct AssetParams {
70    pub asset_id: String,
71    pub name: String,
72    pub symbol: String,
73    pub precision: u8,
74    pub decimals: u8,
75    pub total_supply: u64,
76    pub metadata: String,
77}
78
79/// Asset transfer parameters
80#[derive(Debug, Clone, Serialize, Deserialize)]
81pub struct AssetTransfer {
82    pub asset_id: String,
83    pub amount: u64,
84    pub from: String,
85    pub to: String,
86    pub recipient: String,
87    pub metadata: Option<String>,
88}
89
90/// Result of an asset transfer
91#[derive(Debug, Clone, Serialize, Deserialize)]
92pub struct TransferResult {
93    pub tx_id: String,
94    pub status: TransactionStatus,
95    pub fee: Option<u64>,
96    pub timestamp: u64,
97}
98
99impl Default for TransferResult {
100    fn default() -> Self {
101        Self {
102            tx_id: String::new(),
103            status: TransactionStatus::Pending,
104            fee: None,
105            timestamp: std::time::SystemTime::now()
106                .duration_since(std::time::UNIX_EPOCH)
107                .unwrap_or_default()
108                .as_secs(),
109        }
110    }
111}
112
113/// Proof for Layer2 operations
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct Proof {
116    pub proof_type: String,
117    pub data: Vec<u8>,
118    pub block_height: Option<u32>,
119    pub witness: Option<Vec<u8>>,
120    pub merkle_root: String,
121    pub merkle_proof: Vec<String>,
122    pub block_header: String,
123}
124
125impl Default for Proof {
126    fn default() -> Self {
127        Self {
128            proof_type: "default".to_string(),
129            data: Vec::new(),
130            block_height: None,
131            witness: None,
132            merkle_root: String::new(),
133            merkle_proof: Vec::new(),
134            block_header: String::new(),
135        }
136    }
137}
138
139/// Result of a verification operation
140#[derive(Debug, Clone, Serialize, Deserialize)]
141pub struct VerificationResult {
142    pub valid: bool,
143    pub is_valid: bool,
144    pub error: Option<String>,
145    pub timestamp: u64,
146}
147
148impl Default for VerificationResult {
149    fn default() -> Self {
150        Self {
151            valid: false,
152            is_valid: false,
153            error: None,
154            timestamp: std::time::SystemTime::now()
155                .duration_since(std::time::UNIX_EPOCH)
156                .unwrap_or_default()
157                .as_secs(),
158        }
159    }
160}
161
162/// Result of a validation operation
163#[derive(Debug, Clone, Serialize, Deserialize)]
164pub struct ValidationResult {
165    pub is_valid: bool,
166    pub violations: Vec<String>,
167    pub timestamp: u64,
168}
169
170impl Default for ValidationResult {
171    fn default() -> Self {
172        Self {
173            is_valid: false,
174            violations: Vec::new(),
175            timestamp: std::time::SystemTime::now()
176                .duration_since(std::time::UNIX_EPOCH)
177                .unwrap_or_default()
178                .as_secs(),
179        }
180    }
181}
182
183/// Legacy Layer2 protocol interface for synchronous implementations
184pub trait Layer2ProtocolTrait {
185    fn initialize(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
186    fn get_state(&self) -> Result<ProtocolState, Box<dyn std::error::Error + Send + Sync>>;
187    fn submit_transaction(
188        &self,
189        tx_data: &[u8],
190    ) -> Result<String, Box<dyn std::error::Error + Send + Sync>>;
191    fn check_transaction_status(
192        &self,
193        tx_id: &str,
194    ) -> Result<TransactionStatus, Box<dyn std::error::Error + Send + Sync>>;
195    fn sync_state(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
196    fn issue_asset(
197        &self,
198        params: AssetParams,
199    ) -> Result<String, Box<dyn std::error::Error + Send + Sync>>;
200    fn transfer_asset(
201        &self,
202        transfer: AssetTransfer,
203    ) -> Result<TransferResult, Box<dyn std::error::Error + Send + Sync>>;
204    fn verify_proof(
205        &self,
206        proof: Proof,
207    ) -> Result<VerificationResult, Box<dyn std::error::Error + Send + Sync>>;
208    fn validate_state(
209        &self,
210        state_data: &[u8],
211    ) -> Result<ValidationResult, Box<dyn std::error::Error + Send + Sync>>;
212}
213
214/// Modern Layer2 protocol interface (async trait for modern implementation)
215#[async_trait::async_trait]
216pub trait Layer2Protocol {
217    async fn initialize(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
218    async fn connect(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
219    async fn get_state(&self) -> Result<ProtocolState, Box<dyn std::error::Error + Send + Sync>>;
220    async fn submit_transaction(
221        &self,
222        tx_data: &[u8],
223    ) -> Result<String, Box<dyn std::error::Error + Send + Sync>>;
224    async fn check_transaction_status(
225        &self,
226        tx_id: &str,
227    ) -> Result<TransactionStatus, Box<dyn std::error::Error + Send + Sync>>;
228    async fn sync_state(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
229    async fn issue_asset(
230        &self,
231        params: AssetParams,
232    ) -> Result<String, Box<dyn std::error::Error + Send + Sync>>;
233    async fn transfer_asset(
234        &self,
235        transfer: AssetTransfer,
236    ) -> Result<TransferResult, Box<dyn std::error::Error + Send + Sync>>;
237    async fn verify_proof(
238        &self,
239        proof: Proof,
240    ) -> Result<VerificationResult, Box<dyn std::error::Error + Send + Sync>>;
241    async fn validate_state(
242        &self,
243        state_data: &[u8],
244    ) -> Result<ValidationResult, Box<dyn std::error::Error + Send + Sync>>;
245}
246
247// Add implementation for Arc<T> where T: Layer2ProtocolTrait
248impl<T> Layer2ProtocolTrait for Arc<T>
249where
250    T: Layer2ProtocolTrait + ?Sized,
251{
252    fn initialize(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
253        (**self).initialize()
254    }
255
256    fn get_state(&self) -> Result<ProtocolState, Box<dyn std::error::Error + Send + Sync>> {
257        (**self).get_state()
258    }
259
260    fn submit_transaction(
261        &self,
262        tx_data: &[u8],
263    ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
264        (**self).submit_transaction(tx_data)
265    }
266
267    fn check_transaction_status(
268        &self,
269        tx_id: &str,
270    ) -> Result<TransactionStatus, Box<dyn std::error::Error + Send + Sync>> {
271        (**self).check_transaction_status(tx_id)
272    }
273
274    fn sync_state(&mut self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
275        // This requires mutability, which Arc doesn't easily provide.
276        // We'll need to define a proper implementation or use interior mutability
277        // For now, let's return a sensible error
278        Err("Cannot sync_state on an Arc<T> directly. Use interior mutability like Arc<Mutex<T>> instead.".into())
279    }
280
281    fn issue_asset(
282        &self,
283        params: AssetParams,
284    ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
285        (**self).issue_asset(params)
286    }
287
288    fn transfer_asset(
289        &self,
290        transfer: AssetTransfer,
291    ) -> Result<TransferResult, Box<dyn std::error::Error + Send + Sync>> {
292        (**self).transfer_asset(transfer)
293    }
294
295    fn verify_proof(
296        &self,
297        proof: Proof,
298    ) -> Result<VerificationResult, Box<dyn std::error::Error + Send + Sync>> {
299        (**self).verify_proof(proof)
300    }
301
302    fn validate_state(
303        &self,
304        state_data: &[u8],
305    ) -> Result<ValidationResult, Box<dyn std::error::Error + Send + Sync>> {
306        (**self).validate_state(state_data)
307    }
308}
309
310// Layer2 protocol implementations
311pub mod bob;
312pub mod dlc;
313pub mod lightning;
314pub mod liquid;
315pub mod manager;
316pub mod mock;
317pub mod rgb;
318pub mod rsk;
319pub mod stacks;
320pub mod state_channels;
321pub mod taproot_assets;
322
323// Example function using Layer2ProtocolType instead of Layer2Protocol
324pub fn use_layer2_protocol(protocol: Layer2ProtocolType) {
325    match protocol {
326        Layer2ProtocolType::Lightning => println!("Using Lightning protocol"),
327        Layer2ProtocolType::StateChannels => println!("Using StateChannels protocol"),
328        Layer2ProtocolType::RGB => println!("Using RGB protocol"),
329        Layer2ProtocolType::DLC => println!("Using DLC protocol"),
330        Layer2ProtocolType::BOB => println!("Using BOB protocol"),
331        Layer2ProtocolType::Liquid => println!("Using Liquid protocol"),
332        Layer2ProtocolType::RSK => println!("Using RSK protocol"),
333        Layer2ProtocolType::Stacks => println!("Using Stacks protocol"),
334        Layer2ProtocolType::TaprootAssets => println!("Using TaprootAssets protocol"),
335    }
336}
337
338#[cfg(test)]
339pub mod comprehensive_tests;
340
341// Re-export key components
342pub use bob::BobClient;
343pub use lightning::LightningNetwork;
344pub use liquid::LiquidModule;
345pub use manager::Layer2Manager;
346pub use rsk::RskClient;
347pub use stacks::StacksClient;
348pub use state_channels::StateChannel;
349pub use taproot_assets::TaprootAssetsProtocol;
350
351// Re-export protocol implementations for tests
352pub use dlc::DlcProtocol;
353pub use lightning::LightningProtocol;
354pub use liquid::LiquidProtocol;
355pub use mock::MockLayer2Protocol;
356pub use rgb::RgbProtocol;
357pub use rsk::RskProtocol;
358pub use stacks::StacksProtocol;
359pub use state_channels::StateChannelsProtocol;
360
361// RGB Protocol trait implementation
362pub struct RGBProtocol {
363    pub version: String,
364    pub network: String,
365}
366
367// DLC Protocol trait implementation
368pub struct DiscreteLogContract {
369    pub version: String,
370    pub network: String,
371}
372
373/// Error types for Layer2 protocols
374#[derive(Debug)]
375pub enum Layer2Error {
376    General(String),
377    Connection(String),
378    Protocol(String),
379    Authentication(String),
380    Transaction(String),
381}
382
383impl std::fmt::Display for Layer2Error {
384    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
385        match self {
386            Layer2Error::General(msg) => write!(f, "Layer2 General Error: {msg}"),
387            Layer2Error::Connection(msg) => write!(f, "Layer2 Connection Error: {msg}"),
388            Layer2Error::Protocol(msg) => write!(f, "Layer2 Protocol Error: {msg}"),
389            Layer2Error::Authentication(msg) => write!(f, "Layer2 Authentication Error: {msg}"),
390            Layer2Error::Transaction(msg) => write!(f, "Layer2 Transaction Error: {msg}"),
391        }
392    }
393}
394
395impl Error for Layer2Error {}
396
397/// Helper function to create a default ProtocolState with all required fields
398pub fn create_protocol_state(
399    version: &str,
400    connections: u32,
401    capacity: Option<u64>,
402    operational: bool,
403) -> ProtocolState {
404    ProtocolState {
405        version: version.to_string(),
406        connections,
407        capacity,
408        operational,
409        height: 0,
410        hash: "default_hash".to_string(),
411        timestamp: std::time::SystemTime::now()
412            .duration_since(std::time::UNIX_EPOCH)
413            .unwrap_or_default()
414            .as_secs(),
415    }
416}
417
418/// Helper function to create a default VerificationResult
419pub fn create_verification_result(is_valid: bool, error: Option<String>) -> VerificationResult {
420    VerificationResult {
421        valid: is_valid,
422        is_valid,
423        error,
424        timestamp: std::time::SystemTime::now()
425            .duration_since(std::time::UNIX_EPOCH)
426            .unwrap_or_default()
427            .as_secs(),
428    }
429}
430
431/// Helper function to create a default ValidationResult
432pub fn create_validation_result(is_valid: bool, violations: Vec<String>) -> ValidationResult {
433    ValidationResult {
434        is_valid,
435        violations,
436        timestamp: std::time::SystemTime::now()
437            .duration_since(std::time::UNIX_EPOCH)
438            .unwrap_or_default()
439            .as_secs(),
440    }
441}