anya-core 1.2.0

Enterprise-grade Bitcoin Infrastructure Platform
Documentation
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
use std::collections::HashMap;

// This follows official Bitcoin Improvement Proposals (BIPs) standards for secure HSM implementation
use async_trait::async_trait;
use base64::Engine;
use std::str::FromStr;
use tokio::sync::Mutex;
use uuid::Uuid;

// Types from the HSM module
use crate::security::hsm::config::{HardwareConfig, HardwareDeviceType};
use crate::security::hsm::error::HsmError;
use crate::security::hsm::provider::{
    HsmOperation, HsmProvider, HsmProviderStatus, HsmRequest, HsmResponse, KeyGenParams, KeyInfo,
    KeyPair, KeyType, KeyUsage, SigningAlgorithm,
};
use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
use bitcoin::Network;
use bitcoin::{psbt::Psbt, Address};
use chrono::Utc;
use std::sync::Arc;

/// Hardware connection state
#[derive(Debug, Clone, PartialEq)]
enum ConnectionState {
    Disconnected,
    Connected,
    Authenticated,
}

/// Device information
#[derive(Debug, Clone)]
struct DeviceInfo;

/// Hardware HSM provider for physical security devices
#[derive(Debug)]
pub struct HardwareHsmProvider {
    config: HardwareConfig,
    device_info: Mutex<Option<DeviceInfo>>,
    connection_state: Mutex<ConnectionState>,
    keys: Mutex<HashMap<String, KeyInfo>>,
    network: Network,
    secp: Secp256k1<secp256k1::All>,
}

impl HardwareHsmProvider {
    /// Create a new hardware HSM provider
    pub async fn new(
        config: &HardwareConfig,
        network: Network,
        _audit_logger: Arc<crate::security::hsm::audit::AuditLogger>,
    ) -> Result<Self, HsmError> {
        Ok(Self {
            config: config.clone(),
            device_info: Mutex::new(None),
            connection_state: Mutex::new(ConnectionState::Disconnected),
            keys: Mutex::new(HashMap::new()),
            network, // Use the provided network
            secp: Secp256k1::new(),
        })
    }

    /// Generate a random key ID
    fn generate_key_id(&self) -> String {
        Uuid::new_v4().to_string()
    }

    /// Connect to hardware device
    async fn connect(&self) -> Result<(), HsmError> {
        let mut state = self.connection_state.lock().await;

        if *state == ConnectionState::Connected || *state == ConnectionState::Authenticated {
            return Ok(());
        }

        // Simulate connection based on device type
        let device_info = DeviceInfo;

        // Update device info and state
        *state = ConnectionState::Connected;
        let mut device_info_lock = self.device_info.lock().await;
        *device_info_lock = Some(device_info);

        tracing::info!(
            "Connected to hardware HSM device: {:?}",
            self.config.device_type
        );
        Ok(())
    }

    /// Authenticate with the hardware device
    async fn authenticate(&self) -> Result<(), HsmError> {
        let mut state = self.connection_state.lock().await;

        if *state == ConnectionState::Authenticated {
            return Ok(());
        }

        if *state == ConnectionState::Disconnected {
            drop(state);
            self.connect().await?;
            state = self.connection_state.lock().await;
        }

        // Authenticate based on device type using provided credentials
        match self.config.device_type {
            HardwareDeviceType::YubiHsm => {
                if self.config.auth_key_id.is_none() {
                    return Err(HsmError::AuthenticationError(
                        "Authentication key ID required for YubiHSM".to_string(),
                    ));
                }
            }
            HardwareDeviceType::Ledger | HardwareDeviceType::TrezorModel => {
                // These devices typically use interactive authentication
                tracing::info!("Please confirm operation on your device");
            }
            HardwareDeviceType::Custom => {
                if self.config.password.is_none() {
                    return Err(HsmError::AuthenticationError(
                        "Password required for custom HSM".to_string(),
                    ));
                }
            }
        }

        *state = ConnectionState::Authenticated;
        tracing::info!("Authenticated with hardware HSM device");

        Ok(())
    }

    /// Ensure the device is connected and authenticated
    async fn ensure_authenticated(&self) -> Result<(), HsmError> {
        let state = self.connection_state.lock().await;

        match *state {
            ConnectionState::Disconnected => {
                drop(state);
                self.connect().await?;
                self.authenticate().await?;
            }
            ConnectionState::Connected => {
                drop(state);
                self.authenticate().await?;
            }
            ConnectionState::Authenticated => {}
        }

        Ok(())
    }

    /// Generate Bitcoin key for testnet on hardware device
    async fn generate_bitcoin_key(&self, params: &KeyGenParams) -> Result<KeyPair, HsmError> {
        self.ensure_authenticated().await?;

        // Real hardware would do this on the device
        // For simulation, we'll create a testnet Bitcoin key
        let secret_key = SecretKey::new(&mut rand::thread_rng());
        let public_key = PublicKey::from_secret_key(&self.secp, &secret_key);

        // Convert to CompressedPublicKey for Bitcoin address generation
        let compressed_pubkey = bitcoin::key::CompressedPublicKey::from_private_key(
            &self.secp,
            &bitcoin::PrivateKey::new(secret_key, self.network),
        )
        .map_err(|e| {
            HsmError::KeyGenerationError(format!("Failed to create compressed public key: {}", e))
        })?;

        // Generate testnet address
        let address = Address::p2wpkh(&compressed_pubkey, self.network);

        tracing::info!("Generated new testnet address on hardware: {}", address);

        // In a real hardware implementation, we wouldn't have access to the private key material
        // It would remain on the device
        let key_id = params.id.clone().unwrap_or_else(|| self.generate_key_id());

        // Store key info but not the private key (hardware keeps it)
        let key_info = KeyInfo {
            id: key_id.clone(),
            label: params.label.clone(),
            key_type: params.key_type.clone(),
            extractable: false, // Hardware keys are never extractable
            usages: params.usages.clone(),
            created_at: Utc::now(),
            expires_at: params.expires_at,
            attributes: params.attributes.clone(),
        };

        let mut keys = self.keys.lock().await;
        keys.insert(key_id.clone(), key_info);

        Ok(KeyPair {
            id: key_id.clone(),
            key_type: params.key_type.clone(),
            public_key: public_key.serialize().to_vec(),
            private_key_handle: key_id,
        })
    }

    /// Sign Bitcoin transaction for testnet using hardware device
    async fn sign_bitcoin_transaction(&self, key_id: &str, tx: &mut Psbt) -> Result<(), HsmError> {
        self.ensure_authenticated().await?;

        // Get key info
        let keys = self.keys.lock().await;
        let key_info = keys
            .get(key_id)
            .ok_or_else(|| HsmError::KeyNotFound(key_id.to_string()))?;

        if !key_info.usages.contains(&KeyUsage::Sign) {
            return Err(HsmError::PermissionDenied(
                "Key does not have signing permission".to_string(),
            ));
        }

        // In a real implementation, we would:
        // 1. Send the PSBT to the hardware device
        // 2. Have the device sign it internally
        // 3. Return the signed PSBT

        // For simulation, we'll log what would happen
        tracing::info!("Hardware device would sign Bitcoin transaction");
        tracing::info!(
            "Transaction has {} inputs and {} outputs",
            tx.inputs.len(),
            tx.outputs.len()
        );

        // Simulate confirmation on device
        tracing::info!("Please confirm transaction on your hardware device");

        // Since we can't actually sign (no access to private key), we'll return success
        // In real implementation, this would be correctly signed by the device

        Ok(())
    }
}

#[async_trait]
impl HsmProvider for HardwareHsmProvider {
    async fn initialize(&self) -> Result<(), HsmError> {
        // Connect to the hardware device
        self.connect().await?;
        tracing::info!("Initialized hardware HSM for testnet operations");
        Ok(())
    }

    async fn generate_key(&self, params: KeyGenParams) -> Result<(KeyPair, KeyInfo), HsmError> {
        match &params.key_type {
            KeyType::Ec { curve }
                if *curve == crate::security::hsm::provider::EcCurve::Secp256k1 =>
            {
                let key_pair = self.generate_bitcoin_key(&params).await?;

                // Create KeyInfo for the generated key
                let key_info = KeyInfo {
                    id: params.id.unwrap_or_else(|| self.generate_key_id()),
                    label: params.label.clone(),
                    key_type: params.key_type.clone(),
                    usages: params.usages.clone(),
                    extractable: params.extractable,
                    expires_at: params.expires_at,
                    created_at: chrono::Utc::now(),
                    attributes: params.attributes.clone(),
                };

                Ok((key_pair, key_info))
            }
            _ => Err(HsmError::UnsupportedKeyType),
        }
    }

    async fn sign(
        &self,
        key_id: &str,
        _algorithm: SigningAlgorithm,
        data: &[u8],
    ) -> Result<Vec<u8>, HsmError> {
        self.ensure_authenticated().await?;

        // Get key info
        let keys = self.keys.lock().await;
        let key_info = keys
            .get(key_id)
            .ok_or_else(|| HsmError::KeyNotFound(key_id.to_string()))?;

        if !key_info.usages.contains(&KeyUsage::Sign) {
            return Err(HsmError::PermissionDenied(
                "Key does not have signing permission".to_string(),
            ));
        }

        // In a real implementation, the signing would be done on the device
        // For simulation, we'll return a dummy signature
        tracing::info!("Hardware device would sign data of length {}", data.len());

        // Simulate a DER-encoded ECDSA signature
        Ok(vec![
            0x30, 0x44, 0x02, 0x20, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
            0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
            0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x02, 0x20, 0x21, 0x22, 0x23, 0x24,
            0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32,
            0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40,
        ])
    }

    async fn verify(
        &self,
        key_id: &str,
        _algorithm: SigningAlgorithm,
        data: &[u8],
        _signature: &[u8],
    ) -> Result<bool, HsmError> {
        self.ensure_authenticated().await?;

        // Get key info
        let keys = self.keys.lock().await;
        let key_info = keys
            .get(key_id)
            .ok_or_else(|| HsmError::KeyNotFound(key_id.to_string()))?;

        if !key_info.usages.contains(&KeyUsage::Verify) {
            return Err(HsmError::PermissionDenied(
                "Key does not have verify permission".to_string(),
            ));
        }

        // In a real implementation, verification could be done on the device
        // For simulation, we'll just log and return true
        tracing::info!(
            "Hardware device would verify signature for data of length {}",
            data.len()
        );

        Ok(true)
    }

    async fn export_public_key(&self, key_id: &str) -> Result<Vec<u8>, HsmError> {
        self.ensure_authenticated().await?;

        // Get key info
        let keys = self.keys.lock().await;
        let key_info = keys
            .get(key_id)
            .ok_or_else(|| HsmError::KeyNotFound(key_id.to_string()))?;

        // In a real implementation, we would request the public key from the device
        // For simulation, return a dummy public key
        tracing::info!(
            "Hardware device would export public key for key ID: {}",
            key_id
        );

        // Return a dummy compressed public key (33 bytes)
        Ok(vec![
            0x02, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
            0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
            0x1c, 0x1d, 0x1e, 0x1f, 0x20,
        ])
    }

    async fn list_keys(&self) -> Result<Vec<KeyInfo>, HsmError> {
        self.ensure_authenticated().await?;

        let keys = self.keys.lock().await;
        Ok(keys.values().cloned().collect())
    }

    async fn delete_key(&self, key_id: &str) -> Result<(), HsmError> {
        self.ensure_authenticated().await?;

        let mut keys = self.keys.lock().await;

        if keys.remove(key_id).is_none() {
            return Err(HsmError::KeyNotFound(key_id.to_string()));
        }

        tracing::info!("Deleted key {} from hardware device", key_id);
        Ok(())
    }

    async fn get_status(&self) -> Result<HsmProviderStatus, HsmError> {
        let state = self.connection_state.lock().await;

        match *state {
            ConnectionState::Disconnected => Ok(HsmProviderStatus::Unavailable),
            ConnectionState::Connected => Ok(HsmProviderStatus::NeedsAuthentication),
            ConnectionState::Authenticated => Ok(HsmProviderStatus::Ready),
        }
    }

    async fn close(&self) -> Result<(), HsmError> {
        let mut state = self.connection_state.lock().await;
        *state = ConnectionState::Disconnected;

        tracing::info!("Closed connection to hardware HSM device");
        Ok(())
    }

    async fn execute_operation(&self, request: HsmRequest) -> Result<HsmResponse, HsmError> {
        match request.operation {
            HsmOperation::GenerateKey => {
                let params: KeyGenParams = serde_json::from_value(request.parameters.clone())
                    .map_err(|e| {
                        HsmError::InvalidParameters(format!(
                            "Invalid key generation parameters: {}",
                            e
                        ))
                    })?;

                let key_pair = self.generate_key(params).await?;
                let response_data = serde_json::to_value(key_pair)
                    .map_err(|e| HsmError::SerializationError(e.to_string()))?;

                Ok(HsmResponse::success(request.id, Some(response_data)))
            }
            HsmOperation::Sign => {
                let params: SignParams = serde_json::from_value(request.parameters.clone())
                    .map_err(|e| {
                        HsmError::InvalidParameters(format!("Invalid signing parameters: {}", e))
                    })?;

                // [AIR-3][AIS-3][BPC-3][RES-3] Sign data using hardware HSM
                let signature = self
                    .sign(&params.key_id, params._algorithm, &params.data)
                    .await?;
                // [AIR-3][AIS-3][BPC-3][RES-3] Use base64 Engine for encoding
                // This follows official Bitcoin Improvement Proposals (BIPs) standards for secure data handling
                let response_data = serde_json::to_value(Base64SignatureResponse {
                    signature: base64::engine::general_purpose::STANDARD.encode(&signature),
                    _algorithm: params._algorithm,
                })
                .map_err(|e| HsmError::SerializationError(e.to_string()))?;

                Ok(HsmResponse::success(request.id, Some(response_data)))
            }
            HsmOperation::Custom(op) if op == "sign_bitcoin_tx" => {
                let params: BitcoinTxSignParams =
                    serde_json::from_value(request.parameters.clone()).map_err(|e| {
                        HsmError::InvalidParameters(format!(
                            "Invalid Bitcoin TX signing parameters: {}",
                            e
                        ))
                    })?;

                // Decode PSBT
                let mut psbt = bitcoin::psbt::Psbt::from_str(&params.psbt)
                    .map_err(|e| HsmError::InvalidParameters(format!("Invalid PSBT: {}", e)))?;

                // Sign the transaction
                self.sign_bitcoin_transaction(&params.key_id, &mut psbt)
                    .await?;

                // Return the signed PSBT
                let response_data = serde_json::json!({
                    "signed_psbt": psbt.to_string(),
                    "network": "testnet",
                });

                Ok(HsmResponse::success(request.id, Some(response_data)))
            }
            HsmOperation::Custom(op) if op == "connect" => {
                self.connect().await?;
                Ok(HsmResponse::success(request.id, None))
            }
            HsmOperation::Custom(op) if op == "authenticate" => {
                self.authenticate().await?;
                Ok(HsmResponse::success(request.id, None))
            }
            _ => Err(HsmError::UnsupportedOperation(format!(
                "{:?}",
                request.operation
            ))),
        }
    }
}

/// Parameters for signing operation
#[derive(Debug, serde::Deserialize)]
struct SignParams {
    key_id: String,
    _algorithm: SigningAlgorithm,
    data: Vec<u8>,
}

/// Parameters for Bitcoin transaction signing
#[derive(Debug, serde::Deserialize)]
struct BitcoinTxSignParams {
    key_id: String,
    psbt: String,
}

/// Response for signature in base64 format
#[derive(Debug, serde::Serialize)]
struct Base64SignatureResponse {
    signature: String,
    _algorithm: SigningAlgorithm,
}