blvm-node 0.1.90

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
//! Resolve official module binaries from GitHub Releases.
//!
//! Bootstrap uses `registry/modules.json` **`repo`** (`owner/name`), the semantic
//! **`version`** from `module.toml`, and a **`sha256sums.txt`** asset attached to
//! the matching release tag (`v` + version). Download URLs are derived; hashes
//! come only from that checksum file (same as release CI publishes).

use crate::module::traits::ModuleError;

/// Tag name on GitHub (e.g. `v0.1.2`).
pub fn release_tag(version: &str) -> String {
    format!("v{}", version.trim())
}

/// Version of the artifact a constraint resolved to.
///
/// Module release jobs tag `v{version}` from the commit whose `module.toml`
/// still names the previous version, then push the bump onto the default
/// branch with `[skip ci]`. The tag file therefore lags the release. The
/// GitHub release version is the artifact; checksums on that tag are what
/// bootstrap verifies. An unpinned fetch keeps the manifest version.
pub fn manifest_version_for_release(toml_version: &str, release_version: Option<&str>) -> String {
    match release_version.map(str::trim).filter(|v| !v.is_empty()) {
        Some(release) if toml_version != release => release.to_string(),
        _ => toml_version.to_string(),
    }
}

/// Release artifact base name for the node platform key (e.g. `x86_64-linux`).
pub fn artifact_name(module_name: &str, platform: &str) -> Result<String, ModuleError> {
    let suffix = match platform {
        "x86_64-linux" => "-x86_64-linux",
        "aarch64-linux" => "-aarch64-linux",
        "x86_64-windows" => "-x86_64-windows.exe",
        "x86_64-apple" => "-x86_64-apple",
        "aarch64-apple" => "-aarch64-apple",
        _ => {
            return Err(ModuleError::OperationError(format!(
                "Unsupported platform for GitHub release bootstrap: {platform}"
            )));
        }
    };
    Ok(format!("{module_name}{suffix}"))
}

/// `https://github.com/{owner}/{repo}/releases/download/{tag}/{filename}`
pub fn release_download_url(github_repo: &str, tag: &str, filename: &str) -> String {
    format!("https://github.com/{github_repo}/releases/download/{tag}/{filename}")
}

/// Checksums file names to try (release workflows publish `sha256sums.txt`).
pub const CHECKSUM_FILENAMES: &[&str] = &["sha256sums.txt", "SHA256SUMS"];

/// Default Git ref for `module.toml` when the registry omits `module_toml_url` (repo-root convention).
pub const DEFAULT_MODULE_MANIFEST_REF: &str = "main";

/// Repositories for the modules `ModuleConfig::default()` enables.
/// Used when `modules.json` has not yet listed the name.
pub fn builtin_default_module_repo(name: &str) -> Option<&'static str> {
    match name {
        "blvm-miniscript" => Some("BTCDecoded/blvm-miniscript"),
        "blvm-zmq" => Some("BTCDecoded/blvm-zmq"),
        "blvm-index" => Some("BTCDecoded/blvm-index"),
        _ => None,
    }
}

/// Raw GitHub URL for `module.toml` at the repository root (`owner/name` + ref), like a `Cargo.toml` layout.
pub fn default_module_toml_raw_url(github_repo: &str, git_ref: &str) -> String {
    let github_repo = github_repo.trim();
    let git_ref = git_ref.trim();
    format!("https://raw.githubusercontent.com/{github_repo}/{git_ref}/module.toml")
}

/// Parse GNU `sha256sum` output for a single file name.
pub fn sha256_from_checksums(content: &str, filename: &str) -> Result<String, ModuleError> {
    let wanted = filename.trim();
    for raw in content.lines() {
        let line = raw.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let mut parts = line.split_whitespace();
        let hash = parts.next().ok_or_else(|| {
            ModuleError::OperationError("Invalid sha256sums line (no hash)".to_string())
        })?;
        if hash.len() != 64 || !hash.chars().all(|c| c.is_ascii_hexdigit()) {
            continue;
        }
        let path_field = parts.collect::<Vec<_>>().join(" ");
        if path_field.is_empty() {
            continue;
        }
        let path_field = path_field.strip_prefix('*').unwrap_or(&path_field);
        let base = std::path::Path::new(path_field)
            .file_name()
            .and_then(|s| s.to_str())
            .unwrap_or(path_field);
        if base == wanted || path_field == wanted || path_field.ends_with(wanted) {
            return Ok(hash.to_ascii_lowercase());
        }
    }
    Err(ModuleError::OperationError(format!(
        "No SHA256 line for '{wanted}' in checksums file"
    )))
}

/// `owner/repo` from registry index.
pub fn validate_github_repo(repo: &str) -> Result<(), ModuleError> {
    let repo = repo.trim();
    if repo.is_empty() {
        return Err(ModuleError::OperationError(
            "Registry entry missing non-empty `repo` (expected owner/repo)".to_string(),
        ));
    }
    let parts: Vec<&str> = repo.split('/').filter(|p| !p.is_empty()).collect();
    if parts.len() != 2 {
        return Err(ModuleError::OperationError(format!(
            "Registry `repo` must be `owner/name`, got: {repo}"
        )));
    }
    Ok(())
}

/// Host platform key for GitHub release artifacts (e.g. `x86_64-linux`).
#[cfg(feature = "governance")]
pub fn host_platform_key() -> Result<&'static str, ModuleError> {
    #[cfg(all(target_arch = "x86_64", target_os = "linux"))]
    {
        Ok("x86_64-linux")
    }
    #[cfg(all(target_arch = "aarch64", target_os = "linux"))]
    {
        Ok("aarch64-linux")
    }
    #[cfg(all(target_arch = "x86_64", target_os = "windows"))]
    {
        Ok("x86_64-windows")
    }
    #[cfg(all(target_arch = "x86_64", target_os = "macos"))]
    {
        Ok("x86_64-apple")
    }
    #[cfg(all(target_arch = "aarch64", target_os = "macos"))]
    {
        Ok("aarch64-apple")
    }
    #[cfg(not(any(
        all(target_arch = "x86_64", target_os = "linux"),
        all(target_arch = "aarch64", target_os = "linux"),
        all(target_arch = "x86_64", target_os = "windows"),
        all(target_arch = "x86_64", target_os = "macos"),
        all(target_arch = "aarch64", target_os = "macos"),
    )))]
    {
        Err(ModuleError::OperationError(
            "GitHub release layout is not supported on this host triple".to_string(),
        ))
    }
}

/// Look up `owner/name` for a module in the registry index (`modules.json`).
#[cfg(feature = "governance")]
pub async fn fetch_registry_github_repo(
    client: &reqwest::Client,
    registry_url: &str,
    module_name: &str,
) -> Result<String, ModuleError> {
    use serde::Deserialize;

    #[derive(Deserialize)]
    struct RegistryEntry {
        name: String,
        repo: String,
    }

    let resp = client
        .get(registry_url)
        .send()
        .await
        .map_err(|e| ModuleError::op_err("GET registry index failed", e))?;
    if !resp.status().is_success() {
        return Err(ModuleError::OperationError(format!(
            "GET {registry_url} returned HTTP {}",
            resp.status()
        )));
    }
    let bytes = resp
        .bytes()
        .await
        .map_err(|e| ModuleError::op_err("Reading registry body", e))?;
    let entries: Vec<RegistryEntry> = serde_json::from_slice(&bytes)
        .map_err(|e| ModuleError::op_err("Registry JSON parse failed", e))?;
    entries
        .into_iter()
        .find(|e| e.name == module_name)
        .map(|e| e.repo)
        .ok_or_else(|| {
            ModuleError::OperationError(format!(
                "Module '{module_name}' not found in registry at {registry_url}"
            ))
        })
}

/// List semver release versions (`tag_name` without leading `v`) from GitHub Releases JSON.
#[cfg(feature = "governance")]
pub fn parse_github_release_versions(json: &[u8]) -> Result<Vec<String>, ModuleError> {
    use serde::Deserialize;

    #[derive(Deserialize)]
    struct Release {
        tag_name: String,
        draft: bool,
        prerelease: bool,
    }

    let releases: Vec<Release> = serde_json::from_slice(json)
        .map_err(|e| ModuleError::op_err("GitHub releases JSON parse failed", e))?;

    let mut versions = Vec::new();
    for release in releases {
        if release.draft || release.prerelease {
            continue;
        }
        let version = release.tag_name.trim().trim_start_matches('v').to_string();
        if crate::module::version_constraint::parse_semver_triple(&version).is_some() {
            versions.push(version);
        }
    }
    Ok(versions)
}

/// List semver release versions (`tag_name` without leading `v`) from GitHub Releases.
#[cfg(feature = "governance")]
pub async fn fetch_github_release_versions(
    client: &reqwest::Client,
    github_repo: &str,
) -> Result<Vec<String>, ModuleError> {
    let url = format!("https://api.github.com/repos/{github_repo}/releases?per_page=100");
    let resp = client
        .get(&url)
        .header("Accept", "application/vnd.github+json")
        .send()
        .await
        .map_err(|e| ModuleError::op_err("GET GitHub releases failed", e))?;
    if !resp.status().is_success() {
        return Err(ModuleError::OperationError(format!(
            "GET {url} returned HTTP {}",
            resp.status()
        )));
    }
    let bytes = resp
        .bytes()
        .await
        .map_err(|e| ModuleError::op_err("Reading GitHub releases body", e))?;
    parse_github_release_versions(&bytes)
}

/// Resolve the highest GitHub release version matching a constraint (e.g. `0.1.*`).
#[cfg(feature = "governance")]
pub async fn resolve_release_version_for_constraint(
    client: &reqwest::Client,
    github_repo: &str,
    constraint: &str,
) -> Result<String, ModuleError> {
    let constraint = constraint.trim();
    if constraint.is_empty() || constraint == "*" {
        return Err(ModuleError::OperationError(
            "resolve_release_version_for_constraint requires a pinned constraint".to_string(),
        ));
    }
    let versions = fetch_github_release_versions(client, github_repo).await?;
    crate::module::version_constraint::select_highest_matching_version(&versions, constraint)
}

/// Download the release checksums file (`sha256sums.txt` or `SHA256SUMS`) as UTF-8 text.
#[cfg(feature = "governance")]
pub async fn fetch_release_checksums_text(
    client: &reqwest::Client,
    github_repo: &str,
    tag: &str,
) -> Result<String, ModuleError> {
    for cf in CHECKSUM_FILENAMES {
        let url = release_download_url(github_repo, tag, cf);
        let resp = client
            .get(&url)
            .send()
            .await
            .map_err(|e| ModuleError::op_err("GET checksums URL failed", e))?;
        if resp.status() == reqwest::StatusCode::NOT_FOUND {
            continue;
        }
        if !resp.status().is_success() {
            return Err(ModuleError::OperationError(format!(
                "GET {url} returned HTTP {}",
                resp.status()
            )));
        }
        let bytes = resp
            .bytes()
            .await
            .map_err(|e| ModuleError::op_err("Reading checksums body", e))?;
        return std::str::from_utf8(&bytes)
            .map(|s| s.to_string())
            .map_err(|e| ModuleError::op_err("Checksums file is not UTF-8", e));
    }
    Err(ModuleError::OperationError(format!(
        "No checksums file at GitHub release {tag} for {github_repo} (tried {CHECKSUM_FILENAMES:?})"
    )))
}

/// Expected SHA-256 (hex, lowercase) for this host's release artifact from `sha256sums.txt`.
#[cfg(feature = "governance")]
pub async fn try_fetch_expected_sha_for_native_module(
    client: &reqwest::Client,
    registry_url: &str,
    manifest: &crate::module::registry::manifest::ModuleManifest,
) -> Result<String, ModuleError> {
    let platform = host_platform_key()?;
    let artifact = artifact_name(&manifest.name, platform)?;
    let github_repo = fetch_registry_github_repo(client, registry_url, &manifest.name).await?;
    validate_github_repo(&github_repo)?;
    let tag = release_tag(&manifest.version);
    let checksum_text = fetch_release_checksums_text(client, &github_repo, &tag).await?;
    sha256_from_checksums(&checksum_text, &artifact)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn builtin_default_modules_have_repos() {
        assert_eq!(
            builtin_default_module_repo("blvm-miniscript"),
            Some("BTCDecoded/blvm-miniscript")
        );
        assert_eq!(
            builtin_default_module_repo("blvm-zmq"),
            Some("BTCDecoded/blvm-zmq")
        );
        assert_eq!(
            builtin_default_module_repo("blvm-index"),
            Some("BTCDecoded/blvm-index")
        );
        assert!(builtin_default_module_repo("blvm-payment").is_none());
    }

    #[test]
    fn sha256_from_checksums_finds_line() {
        let content = "7216f60f508ff0e82c161e902726deb81cfaba2ee0e10d08c4e0c2e893a9ec2e  blvm-fibre-x86_64-linux\n";
        assert_eq!(
            sha256_from_checksums(content, "blvm-fibre-x86_64-linux").unwrap(),
            "7216f60f508ff0e82c161e902726deb81cfaba2ee0e10d08c4e0c2e893a9ec2e"
        );
    }

    #[test]
    fn sha256_from_checksums_star_prefix() {
        let h = "a".repeat(64);
        let content = format!("{h} *foo-x86_64-linux\n");
        assert_eq!(
            sha256_from_checksums(&content, "foo-x86_64-linux").unwrap(),
            h
        );
    }

    #[test]
    fn release_tag_strips_no_extra_v() {
        assert_eq!(release_tag("0.1.2"), "v0.1.2");
    }

    #[test]
    fn lagged_tag_manifest_installs_as_the_release() {
        // v0.1.11's module.toml still says 0.1.10; main says 0.1.11.
        assert_eq!(
            manifest_version_for_release("0.1.10", Some("0.1.11")),
            "0.1.11"
        );
    }

    #[test]
    fn matching_manifest_keeps_its_version() {
        assert_eq!(
            manifest_version_for_release("0.1.11", Some("0.1.11")),
            "0.1.11"
        );
        assert_eq!(manifest_version_for_release("0.1.11", None), "0.1.11");
    }

    #[test]
    fn default_module_toml_raw_url_shape() {
        assert_eq!(
            default_module_toml_raw_url("Foo/bar", "main"),
            "https://raw.githubusercontent.com/Foo/bar/main/module.toml"
        );
    }

    #[cfg(feature = "governance")]
    #[test]
    fn parse_github_release_versions_skips_draft_prerelease_and_non_semver() {
        let json = br#"[
          {"tag_name":"v0.1.0","draft":false,"prerelease":false},
          {"tag_name":"v0.2.0","draft":true,"prerelease":false},
          {"tag_name":"v0.3.0-rc1","draft":false,"prerelease":true},
          {"tag_name":"not-a-version","draft":false,"prerelease":false},
          {"tag_name":"v0.1.5","draft":false,"prerelease":false}
        ]"#;
        let versions = parse_github_release_versions(json).unwrap();
        assert_eq!(versions, vec!["0.1.0".to_string(), "0.1.5".to_string()]);
    }

    #[cfg(feature = "governance")]
    #[test]
    fn resolve_release_version_for_constraint_picks_highest_patch() {
        let json = br#"[
          {"tag_name":"v0.1.0","draft":false,"prerelease":false},
          {"tag_name":"v0.1.5","draft":false,"prerelease":false},
          {"tag_name":"v0.2.0","draft":false,"prerelease":false}
        ]"#;
        let versions = parse_github_release_versions(json).unwrap();
        let picked =
            crate::module::version_constraint::select_highest_matching_version(&versions, "0.1.*")
                .unwrap();
        assert_eq!(picked, "0.1.5");
    }
}