blvm-node 0.1.16

Bitcoin Commons BLVM: Minimal Bitcoin node implementation using blvm-protocol and blvm-consensus
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
//! Module loader implementation
//!
//! Handles dynamic module loading, initialization, and configuration.
//! Includes cryptographic signature verification for signed modules.

use std::collections::HashMap;
use std::path::Path;
use tracing::{debug, info, warn};

use crate::module::manager::ModuleManager;
use crate::module::registry::discovery::DiscoveredModule;
use crate::module::security::signing::ModuleSigner;
use crate::module::traits::ModuleError;

/// Module loader for loading and initializing modules
pub struct ModuleLoader;

impl ModuleLoader {
    /// Load a discovered module
    pub async fn load_discovered_module(
        manager: &mut ModuleManager,
        discovered: &DiscoveredModule,
        config: HashMap<String, String>,
    ) -> Result<(), ModuleError> {
        info!("Loading module: {}", discovered.manifest.name);

        #[cfg(feature = "governance")]
        {
            let is_wasm =
                discovered.binary_path.extension().and_then(|s| s.to_str()) == Some("wasm");

            if !is_wasm {
                if let Some(registry_url) = manager.registry_url() {
                    let client = reqwest::Client::builder()
                        .timeout(std::time::Duration::from_secs(60))
                        .user_agent(concat!("blvm-node/", env!("CARGO_PKG_VERSION")))
                        .build()
                        .map_err(|e| ModuleError::op_err("Failed to build HTTP client", e))?;

                    match crate::module::github_release_install::try_fetch_expected_sha_for_native_module(
                        &client,
                        registry_url,
                        &discovered.manifest,
                    )
                    .await
                    {
                        Ok(expected_sha) => {
                            let binary_content = tokio::fs::read(&discovered.binary_path)
                                .await
                                .map_err(|e| {
                                    ModuleError::CryptoError(format!("Failed to read binary: {e}"))
                                })?;
                            use sha2::{Digest, Sha256};
                            let actual = hex::encode(Sha256::digest(&binary_content));
                            if actual != expected_sha {
                                return Err(ModuleError::OperationError(format!(
                                    "SHA256 mismatch for module '{}' (GitHub release checksums): expected {} got {}",
                                    discovered.manifest.name, expected_sha, actual
                                )));
                            }
                            info!(
                                "Module {} binary verified against GitHub release checksums",
                                discovered.manifest.name
                            );
                        }
                        Err(e) => {
                            if let Some(h) = discovered
                                .manifest
                                .binary
                                .as_ref()
                                .and_then(|b| b.hash.as_ref())
                            {
                                Self::verify_stored_binary_hash(
                                    &discovered.manifest,
                                    &discovered.binary_path,
                                    h,
                                )?;
                                warn!(
                                    "Module {}: could not fetch GitHub release checksums ({}); verified against module.toml [binary].hash",
                                    discovered.manifest.name, e
                                );
                            } else {
                                return Err(e);
                            }
                        }
                    }
                } else {
                    Self::verify_manifest_binary_hash_if_present(
                        &discovered.manifest,
                        &discovered.binary_path,
                    )?;
                }
            } else {
                Self::verify_manifest_binary_hash_if_present(
                    &discovered.manifest,
                    &discovered.binary_path,
                )?;
            }
        }

        #[cfg(not(feature = "governance"))]
        {
            Self::verify_manifest_binary_hash_if_present(
                &discovered.manifest,
                &discovered.binary_path,
            )?;
        }

        // Verify signatures if present
        if discovered.manifest.has_signatures() {
            debug!(
                "Module {} has signatures, verifying...",
                discovered.manifest.name
            );
            Self::verify_module_signatures(&discovered.manifest, &discovered.binary_path)?;
            info!("Module {} signatures verified", discovered.manifest.name);
        } else {
            warn!(
                "Module {} has no signatures - loading unsigned module (not recommended)",
                discovered.manifest.name
            );
        }

        let metadata = discovered.manifest.to_metadata();

        manager
            .load_module(
                &discovered.manifest.name,
                &discovered.binary_path,
                metadata,
                config,
            )
            .await
    }

    /// If the manifest declares `[binary].hash`, ensure the on-disk file matches.
    fn verify_manifest_binary_hash_if_present(
        manifest: &crate::module::registry::manifest::ModuleManifest,
        binary_path: &Path,
    ) -> Result<(), ModuleError> {
        if let Some(bin) = &manifest.binary {
            if let Some(h) = &bin.hash {
                Self::verify_stored_binary_hash(manifest, binary_path, h)?;
            }
        }
        Ok(())
    }

    fn verify_stored_binary_hash(
        manifest: &crate::module::registry::manifest::ModuleManifest,
        binary_path: &Path,
        expected_hex: &str,
    ) -> Result<(), ModuleError> {
        let binary_content = std::fs::read(binary_path)
            .map_err(|e| ModuleError::CryptoError(format!("Failed to read binary: {e}")))?;
        use sha2::{Digest, Sha256};
        let actual_hash = hex::encode(Sha256::digest(&binary_content));
        let expected_hash = expected_hex.trim_start_matches("sha256:").to_lowercase();
        if actual_hash != expected_hash {
            return Err(ModuleError::CryptoError(format!(
                "Binary hash mismatch for module {}: expected {}, got {}",
                manifest.name, expected_hex, actual_hash
            )));
        }
        debug!("Binary hash verified for module {}", manifest.name);
        Ok(())
    }

    /// Verify module signatures (manifest and binary)
    fn verify_module_signatures(
        manifest: &crate::module::registry::manifest::ModuleManifest,
        binary_path: &Path,
    ) -> Result<(), ModuleError> {
        let signer = ModuleSigner::new();

        // Verify manifest signatures
        if let Some(_sig_section) = &manifest.signatures {
            // Find manifest file (should be in the same directory as binary)
            let manifest_path = binary_path
                .parent()
                .ok_or_else(|| ModuleError::CryptoError("Binary path has no parent".to_string()))?
                .join("module.toml");

            // Read raw manifest content for signature verification
            // Note: We need to read the file before signatures are parsed out
            // For now, we'll read it and verify - in a full implementation,
            // we'd need to handle the signature section specially
            let manifest_content = std::fs::read_to_string(&manifest_path).map_err(|e| {
                ModuleError::CryptoError(format!("Failed to read manifest file: {e}"))
            })?;

            // Remove signature section from content for verification
            // (signatures are over the content without the signature section)
            // This is a simplified approach - in production, we'd need proper TOML manipulation
            let content_for_verification = Self::remove_signature_section(&manifest_content);

            let signatures = manifest.get_signatures();
            let public_keys = manifest.get_public_keys();
            let threshold = manifest.get_threshold().ok_or_else(|| {
                ModuleError::CryptoError("Signature threshold not specified".to_string())
            })?;

            let valid = signer.verify_manifest(
                content_for_verification.as_bytes(),
                &signatures,
                &public_keys,
                threshold,
            )?;

            if !valid {
                return Err(ModuleError::CryptoError(format!(
                    "Manifest signature verification failed for module {} (required {}-of-{})",
                    manifest.name, threshold.0, threshold.1
                )));
            }

            debug!("Manifest signatures verified for module {}", manifest.name);
        }

        // Verify binary hash and signatures if present
        if let Some(binary_section) = &manifest.binary {
            if binary_path.exists() {
                let binary_content = std::fs::read(binary_path)
                    .map_err(|e| ModuleError::CryptoError(format!("Failed to read binary: {e}")))?;

                // Verify binary hash if specified
                if let Some(expected_hash) = &binary_section.hash {
                    Self::verify_stored_binary_hash(manifest, binary_path, expected_hash)?;
                }

                // Verify binary signatures if present
                if let Some(_sig_section) = &manifest.signatures {
                    let signatures = manifest.get_signatures();
                    let public_keys = manifest.get_public_keys();
                    let threshold = manifest.get_threshold().ok_or_else(|| {
                        ModuleError::CryptoError("Signature threshold not specified".to_string())
                    })?;

                    let valid = signer.verify_binary(
                        &binary_content,
                        &signatures,
                        &public_keys,
                        threshold,
                    )?;

                    if !valid {
                        return Err(ModuleError::CryptoError(format!(
                            "Binary signature verification failed for module {} (required {}-of-{})",
                            manifest.name, threshold.0, threshold.1
                        )));
                    }

                    debug!("Binary signatures verified for module {}", manifest.name);
                }
            }
        }

        Ok(())
    }

    /// Load all modules in dependency order
    pub async fn load_modules_in_order(
        manager: &mut ModuleManager,
        discovered_modules: &[DiscoveredModule],
        load_order: &[String],
        module_configs: &HashMap<String, HashMap<String, String>>,
    ) -> Result<(), ModuleError> {
        for module_name in load_order {
            // Find the discovered module
            let discovered = discovered_modules
                .iter()
                .find(|m| m.manifest.name == *module_name)
                .ok_or_else(|| ModuleError::ModuleNotFound(module_name.clone()))?;

            // Get module config (or empty default)
            let config = module_configs.get(module_name).cloned().unwrap_or_default();

            // Load the module
            Self::load_discovered_module(manager, discovered, config).await?;
        }

        Ok(())
    }

    /// Load module configuration from file
    pub fn load_module_config<P: AsRef<Path>>(
        module_name: &str,
        config_path: P,
    ) -> Result<HashMap<String, String>, ModuleError> {
        if !config_path.as_ref().exists() {
            debug!("No config file for module {}, using defaults", module_name);
            return Ok(HashMap::new());
        }

        // Try TOML first
        if let Ok(contents) = std::fs::read_to_string(&config_path) {
            if let Ok(config) = toml::from_str::<HashMap<String, toml::Value>>(&contents) {
                // Convert TOML values to strings
                let mut string_config = HashMap::new();
                for (key, value) in config {
                    let value_str = match value {
                        toml::Value::String(s) => s,
                        toml::Value::Integer(i) => i.to_string(),
                        toml::Value::Float(f) => f.to_string(),
                        toml::Value::Boolean(b) => b.to_string(),
                        toml::Value::Array(arr) => arr
                            .iter()
                            .map(|v| v.to_string())
                            .collect::<Vec<_>>()
                            .join(","),
                        toml::Value::Table(map) => {
                            // Nested tables become dot-notation keys
                            let mut result = Vec::new();
                            for (subkey, subvalue) in map {
                                result.push(format!("{key}.{subkey}"));
                                result.push(subvalue.to_string());
                            }
                            result.join(",")
                        }
                        toml::Value::Datetime(dt) => dt.to_string(),
                    };
                    string_config.insert(key, value_str);
                }
                return Ok(string_config);
            }
        }

        // If TOML parsing failed, try simple key=value format
        let contents = std::fs::read_to_string(&config_path)
            .map_err(|e| ModuleError::op_err("Failed to read config file", e))?;

        let mut config = HashMap::new();
        for line in contents.lines() {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            if let Some((key, value)) = line.split_once('=') {
                config.insert(key.trim().to_string(), value.trim().to_string());
            }
        }

        Ok(config)
    }

    /// Flatten TOML value to string hashmap
    fn flatten_toml_value(
        prefix: String,
        value: &toml::Value,
        result: &mut HashMap<String, String>,
    ) {
        use toml::Value;

        match value {
            Value::String(s) => {
                if !prefix.is_empty() {
                    result.insert(prefix, s.clone());
                }
            }
            Value::Integer(i) => {
                result.insert(prefix, i.to_string());
            }
            Value::Float(f) => {
                result.insert(prefix, f.to_string());
            }
            Value::Boolean(b) => {
                result.insert(prefix, b.to_string());
            }
            Value::Array(arr) => {
                let values: Vec<String> = arr
                    .iter()
                    .map(|v| match v {
                        Value::String(s) => s.clone(),
                        _ => v.to_string(),
                    })
                    .collect();
                result.insert(prefix, values.join(","));
            }
            Value::Table(table) => {
                for (key, val) in table {
                    let new_prefix = if prefix.is_empty() {
                        key.clone()
                    } else {
                        format!("{prefix}.{key}")
                    };
                    Self::flatten_toml_value(new_prefix, val, result);
                }
            }
            Value::Datetime(dt) => {
                result.insert(prefix, dt.to_string());
            }
        }
    }

    /// Remove signature section from TOML content for verification
    ///
    /// Signatures are computed over the manifest content without the signature section itself.
    /// Uses line-based parsing to strip [signatures] and its key=value entries; sufficient for
    /// standard module manifests. Full TOML round-trip would preserve formatting.
    fn remove_signature_section(content: &str) -> String {
        let lines: Vec<&str> = content.lines().collect();
        let mut in_signatures = false;
        let mut result = Vec::new();

        for line in lines.iter() {
            let trimmed = line.trim();
            if trimmed == "[signatures]" {
                in_signatures = true;
                continue;
            }
            if in_signatures {
                if trimmed.starts_with('[') && trimmed.ends_with(']') {
                    // New section started
                    in_signatures = false;
                    result.push(*line);
                } else if trimmed.is_empty()
                    && result
                        .last()
                        .map(|l: &&str| l.trim().is_empty())
                        .unwrap_or(false)
                {
                    // Skip empty lines in signatures section
                    continue;
                } else if !trimmed.starts_with('#') && trimmed.contains('=') {
                    // Skip signature entries (key=value lines)
                    continue;
                } else {
                    // Keep other content
                    result.push(*line);
                }
            } else {
                result.push(*line);
            }
        }

        result.join("\n")
    }
}